three.js 805 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '52dev' };
  6. self.console = self.console || {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. self.Int32Array = self.Int32Array || Array;
  14. self.Float32Array = self.Float32Array || Array;
  15. // Shims for "startsWith", "endsWith", and "trim" for browsers where this is not yet implemented
  16. // not sure we should have this, or at least not have it here
  17. // http://stackoverflow.com/questions/646628/javascript-startswith
  18. // http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript
  19. // http://wiki.ecmascript.org/doku.php?id=harmony%3astring_extras
  20. String.prototype.startsWith = String.prototype.startsWith || function ( str ) {
  21. return this.slice( 0, str.length ) === str;
  22. };
  23. String.prototype.endsWith = String.prototype.endsWith || function ( str ) {
  24. var t = String( str );
  25. var index = this.lastIndexOf( t );
  26. return ( -1 < index && index ) === (this.length - t.length);
  27. };
  28. String.prototype.trim = String.prototype.trim || function () {
  29. return this.replace( /^\s+|\s+$/g, '' );
  30. };
  31. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  32. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  33. // requestAnimationFrame polyfill by Erik Möller
  34. // fixes from Paul Irish and Tino Zijdel
  35. ( function () {
  36. var lastTime = 0;
  37. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  38. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  39. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  40. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  41. }
  42. if ( window.requestAnimationFrame === undefined ) {
  43. window.requestAnimationFrame = function ( callback, element ) {
  44. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  45. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  46. lastTime = currTime + timeToCall;
  47. return id;
  48. };
  49. }
  50. window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
  51. }() );
  52. // MATERIAL CONSTANTS
  53. // side
  54. THREE.FrontSide = 0;
  55. THREE.BackSide = 1;
  56. THREE.DoubleSide = 2;
  57. // shading
  58. THREE.NoShading = 0;
  59. THREE.FlatShading = 1;
  60. THREE.SmoothShading = 2;
  61. // colors
  62. THREE.NoColors = 0;
  63. THREE.FaceColors = 1;
  64. THREE.VertexColors = 2;
  65. // blending modes
  66. THREE.NoBlending = 0;
  67. THREE.NormalBlending = 1;
  68. THREE.AdditiveBlending = 2;
  69. THREE.SubtractiveBlending = 3;
  70. THREE.MultiplyBlending = 4;
  71. THREE.CustomBlending = 5;
  72. // custom blending equations
  73. // (numbers start from 100 not to clash with other
  74. // mappings to OpenGL constants defined in Texture.js)
  75. THREE.AddEquation = 100;
  76. THREE.SubtractEquation = 101;
  77. THREE.ReverseSubtractEquation = 102;
  78. // custom blending destination factors
  79. THREE.ZeroFactor = 200;
  80. THREE.OneFactor = 201;
  81. THREE.SrcColorFactor = 202;
  82. THREE.OneMinusSrcColorFactor = 203;
  83. THREE.SrcAlphaFactor = 204;
  84. THREE.OneMinusSrcAlphaFactor = 205;
  85. THREE.DstAlphaFactor = 206;
  86. THREE.OneMinusDstAlphaFactor = 207;
  87. // custom blending source factors
  88. //THREE.ZeroFactor = 200;
  89. //THREE.OneFactor = 201;
  90. //THREE.SrcAlphaFactor = 204;
  91. //THREE.OneMinusSrcAlphaFactor = 205;
  92. //THREE.DstAlphaFactor = 206;
  93. //THREE.OneMinusDstAlphaFactor = 207;
  94. THREE.DstColorFactor = 208;
  95. THREE.OneMinusDstColorFactor = 209;
  96. THREE.SrcAlphaSaturateFactor = 210;
  97. // TEXTURE CONSTANTS
  98. THREE.MultiplyOperation = 0;
  99. THREE.MixOperation = 1;
  100. // Mapping modes
  101. THREE.UVMapping = function () {};
  102. THREE.CubeReflectionMapping = function () {};
  103. THREE.CubeRefractionMapping = function () {};
  104. THREE.SphericalReflectionMapping = function () {};
  105. THREE.SphericalRefractionMapping = function () {};
  106. // Wrapping modes
  107. THREE.RepeatWrapping = 1000;
  108. THREE.ClampToEdgeWrapping = 1001;
  109. THREE.MirroredRepeatWrapping = 1002;
  110. // Filters
  111. THREE.NearestFilter = 1003;
  112. THREE.NearestMipMapNearestFilter = 1004;
  113. THREE.NearestMipMapLinearFilter = 1005;
  114. THREE.LinearFilter = 1006;
  115. THREE.LinearMipMapNearestFilter = 1007;
  116. THREE.LinearMipMapLinearFilter = 1008;
  117. // Data types
  118. THREE.UnsignedByteType = 1009;
  119. THREE.ByteType = 1010;
  120. THREE.ShortType = 1011;
  121. THREE.UnsignedShortType = 1012;
  122. THREE.IntType = 1013;
  123. THREE.UnsignedIntType = 1014;
  124. THREE.FloatType = 1015;
  125. // Pixel types
  126. //THREE.UnsignedByteType = 1009;
  127. THREE.UnsignedShort4444Type = 1016;
  128. THREE.UnsignedShort5551Type = 1017;
  129. THREE.UnsignedShort565Type = 1018;
  130. // Pixel formats
  131. THREE.AlphaFormat = 1019;
  132. THREE.RGBFormat = 1020;
  133. THREE.RGBAFormat = 1021;
  134. THREE.LuminanceFormat = 1022;
  135. THREE.LuminanceAlphaFormat = 1023;
  136. // Compressed texture formats
  137. THREE.RGB_S3TC_DXT1_Format = 2001;
  138. THREE.RGBA_S3TC_DXT1_Format = 2002;
  139. THREE.RGBA_S3TC_DXT3_Format = 2003;
  140. THREE.RGBA_S3TC_DXT5_Format = 2004;
  141. /*
  142. // Potential future PVRTC compressed texture formats
  143. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  144. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  145. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  146. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  147. */
  148. /**
  149. * @author alteredq / http://alteredqualia.com/
  150. */
  151. THREE.Clock = function ( autoStart ) {
  152. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  153. this.startTime = 0;
  154. this.oldTime = 0;
  155. this.elapsedTime = 0;
  156. this.running = false;
  157. };
  158. THREE.Clock.prototype.start = function () {
  159. this.startTime = Date.now();
  160. this.oldTime = this.startTime;
  161. this.running = true;
  162. };
  163. THREE.Clock.prototype.stop = function () {
  164. this.getElapsedTime();
  165. this.running = false;
  166. };
  167. THREE.Clock.prototype.getElapsedTime = function () {
  168. this.elapsedTime += this.getDelta();
  169. return this.elapsedTime;
  170. };
  171. THREE.Clock.prototype.getDelta = function () {
  172. var diff = 0;
  173. if ( this.autoStart && ! this.running ) {
  174. this.start();
  175. }
  176. if ( this.running ) {
  177. var newTime = Date.now();
  178. diff = 0.001 * ( newTime - this.oldTime );
  179. this.oldTime = newTime;
  180. this.elapsedTime += diff;
  181. }
  182. return diff;
  183. };/**
  184. * @author mrdoob / http://mrdoob.com/
  185. */
  186. THREE.Color = function ( hex ) {
  187. if ( hex !== undefined ) this.setHex( hex );
  188. return this;
  189. };
  190. THREE.Color.prototype = {
  191. constructor: THREE.Color,
  192. r: 1, g: 1, b: 1,
  193. copy: function ( color ) {
  194. this.r = color.r;
  195. this.g = color.g;
  196. this.b = color.b;
  197. return this;
  198. },
  199. copyGammaToLinear: function ( color ) {
  200. this.r = color.r * color.r;
  201. this.g = color.g * color.g;
  202. this.b = color.b * color.b;
  203. return this;
  204. },
  205. copyLinearToGamma: function ( color ) {
  206. this.r = Math.sqrt( color.r );
  207. this.g = Math.sqrt( color.g );
  208. this.b = Math.sqrt( color.b );
  209. return this;
  210. },
  211. convertGammaToLinear: function () {
  212. var r = this.r, g = this.g, b = this.b;
  213. this.r = r * r;
  214. this.g = g * g;
  215. this.b = b * b;
  216. return this;
  217. },
  218. convertLinearToGamma: function () {
  219. this.r = Math.sqrt( this.r );
  220. this.g = Math.sqrt( this.g );
  221. this.b = Math.sqrt( this.b );
  222. return this;
  223. },
  224. setRGB: function ( r, g, b ) {
  225. this.r = r;
  226. this.g = g;
  227. this.b = b;
  228. return this;
  229. },
  230. setHSV: function ( h, s, v ) {
  231. // based on MochiKit implementation by Bob Ippolito
  232. // h,s,v ranges are < 0.0 - 1.0 >
  233. var i, f, p, q, t;
  234. if ( v === 0 ) {
  235. this.r = this.g = this.b = 0;
  236. } else {
  237. i = Math.floor( h * 6 );
  238. f = ( h * 6 ) - i;
  239. p = v * ( 1 - s );
  240. q = v * ( 1 - ( s * f ) );
  241. t = v * ( 1 - ( s * ( 1 - f ) ) );
  242. if ( i === 0 ) {
  243. this.r = v;
  244. this.g = t;
  245. this.b = p;
  246. } else if ( i === 1 ) {
  247. this.r = q;
  248. this.g = v;
  249. this.b = p;
  250. } else if ( i === 2 ) {
  251. this.r = p;
  252. this.g = v;
  253. this.b = t;
  254. } else if ( i === 3 ) {
  255. this.r = p;
  256. this.g = q;
  257. this.b = v;
  258. } else if ( i === 4 ) {
  259. this.r = t;
  260. this.g = p;
  261. this.b = v;
  262. } else if ( i === 5 ) {
  263. this.r = v;
  264. this.g = p;
  265. this.b = q;
  266. }
  267. }
  268. return this;
  269. },
  270. setHex: function ( hex ) {
  271. hex = Math.floor( hex );
  272. this.r = ( hex >> 16 & 255 ) / 255;
  273. this.g = ( hex >> 8 & 255 ) / 255;
  274. this.b = ( hex & 255 ) / 255;
  275. return this;
  276. },
  277. lerpSelf: function ( color, alpha ) {
  278. this.r += ( color.r - this.r ) * alpha;
  279. this.g += ( color.g - this.g ) * alpha;
  280. this.b += ( color.b - this.b ) * alpha;
  281. return this;
  282. },
  283. getHex: function () {
  284. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  285. },
  286. getContextStyle: function () {
  287. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  288. },
  289. clone: function () {
  290. return new THREE.Color().setRGB( this.r, this.g, this.b );
  291. }
  292. };
  293. /**
  294. * @author mrdoob / http://mrdoob.com/
  295. * @author philogb / http://blog.thejit.org/
  296. * @author egraether / http://egraether.com/
  297. * @author zz85 / http://www.lab4games.net/zz85/blog
  298. */
  299. THREE.Vector2 = function ( x, y ) {
  300. this.x = x || 0;
  301. this.y = y || 0;
  302. };
  303. THREE.Vector2.prototype = {
  304. constructor: THREE.Vector2,
  305. set: function ( x, y ) {
  306. this.x = x;
  307. this.y = y;
  308. return this;
  309. },
  310. copy: function ( v ) {
  311. this.x = v.x;
  312. this.y = v.y;
  313. return this;
  314. },
  315. add: function ( a, b ) {
  316. this.x = a.x + b.x;
  317. this.y = a.y + b.y;
  318. return this;
  319. },
  320. addSelf: function ( v ) {
  321. this.x += v.x;
  322. this.y += v.y;
  323. return this;
  324. },
  325. sub: function ( a, b ) {
  326. this.x = a.x - b.x;
  327. this.y = a.y - b.y;
  328. return this;
  329. },
  330. subSelf: function ( v ) {
  331. this.x -= v.x;
  332. this.y -= v.y;
  333. return this;
  334. },
  335. multiplyScalar: function ( s ) {
  336. this.x *= s;
  337. this.y *= s;
  338. return this;
  339. },
  340. divideScalar: function ( s ) {
  341. if ( s ) {
  342. this.x /= s;
  343. this.y /= s;
  344. } else {
  345. this.set( 0, 0 );
  346. }
  347. return this;
  348. },
  349. negate: function() {
  350. return this.multiplyScalar( - 1 );
  351. },
  352. dot: function ( v ) {
  353. return this.x * v.x + this.y * v.y;
  354. },
  355. lengthSq: function () {
  356. return this.x * this.x + this.y * this.y;
  357. },
  358. length: function () {
  359. return Math.sqrt( this.lengthSq() );
  360. },
  361. normalize: function () {
  362. return this.divideScalar( this.length() );
  363. },
  364. distanceTo: function ( v ) {
  365. return Math.sqrt( this.distanceToSquared( v ) );
  366. },
  367. distanceToSquared: function ( v ) {
  368. var dx = this.x - v.x, dy = this.y - v.y;
  369. return dx * dx + dy * dy;
  370. },
  371. setLength: function ( l ) {
  372. return this.normalize().multiplyScalar( l );
  373. },
  374. lerpSelf: function ( v, alpha ) {
  375. this.x += ( v.x - this.x ) * alpha;
  376. this.y += ( v.y - this.y ) * alpha;
  377. return this;
  378. },
  379. equals: function( v ) {
  380. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  381. },
  382. isZero: function ( v ) {
  383. return this.lengthSq() < ( v !== undefined ? v : 0.0001 );
  384. },
  385. clone: function () {
  386. return new THREE.Vector2( this.x, this.y );
  387. }
  388. };
  389. /**
  390. * @author mrdoob / http://mrdoob.com/
  391. * @author kile / http://kile.stravaganza.org/
  392. * @author philogb / http://blog.thejit.org/
  393. * @author mikael emtinger / http://gomo.se/
  394. * @author egraether / http://egraether.com/
  395. * @author WestLangley / http://github.com/WestLangley
  396. */
  397. THREE.Vector3 = function ( x, y, z ) {
  398. this.x = x || 0;
  399. this.y = y || 0;
  400. this.z = z || 0;
  401. };
  402. THREE.Vector3.prototype = {
  403. constructor: THREE.Vector3,
  404. set: function ( x, y, z ) {
  405. this.x = x;
  406. this.y = y;
  407. this.z = z;
  408. return this;
  409. },
  410. setX: function ( x ) {
  411. this.x = x;
  412. return this;
  413. },
  414. setY: function ( y ) {
  415. this.y = y;
  416. return this;
  417. },
  418. setZ: function ( z ) {
  419. this.z = z;
  420. return this;
  421. },
  422. copy: function ( v ) {
  423. this.x = v.x;
  424. this.y = v.y;
  425. this.z = v.z;
  426. return this;
  427. },
  428. add: function ( a, b ) {
  429. this.x = a.x + b.x;
  430. this.y = a.y + b.y;
  431. this.z = a.z + b.z;
  432. return this;
  433. },
  434. addSelf: function ( v ) {
  435. this.x += v.x;
  436. this.y += v.y;
  437. this.z += v.z;
  438. return this;
  439. },
  440. addScalar: function ( s ) {
  441. this.x += s;
  442. this.y += s;
  443. this.z += s;
  444. return this;
  445. },
  446. sub: function ( a, b ) {
  447. this.x = a.x - b.x;
  448. this.y = a.y - b.y;
  449. this.z = a.z - b.z;
  450. return this;
  451. },
  452. subSelf: function ( v ) {
  453. this.x -= v.x;
  454. this.y -= v.y;
  455. this.z -= v.z;
  456. return this;
  457. },
  458. multiply: function ( a, b ) {
  459. this.x = a.x * b.x;
  460. this.y = a.y * b.y;
  461. this.z = a.z * b.z;
  462. return this;
  463. },
  464. multiplySelf: function ( v ) {
  465. this.x *= v.x;
  466. this.y *= v.y;
  467. this.z *= v.z;
  468. return this;
  469. },
  470. multiplyScalar: function ( s ) {
  471. this.x *= s;
  472. this.y *= s;
  473. this.z *= s;
  474. return this;
  475. },
  476. divideSelf: function ( v ) {
  477. this.x /= v.x;
  478. this.y /= v.y;
  479. this.z /= v.z;
  480. return this;
  481. },
  482. divideScalar: function ( s ) {
  483. if ( s ) {
  484. this.x /= s;
  485. this.y /= s;
  486. this.z /= s;
  487. } else {
  488. this.x = 0;
  489. this.y = 0;
  490. this.z = 0;
  491. }
  492. return this;
  493. },
  494. negate: function() {
  495. return this.multiplyScalar( - 1 );
  496. },
  497. dot: function ( v ) {
  498. return this.x * v.x + this.y * v.y + this.z * v.z;
  499. },
  500. lengthSq: function () {
  501. return this.x * this.x + this.y * this.y + this.z * this.z;
  502. },
  503. length: function () {
  504. return Math.sqrt( this.lengthSq() );
  505. },
  506. lengthManhattan: function () {
  507. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  508. },
  509. normalize: function () {
  510. return this.divideScalar( this.length() );
  511. },
  512. setLength: function ( l ) {
  513. return this.normalize().multiplyScalar( l );
  514. },
  515. lerpSelf: function ( v, alpha ) {
  516. this.x += ( v.x - this.x ) * alpha;
  517. this.y += ( v.y - this.y ) * alpha;
  518. this.z += ( v.z - this.z ) * alpha;
  519. return this;
  520. },
  521. cross: function ( a, b ) {
  522. this.x = a.y * b.z - a.z * b.y;
  523. this.y = a.z * b.x - a.x * b.z;
  524. this.z = a.x * b.y - a.y * b.x;
  525. return this;
  526. },
  527. crossSelf: function ( v ) {
  528. var x = this.x, y = this.y, z = this.z;
  529. this.x = y * v.z - z * v.y;
  530. this.y = z * v.x - x * v.z;
  531. this.z = x * v.y - y * v.x;
  532. return this;
  533. },
  534. distanceTo: function ( v ) {
  535. return Math.sqrt( this.distanceToSquared( v ) );
  536. },
  537. distanceToSquared: function ( v ) {
  538. return new THREE.Vector3().sub( this, v ).lengthSq();
  539. },
  540. getPositionFromMatrix: function ( m ) {
  541. this.x = m.elements[12];
  542. this.y = m.elements[13];
  543. this.z = m.elements[14];
  544. return this;
  545. },
  546. setEulerFromRotationMatrix: function ( m, order ) {
  547. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  548. // clamp, to handle numerical problems
  549. function clamp( x ) {
  550. return Math.min( Math.max( x, -1 ), 1 );
  551. }
  552. var te = m.elements;
  553. var m11 = te[0], m12 = te[4], m13 = te[8];
  554. var m21 = te[1], m22 = te[5], m23 = te[9];
  555. var m31 = te[2], m32 = te[6], m33 = te[10];
  556. if ( order === undefined || order === 'XYZ' ) {
  557. this.y = Math.asin( clamp( m13 ) );
  558. if ( Math.abs( m13 ) < 0.99999 ) {
  559. this.x = Math.atan2( - m23, m33 );
  560. this.z = Math.atan2( - m12, m11 );
  561. } else {
  562. this.x = Math.atan2( m32, m22 );
  563. this.z = 0;
  564. }
  565. } else if ( order === 'YXZ' ) {
  566. this.x = Math.asin( - clamp( m23 ) );
  567. if ( Math.abs( m23 ) < 0.99999 ) {
  568. this.y = Math.atan2( m13, m33 );
  569. this.z = Math.atan2( m21, m22 );
  570. } else {
  571. this.y = Math.atan2( - m31, m11 );
  572. this.z = 0;
  573. }
  574. } else if ( order === 'ZXY' ) {
  575. this.x = Math.asin( clamp( m32 ) );
  576. if ( Math.abs( m32 ) < 0.99999 ) {
  577. this.y = Math.atan2( - m31, m33 );
  578. this.z = Math.atan2( - m12, m22 );
  579. } else {
  580. this.y = 0;
  581. this.z = Math.atan2( m21, m11 );
  582. }
  583. } else if ( order === 'ZYX' ) {
  584. this.y = Math.asin( - clamp( m31 ) );
  585. if ( Math.abs( m31 ) < 0.99999 ) {
  586. this.x = Math.atan2( m32, m33 );
  587. this.z = Math.atan2( m21, m11 );
  588. } else {
  589. this.x = 0;
  590. this.z = Math.atan2( - m12, m22 );
  591. }
  592. } else if ( order === 'YZX' ) {
  593. this.z = Math.asin( clamp( m21 ) );
  594. if ( Math.abs( m21 ) < 0.99999 ) {
  595. this.x = Math.atan2( - m23, m22 );
  596. this.y = Math.atan2( - m31, m11 );
  597. } else {
  598. this.x = 0;
  599. this.y = Math.atan2( m13, m33 );
  600. }
  601. } else if ( order === 'XZY' ) {
  602. this.z = Math.asin( - clamp( m12 ) );
  603. if ( Math.abs( m12 ) < 0.99999 ) {
  604. this.x = Math.atan2( m32, m22 );
  605. this.y = Math.atan2( m13, m11 );
  606. } else {
  607. this.x = Math.atan2( - m23, m33 );
  608. this.y = 0;
  609. }
  610. }
  611. return this;
  612. },
  613. setEulerFromQuaternion: function ( q, order ) {
  614. // q is assumed to be normalized
  615. // clamp, to handle numerical problems
  616. function clamp( x ) {
  617. return Math.min( Math.max( x, -1 ), 1 );
  618. }
  619. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  620. var sqx = q.x * q.x;
  621. var sqy = q.y * q.y;
  622. var sqz = q.z * q.z;
  623. var sqw = q.w * q.w;
  624. if ( order === undefined || order === 'XYZ' ) {
  625. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  626. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  627. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  628. } else if ( order === 'YXZ' ) {
  629. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  630. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  631. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  632. } else if ( order === 'ZXY' ) {
  633. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  634. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  635. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  636. } else if ( order === 'ZYX' ) {
  637. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  638. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  639. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  640. } else if ( order === 'YZX' ) {
  641. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  642. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  643. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  644. } else if ( order === 'XZY' ) {
  645. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  646. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  647. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  648. }
  649. return this;
  650. },
  651. getScaleFromMatrix: function ( m ) {
  652. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  653. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  654. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  655. this.x = sx;
  656. this.y = sy;
  657. this.z = sz;
  658. return this;
  659. },
  660. equals: function ( v ) {
  661. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  662. },
  663. isZero: function ( v ) {
  664. return this.lengthSq() < ( v !== undefined ? v : 0.0001 );
  665. },
  666. clone: function () {
  667. return new THREE.Vector3( this.x, this.y, this.z );
  668. }
  669. };
  670. /**
  671. * @author supereggbert / http://www.paulbrunt.co.uk/
  672. * @author philogb / http://blog.thejit.org/
  673. * @author mikael emtinger / http://gomo.se/
  674. * @author egraether / http://egraether.com/
  675. * @author WestLangley / http://github.com/WestLangley
  676. */
  677. THREE.Vector4 = function ( x, y, z, w ) {
  678. this.x = x || 0;
  679. this.y = y || 0;
  680. this.z = z || 0;
  681. this.w = ( w !== undefined ) ? w : 1;
  682. };
  683. THREE.Vector4.prototype = {
  684. constructor: THREE.Vector4,
  685. set: function ( x, y, z, w ) {
  686. this.x = x;
  687. this.y = y;
  688. this.z = z;
  689. this.w = w;
  690. return this;
  691. },
  692. copy: function ( v ) {
  693. this.x = v.x;
  694. this.y = v.y;
  695. this.z = v.z;
  696. this.w = ( v.w !== undefined ) ? v.w : 1;
  697. return this;
  698. },
  699. add: function ( a, b ) {
  700. this.x = a.x + b.x;
  701. this.y = a.y + b.y;
  702. this.z = a.z + b.z;
  703. this.w = a.w + b.w;
  704. return this;
  705. },
  706. addSelf: function ( v ) {
  707. this.x += v.x;
  708. this.y += v.y;
  709. this.z += v.z;
  710. this.w += v.w;
  711. return this;
  712. },
  713. sub: function ( a, b ) {
  714. this.x = a.x - b.x;
  715. this.y = a.y - b.y;
  716. this.z = a.z - b.z;
  717. this.w = a.w - b.w;
  718. return this;
  719. },
  720. subSelf: function ( v ) {
  721. this.x -= v.x;
  722. this.y -= v.y;
  723. this.z -= v.z;
  724. this.w -= v.w;
  725. return this;
  726. },
  727. multiplyScalar: function ( s ) {
  728. this.x *= s;
  729. this.y *= s;
  730. this.z *= s;
  731. this.w *= s;
  732. return this;
  733. },
  734. divideScalar: function ( s ) {
  735. if ( s ) {
  736. this.x /= s;
  737. this.y /= s;
  738. this.z /= s;
  739. this.w /= s;
  740. } else {
  741. this.x = 0;
  742. this.y = 0;
  743. this.z = 0;
  744. this.w = 1;
  745. }
  746. return this;
  747. },
  748. negate: function() {
  749. return this.multiplyScalar( -1 );
  750. },
  751. dot: function ( v ) {
  752. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  753. },
  754. lengthSq: function () {
  755. return this.dot( this );
  756. },
  757. length: function () {
  758. return Math.sqrt( this.lengthSq() );
  759. },
  760. lengthManhattan: function () {
  761. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  762. },
  763. normalize: function () {
  764. return this.divideScalar( this.length() );
  765. },
  766. setLength: function ( l ) {
  767. return this.normalize().multiplyScalar( l );
  768. },
  769. lerpSelf: function ( v, alpha ) {
  770. this.x += ( v.x - this.x ) * alpha;
  771. this.y += ( v.y - this.y ) * alpha;
  772. this.z += ( v.z - this.z ) * alpha;
  773. this.w += ( v.w - this.w ) * alpha;
  774. return this;
  775. },
  776. clone: function () {
  777. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  778. },
  779. setAxisAngleFromQuaternion: function ( q ) {
  780. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  781. // q is assumed to be normalized
  782. this.w = 2 * Math.acos( q.w );
  783. var s = Math.sqrt( 1 - q.w * q.w );
  784. if ( s < 0.0001 ) {
  785. this.x = 1;
  786. this.y = 0;
  787. this.z = 0;
  788. } else {
  789. this.x = q.x / s;
  790. this.y = q.y / s;
  791. this.z = q.z / s;
  792. }
  793. return this;
  794. },
  795. setAxisAngleFromRotationMatrix: function ( m ) {
  796. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  797. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  798. var angle, x, y, z, // variables for result
  799. epsilon = 0.01, // margin to allow for rounding errors
  800. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  801. te = m.elements,
  802. m11 = te[0], m12 = te[4], m13 = te[8],
  803. m21 = te[1], m22 = te[5], m23 = te[9],
  804. m31 = te[2], m32 = te[6], m33 = te[10];
  805. if ( ( Math.abs( m12 - m21 ) < epsilon )
  806. && ( Math.abs( m13 - m31 ) < epsilon )
  807. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  808. // singularity found
  809. // first check for identity matrix which must have +1 for all terms
  810. // in leading diagonal and zero in other terms
  811. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  812. && ( Math.abs( m13 + m31 ) < epsilon2 )
  813. && ( Math.abs( m23 + m32 ) < epsilon2 )
  814. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  815. // this singularity is identity matrix so angle = 0
  816. this.set( 1, 0, 0, 0 );
  817. return this; // zero angle, arbitrary axis
  818. }
  819. // otherwise this singularity is angle = 180
  820. angle = Math.PI;
  821. var xx = ( m11 + 1 ) / 2;
  822. var yy = ( m22 + 1 ) / 2;
  823. var zz = ( m33 + 1 ) / 2;
  824. var xy = ( m12 + m21 ) / 4;
  825. var xz = ( m13 + m31 ) / 4;
  826. var yz = ( m23 + m32 ) / 4;
  827. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  828. if ( xx < epsilon ) {
  829. x = 0;
  830. y = 0.707106781;
  831. z = 0.707106781;
  832. } else {
  833. x = Math.sqrt( xx );
  834. y = xy / x;
  835. z = xz / x;
  836. }
  837. } else if ( yy > zz ) { // m22 is the largest diagonal term
  838. if ( yy < epsilon ) {
  839. x = 0.707106781;
  840. y = 0;
  841. z = 0.707106781;
  842. } else {
  843. y = Math.sqrt( yy );
  844. x = xy / y;
  845. z = yz / y;
  846. }
  847. } else { // m33 is the largest diagonal term so base result on this
  848. if ( zz < epsilon ) {
  849. x = 0.707106781;
  850. y = 0.707106781;
  851. z = 0;
  852. } else {
  853. z = Math.sqrt( zz );
  854. x = xz / z;
  855. y = yz / z;
  856. }
  857. }
  858. this.set( x, y, z, angle );
  859. return this; // return 180 deg rotation
  860. }
  861. // as we have reached here there are no singularities so we can handle normally
  862. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  863. + ( m13 - m31 ) * ( m13 - m31 )
  864. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  865. if ( Math.abs( s ) < 0.001 ) s = 1;
  866. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  867. // caught by singularity test above, but I've left it in just in case
  868. this.x = ( m32 - m23 ) / s;
  869. this.y = ( m13 - m31 ) / s;
  870. this.z = ( m21 - m12 ) / s;
  871. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  872. return this;
  873. }
  874. };
  875. /**
  876. * @author alteredq / http://alteredqualia.com/
  877. */
  878. THREE.Matrix3 = function () {
  879. this.elements = new Float32Array(9);
  880. };
  881. THREE.Matrix3.prototype = {
  882. constructor: THREE.Matrix3,
  883. getInverse: function ( matrix ) {
  884. // input: THREE.Matrix4
  885. // ( based on http://code.google.com/p/webgl-mjs/ )
  886. var me = matrix.elements;
  887. var a11 = me[10] * me[5] - me[6] * me[9];
  888. var a21 = - me[10] * me[1] + me[2] * me[9];
  889. var a31 = me[6] * me[1] - me[2] * me[5];
  890. var a12 = - me[10] * me[4] + me[6] * me[8];
  891. var a22 = me[10] * me[0] - me[2] * me[8];
  892. var a32 = - me[6] * me[0] + me[2] * me[4];
  893. var a13 = me[9] * me[4] - me[5] * me[8];
  894. var a23 = - me[9] * me[0] + me[1] * me[8];
  895. var a33 = me[5] * me[0] - me[1] * me[4];
  896. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  897. // no inverse
  898. if ( det === 0 ) {
  899. console.warn( "Matrix3.getInverse(): determinant == 0" );
  900. }
  901. var idet = 1.0 / det;
  902. var m = this.elements;
  903. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  904. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  905. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  906. return this;
  907. },
  908. transpose: function () {
  909. var tmp, m = this.elements;
  910. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  911. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  912. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  913. return this;
  914. },
  915. transposeIntoArray: function ( r ) {
  916. var m = this.m;
  917. r[ 0 ] = m[ 0 ];
  918. r[ 1 ] = m[ 3 ];
  919. r[ 2 ] = m[ 6 ];
  920. r[ 3 ] = m[ 1 ];
  921. r[ 4 ] = m[ 4 ];
  922. r[ 5 ] = m[ 7 ];
  923. r[ 6 ] = m[ 2 ];
  924. r[ 7 ] = m[ 5 ];
  925. r[ 8 ] = m[ 8 ];
  926. return this;
  927. }
  928. };
  929. /**
  930. * @author mrdoob / http://mrdoob.com/
  931. * @author supereggbert / http://www.paulbrunt.co.uk/
  932. * @author philogb / http://blog.thejit.org/
  933. * @author jordi_ros / http://plattsoft.com
  934. * @author D1plo1d / http://github.com/D1plo1d
  935. * @author alteredq / http://alteredqualia.com/
  936. * @author mikael emtinger / http://gomo.se/
  937. * @author timknip / http://www.floorplanner.com/
  938. */
  939. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  940. this.elements = new Float32Array( 16 );
  941. this.set(
  942. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  943. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  944. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  945. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  946. );
  947. };
  948. THREE.Matrix4.prototype = {
  949. constructor: THREE.Matrix4,
  950. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  951. var te = this.elements;
  952. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  953. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  954. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  955. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  956. return this;
  957. },
  958. identity: function () {
  959. this.set(
  960. 1, 0, 0, 0,
  961. 0, 1, 0, 0,
  962. 0, 0, 1, 0,
  963. 0, 0, 0, 1
  964. );
  965. return this;
  966. },
  967. copy: function ( m ) {
  968. var me = m.elements;
  969. this.set(
  970. me[0], me[4], me[8], me[12],
  971. me[1], me[5], me[9], me[13],
  972. me[2], me[6], me[10], me[14],
  973. me[3], me[7], me[11], me[15]
  974. );
  975. return this;
  976. },
  977. lookAt: function ( eye, target, up ) {
  978. var te = this.elements;
  979. var x = THREE.Matrix4.__v1;
  980. var y = THREE.Matrix4.__v2;
  981. var z = THREE.Matrix4.__v3;
  982. z.sub( eye, target ).normalize();
  983. if ( z.length() === 0 ) {
  984. z.z = 1;
  985. }
  986. x.cross( up, z ).normalize();
  987. if ( x.length() === 0 ) {
  988. z.x += 0.0001;
  989. x.cross( up, z ).normalize();
  990. }
  991. y.cross( z, x );
  992. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  993. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  994. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  995. return this;
  996. },
  997. multiply: function ( a, b ) {
  998. var ae = a.elements;
  999. var be = b.elements;
  1000. var te = this.elements;
  1001. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1002. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1003. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1004. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1005. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1006. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1007. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1008. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1009. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1010. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1011. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1012. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1013. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1014. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1015. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1016. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1017. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1018. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1019. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1020. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1021. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1022. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1023. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1024. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1025. return this;
  1026. },
  1027. multiplySelf: function ( m ) {
  1028. return this.multiply( this, m );
  1029. },
  1030. multiplyToArray: function ( a, b, r ) {
  1031. var te = this.elements;
  1032. this.multiply( a, b );
  1033. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1034. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1035. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1036. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1037. return this;
  1038. },
  1039. multiplyScalar: function ( s ) {
  1040. var te = this.elements;
  1041. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1042. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1043. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1044. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1045. return this;
  1046. },
  1047. multiplyVector3: function ( v ) {
  1048. var te = this.elements;
  1049. var vx = v.x, vy = v.y, vz = v.z;
  1050. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1051. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1052. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1053. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1054. return v;
  1055. },
  1056. multiplyVector4: function ( v ) {
  1057. var te = this.elements;
  1058. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1059. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1060. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1061. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1062. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1063. return v;
  1064. },
  1065. multiplyVector3Array: function ( a ) {
  1066. var tmp = THREE.Matrix4.__v1;
  1067. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1068. tmp.x = a[ i ];
  1069. tmp.y = a[ i + 1 ];
  1070. tmp.z = a[ i + 2 ];
  1071. this.multiplyVector3( tmp );
  1072. a[ i ] = tmp.x;
  1073. a[ i + 1 ] = tmp.y;
  1074. a[ i + 2 ] = tmp.z;
  1075. }
  1076. return a;
  1077. },
  1078. rotateAxis: function ( v ) {
  1079. var te = this.elements;
  1080. var vx = v.x, vy = v.y, vz = v.z;
  1081. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1082. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1083. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1084. v.normalize();
  1085. return v;
  1086. },
  1087. crossVector: function ( a ) {
  1088. var te = this.elements;
  1089. var v = new THREE.Vector4();
  1090. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1091. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1092. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1093. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1094. return v;
  1095. },
  1096. determinant: function () {
  1097. var te = this.elements;
  1098. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1099. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1100. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1101. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1102. //TODO: make this more efficient
  1103. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1104. return (
  1105. n14 * n23 * n32 * n41-
  1106. n13 * n24 * n32 * n41-
  1107. n14 * n22 * n33 * n41+
  1108. n12 * n24 * n33 * n41+
  1109. n13 * n22 * n34 * n41-
  1110. n12 * n23 * n34 * n41-
  1111. n14 * n23 * n31 * n42+
  1112. n13 * n24 * n31 * n42+
  1113. n14 * n21 * n33 * n42-
  1114. n11 * n24 * n33 * n42-
  1115. n13 * n21 * n34 * n42+
  1116. n11 * n23 * n34 * n42+
  1117. n14 * n22 * n31 * n43-
  1118. n12 * n24 * n31 * n43-
  1119. n14 * n21 * n32 * n43+
  1120. n11 * n24 * n32 * n43+
  1121. n12 * n21 * n34 * n43-
  1122. n11 * n22 * n34 * n43-
  1123. n13 * n22 * n31 * n44+
  1124. n12 * n23 * n31 * n44+
  1125. n13 * n21 * n32 * n44-
  1126. n11 * n23 * n32 * n44-
  1127. n12 * n21 * n33 * n44+
  1128. n11 * n22 * n33 * n44
  1129. );
  1130. },
  1131. transpose: function () {
  1132. var te = this.elements;
  1133. var tmp;
  1134. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1135. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1136. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1137. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1138. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1139. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1140. return this;
  1141. },
  1142. flattenToArray: function ( flat ) {
  1143. var te = this.elements;
  1144. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1145. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1146. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1147. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1148. return flat;
  1149. },
  1150. flattenToArrayOffset: function( flat, offset ) {
  1151. var te = this.elements;
  1152. flat[ offset ] = te[0];
  1153. flat[ offset + 1 ] = te[1];
  1154. flat[ offset + 2 ] = te[2];
  1155. flat[ offset + 3 ] = te[3];
  1156. flat[ offset + 4 ] = te[4];
  1157. flat[ offset + 5 ] = te[5];
  1158. flat[ offset + 6 ] = te[6];
  1159. flat[ offset + 7 ] = te[7];
  1160. flat[ offset + 8 ] = te[8];
  1161. flat[ offset + 9 ] = te[9];
  1162. flat[ offset + 10 ] = te[10];
  1163. flat[ offset + 11 ] = te[11];
  1164. flat[ offset + 12 ] = te[12];
  1165. flat[ offset + 13 ] = te[13];
  1166. flat[ offset + 14 ] = te[14];
  1167. flat[ offset + 15 ] = te[15];
  1168. return flat;
  1169. },
  1170. getPosition: function () {
  1171. var te = this.elements;
  1172. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1173. },
  1174. setPosition: function ( v ) {
  1175. var te = this.elements;
  1176. te[12] = v.x;
  1177. te[13] = v.y;
  1178. te[14] = v.z;
  1179. return this;
  1180. },
  1181. getColumnX: function () {
  1182. var te = this.elements;
  1183. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1184. },
  1185. getColumnY: function () {
  1186. var te = this.elements;
  1187. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1188. },
  1189. getColumnZ: function() {
  1190. var te = this.elements;
  1191. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1192. },
  1193. getInverse: function ( m ) {
  1194. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1195. var te = this.elements;
  1196. var me = m.elements;
  1197. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1198. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1199. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1200. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1201. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1202. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1203. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1204. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1205. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1206. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1207. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1208. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1209. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1210. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1211. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1212. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1213. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1214. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1215. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1216. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1217. this.multiplyScalar( 1 / m.determinant() );
  1218. return this;
  1219. },
  1220. setRotationFromEuler: function ( v, order ) {
  1221. var te = this.elements;
  1222. var x = v.x, y = v.y, z = v.z;
  1223. var a = Math.cos( x ), b = Math.sin( x );
  1224. var c = Math.cos( y ), d = Math.sin( y );
  1225. var e = Math.cos( z ), f = Math.sin( z );
  1226. if ( order === undefined || order === 'XYZ' ) {
  1227. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1228. te[0] = c * e;
  1229. te[4] = - c * f;
  1230. te[8] = d;
  1231. te[1] = af + be * d;
  1232. te[5] = ae - bf * d;
  1233. te[9] = - b * c;
  1234. te[2] = bf - ae * d;
  1235. te[6] = be + af * d;
  1236. te[10] = a * c;
  1237. } else if ( order === 'YXZ' ) {
  1238. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1239. te[0] = ce + df * b;
  1240. te[4] = de * b - cf;
  1241. te[8] = a * d;
  1242. te[1] = a * f;
  1243. te[5] = a * e;
  1244. te[9] = - b;
  1245. te[2] = cf * b - de;
  1246. te[6] = df + ce * b;
  1247. te[10] = a * c;
  1248. } else if ( order === 'ZXY' ) {
  1249. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1250. te[0] = ce - df * b;
  1251. te[4] = - a * f;
  1252. te[8] = de + cf * b;
  1253. te[1] = cf + de * b;
  1254. te[5] = a * e;
  1255. te[9] = df - ce * b;
  1256. te[2] = - a * d;
  1257. te[6] = b;
  1258. te[10] = a * c;
  1259. } else if ( order === 'ZYX' ) {
  1260. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1261. te[0] = c * e;
  1262. te[4] = be * d - af;
  1263. te[8] = ae * d + bf;
  1264. te[1] = c * f;
  1265. te[5] = bf * d + ae;
  1266. te[9] = af * d - be;
  1267. te[2] = - d;
  1268. te[6] = b * c;
  1269. te[10] = a * c;
  1270. } else if ( order === 'YZX' ) {
  1271. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1272. te[0] = c * e;
  1273. te[4] = bd - ac * f;
  1274. te[8] = bc * f + ad;
  1275. te[1] = f;
  1276. te[5] = a * e;
  1277. te[9] = - b * e;
  1278. te[2] = - d * e;
  1279. te[6] = ad * f + bc;
  1280. te[10] = ac - bd * f;
  1281. } else if ( order === 'XZY' ) {
  1282. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1283. te[0] = c * e;
  1284. te[4] = - f;
  1285. te[8] = d * e;
  1286. te[1] = ac * f + bd;
  1287. te[5] = a * e;
  1288. te[9] = ad * f - bc;
  1289. te[2] = bc * f - ad;
  1290. te[6] = b * e;
  1291. te[10] = bd * f + ac;
  1292. }
  1293. return this;
  1294. },
  1295. setRotationFromQuaternion: function ( q ) {
  1296. var te = this.elements;
  1297. var x = q.x, y = q.y, z = q.z, w = q.w;
  1298. var x2 = x + x, y2 = y + y, z2 = z + z;
  1299. var xx = x * x2, xy = x * y2, xz = x * z2;
  1300. var yy = y * y2, yz = y * z2, zz = z * z2;
  1301. var wx = w * x2, wy = w * y2, wz = w * z2;
  1302. te[0] = 1 - ( yy + zz );
  1303. te[4] = xy - wz;
  1304. te[8] = xz + wy;
  1305. te[1] = xy + wz;
  1306. te[5] = 1 - ( xx + zz );
  1307. te[9] = yz - wx;
  1308. te[2] = xz - wy;
  1309. te[6] = yz + wx;
  1310. te[10] = 1 - ( xx + yy );
  1311. return this;
  1312. },
  1313. compose: function ( translation, rotation, scale ) {
  1314. var te = this.elements;
  1315. var mRotation = THREE.Matrix4.__m1;
  1316. var mScale = THREE.Matrix4.__m2;
  1317. mRotation.identity();
  1318. mRotation.setRotationFromQuaternion( rotation );
  1319. mScale.makeScale( scale.x, scale.y, scale.z );
  1320. this.multiply( mRotation, mScale );
  1321. te[12] = translation.x;
  1322. te[13] = translation.y;
  1323. te[14] = translation.z;
  1324. return this;
  1325. },
  1326. decompose: function ( translation, rotation, scale ) {
  1327. var te = this.elements;
  1328. // grab the axis vectors
  1329. var x = THREE.Matrix4.__v1;
  1330. var y = THREE.Matrix4.__v2;
  1331. var z = THREE.Matrix4.__v3;
  1332. x.set( te[0], te[1], te[2] );
  1333. y.set( te[4], te[5], te[6] );
  1334. z.set( te[8], te[9], te[10] );
  1335. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1336. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1337. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1338. scale.x = x.length();
  1339. scale.y = y.length();
  1340. scale.z = z.length();
  1341. translation.x = te[12];
  1342. translation.y = te[13];
  1343. translation.z = te[14];
  1344. // scale the rotation part
  1345. var matrix = THREE.Matrix4.__m1;
  1346. matrix.copy( this );
  1347. matrix.elements[0] /= scale.x;
  1348. matrix.elements[1] /= scale.x;
  1349. matrix.elements[2] /= scale.x;
  1350. matrix.elements[4] /= scale.y;
  1351. matrix.elements[5] /= scale.y;
  1352. matrix.elements[6] /= scale.y;
  1353. matrix.elements[8] /= scale.z;
  1354. matrix.elements[9] /= scale.z;
  1355. matrix.elements[10] /= scale.z;
  1356. rotation.setFromRotationMatrix( matrix );
  1357. return [ translation, rotation, scale ];
  1358. },
  1359. extractPosition: function ( m ) {
  1360. var te = this.elements;
  1361. var me = m.elements;
  1362. te[12] = me[12];
  1363. te[13] = me[13];
  1364. te[14] = me[14];
  1365. return this;
  1366. },
  1367. extractRotation: function ( m ) {
  1368. var te = this.elements;
  1369. var me = m.elements;
  1370. var vector = THREE.Matrix4.__v1;
  1371. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1372. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1373. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1374. te[0] = me[0] * scaleX;
  1375. te[1] = me[1] * scaleX;
  1376. te[2] = me[2] * scaleX;
  1377. te[4] = me[4] * scaleY;
  1378. te[5] = me[5] * scaleY;
  1379. te[6] = me[6] * scaleY;
  1380. te[8] = me[8] * scaleZ;
  1381. te[9] = me[9] * scaleZ;
  1382. te[10] = me[10] * scaleZ;
  1383. return this;
  1384. },
  1385. //
  1386. translate: function ( v ) {
  1387. var te = this.elements;
  1388. var x = v.x, y = v.y, z = v.z;
  1389. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1390. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1391. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1392. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1393. return this;
  1394. },
  1395. rotateX: function ( angle ) {
  1396. var te = this.elements;
  1397. var m12 = te[4];
  1398. var m22 = te[5];
  1399. var m32 = te[6];
  1400. var m42 = te[7];
  1401. var m13 = te[8];
  1402. var m23 = te[9];
  1403. var m33 = te[10];
  1404. var m43 = te[11];
  1405. var c = Math.cos( angle );
  1406. var s = Math.sin( angle );
  1407. te[4] = c * m12 + s * m13;
  1408. te[5] = c * m22 + s * m23;
  1409. te[6] = c * m32 + s * m33;
  1410. te[7] = c * m42 + s * m43;
  1411. te[8] = c * m13 - s * m12;
  1412. te[9] = c * m23 - s * m22;
  1413. te[10] = c * m33 - s * m32;
  1414. te[11] = c * m43 - s * m42;
  1415. return this;
  1416. },
  1417. rotateY: function ( angle ) {
  1418. var te = this.elements;
  1419. var m11 = te[0];
  1420. var m21 = te[1];
  1421. var m31 = te[2];
  1422. var m41 = te[3];
  1423. var m13 = te[8];
  1424. var m23 = te[9];
  1425. var m33 = te[10];
  1426. var m43 = te[11];
  1427. var c = Math.cos( angle );
  1428. var s = Math.sin( angle );
  1429. te[0] = c * m11 - s * m13;
  1430. te[1] = c * m21 - s * m23;
  1431. te[2] = c * m31 - s * m33;
  1432. te[3] = c * m41 - s * m43;
  1433. te[8] = c * m13 + s * m11;
  1434. te[9] = c * m23 + s * m21;
  1435. te[10] = c * m33 + s * m31;
  1436. te[11] = c * m43 + s * m41;
  1437. return this;
  1438. },
  1439. rotateZ: function ( angle ) {
  1440. var te = this.elements;
  1441. var m11 = te[0];
  1442. var m21 = te[1];
  1443. var m31 = te[2];
  1444. var m41 = te[3];
  1445. var m12 = te[4];
  1446. var m22 = te[5];
  1447. var m32 = te[6];
  1448. var m42 = te[7];
  1449. var c = Math.cos( angle );
  1450. var s = Math.sin( angle );
  1451. te[0] = c * m11 + s * m12;
  1452. te[1] = c * m21 + s * m22;
  1453. te[2] = c * m31 + s * m32;
  1454. te[3] = c * m41 + s * m42;
  1455. te[4] = c * m12 - s * m11;
  1456. te[5] = c * m22 - s * m21;
  1457. te[6] = c * m32 - s * m31;
  1458. te[7] = c * m42 - s * m41;
  1459. return this;
  1460. },
  1461. rotateByAxis: function ( axis, angle ) {
  1462. var te = this.elements;
  1463. // optimize by checking axis
  1464. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1465. return this.rotateX( angle );
  1466. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1467. return this.rotateY( angle );
  1468. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1469. return this.rotateZ( angle );
  1470. }
  1471. var x = axis.x, y = axis.y, z = axis.z;
  1472. var n = Math.sqrt(x * x + y * y + z * z);
  1473. x /= n;
  1474. y /= n;
  1475. z /= n;
  1476. var xx = x * x, yy = y * y, zz = z * z;
  1477. var c = Math.cos( angle );
  1478. var s = Math.sin( angle );
  1479. var oneMinusCosine = 1 - c;
  1480. var xy = x * y * oneMinusCosine;
  1481. var xz = x * z * oneMinusCosine;
  1482. var yz = y * z * oneMinusCosine;
  1483. var xs = x * s;
  1484. var ys = y * s;
  1485. var zs = z * s;
  1486. var r11 = xx + (1 - xx) * c;
  1487. var r21 = xy + zs;
  1488. var r31 = xz - ys;
  1489. var r12 = xy - zs;
  1490. var r22 = yy + (1 - yy) * c;
  1491. var r32 = yz + xs;
  1492. var r13 = xz + ys;
  1493. var r23 = yz - xs;
  1494. var r33 = zz + (1 - zz) * c;
  1495. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1496. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1497. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1498. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1499. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1500. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1501. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1502. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1503. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1504. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1505. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1506. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1507. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1508. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1509. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1510. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1511. return this;
  1512. },
  1513. scale: function ( v ) {
  1514. var te = this.elements;
  1515. var x = v.x, y = v.y, z = v.z;
  1516. te[0] *= x; te[4] *= y; te[8] *= z;
  1517. te[1] *= x; te[5] *= y; te[9] *= z;
  1518. te[2] *= x; te[6] *= y; te[10] *= z;
  1519. te[3] *= x; te[7] *= y; te[11] *= z;
  1520. return this;
  1521. },
  1522. getMaxScaleOnAxis: function () {
  1523. var te = this.elements;
  1524. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  1525. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  1526. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  1527. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  1528. },
  1529. //
  1530. makeTranslation: function ( x, y, z ) {
  1531. this.set(
  1532. 1, 0, 0, x,
  1533. 0, 1, 0, y,
  1534. 0, 0, 1, z,
  1535. 0, 0, 0, 1
  1536. );
  1537. return this;
  1538. },
  1539. makeRotationX: function ( theta ) {
  1540. var c = Math.cos( theta ), s = Math.sin( theta );
  1541. this.set(
  1542. 1, 0, 0, 0,
  1543. 0, c, -s, 0,
  1544. 0, s, c, 0,
  1545. 0, 0, 0, 1
  1546. );
  1547. return this;
  1548. },
  1549. makeRotationY: function ( theta ) {
  1550. var c = Math.cos( theta ), s = Math.sin( theta );
  1551. this.set(
  1552. c, 0, s, 0,
  1553. 0, 1, 0, 0,
  1554. -s, 0, c, 0,
  1555. 0, 0, 0, 1
  1556. );
  1557. return this;
  1558. },
  1559. makeRotationZ: function ( theta ) {
  1560. var c = Math.cos( theta ), s = Math.sin( theta );
  1561. this.set(
  1562. c, -s, 0, 0,
  1563. s, c, 0, 0,
  1564. 0, 0, 1, 0,
  1565. 0, 0, 0, 1
  1566. );
  1567. return this;
  1568. },
  1569. makeRotationAxis: function ( axis, angle ) {
  1570. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1571. var c = Math.cos( angle );
  1572. var s = Math.sin( angle );
  1573. var t = 1 - c;
  1574. var x = axis.x, y = axis.y, z = axis.z;
  1575. var tx = t * x, ty = t * y;
  1576. this.set(
  1577. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1578. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1579. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1580. 0, 0, 0, 1
  1581. );
  1582. return this;
  1583. },
  1584. makeScale: function ( x, y, z ) {
  1585. this.set(
  1586. x, 0, 0, 0,
  1587. 0, y, 0, 0,
  1588. 0, 0, z, 0,
  1589. 0, 0, 0, 1
  1590. );
  1591. return this;
  1592. },
  1593. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1594. var te = this.elements;
  1595. var x = 2 * near / ( right - left );
  1596. var y = 2 * near / ( top - bottom );
  1597. var a = ( right + left ) / ( right - left );
  1598. var b = ( top + bottom ) / ( top - bottom );
  1599. var c = - ( far + near ) / ( far - near );
  1600. var d = - 2 * far * near / ( far - near );
  1601. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1602. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1603. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1604. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1605. return this;
  1606. },
  1607. makePerspective: function ( fov, aspect, near, far ) {
  1608. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1609. var ymin = - ymax;
  1610. var xmin = ymin * aspect;
  1611. var xmax = ymax * aspect;
  1612. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1613. },
  1614. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1615. var te = this.elements;
  1616. var w = right - left;
  1617. var h = top - bottom;
  1618. var p = far - near;
  1619. var x = ( right + left ) / w;
  1620. var y = ( top + bottom ) / h;
  1621. var z = ( far + near ) / p;
  1622. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1623. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1624. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1625. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  1626. return this;
  1627. },
  1628. clone: function () {
  1629. var te = this.elements;
  1630. return new THREE.Matrix4(
  1631. te[0], te[4], te[8], te[12],
  1632. te[1], te[5], te[9], te[13],
  1633. te[2], te[6], te[10], te[14],
  1634. te[3], te[7], te[11], te[15]
  1635. );
  1636. }
  1637. };
  1638. THREE.Matrix4.__v1 = new THREE.Vector3();
  1639. THREE.Matrix4.__v2 = new THREE.Vector3();
  1640. THREE.Matrix4.__v3 = new THREE.Vector3();
  1641. THREE.Matrix4.__m1 = new THREE.Matrix4();
  1642. THREE.Matrix4.__m2 = new THREE.Matrix4();
  1643. /**
  1644. * https://github.com/mrdoob/eventtarget.js/
  1645. */
  1646. THREE.EventTarget = function () {
  1647. var listeners = {};
  1648. this.addEventListener = function ( type, listener ) {
  1649. if ( listeners[ type ] === undefined ) {
  1650. listeners[ type ] = [];
  1651. }
  1652. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1653. listeners[ type ].push( listener );
  1654. }
  1655. };
  1656. this.dispatchEvent = function ( event ) {
  1657. for ( var listener in listeners[ event.type ] ) {
  1658. listeners[ event.type ][ listener ]( event );
  1659. }
  1660. };
  1661. this.removeEventListener = function ( type, listener ) {
  1662. var index = listeners[ type ].indexOf( listener );
  1663. if ( index !== - 1 ) {
  1664. listeners[ type ].splice( index, 1 );
  1665. }
  1666. };
  1667. };
  1668. /**
  1669. * @author mrdoob / http://mrdoob.com/
  1670. * @author alteredq / http://alteredqualia.com/
  1671. */
  1672. THREE.Frustum = function ( ) {
  1673. this.planes = [
  1674. new THREE.Vector4(),
  1675. new THREE.Vector4(),
  1676. new THREE.Vector4(),
  1677. new THREE.Vector4(),
  1678. new THREE.Vector4(),
  1679. new THREE.Vector4()
  1680. ];
  1681. };
  1682. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  1683. var plane;
  1684. var planes = this.planes;
  1685. var me = m.elements;
  1686. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  1687. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  1688. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  1689. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  1690. planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  1691. planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  1692. planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  1693. planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  1694. planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  1695. planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  1696. for ( var i = 0; i < 6; i ++ ) {
  1697. plane = planes[ i ];
  1698. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  1699. }
  1700. };
  1701. THREE.Frustum.prototype.contains = function ( object ) {
  1702. var distance = 0.0;
  1703. var planes = this.planes;
  1704. var matrix = object.matrixWorld;
  1705. var me = matrix.elements;
  1706. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  1707. for ( var i = 0; i < 6; i ++ ) {
  1708. distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
  1709. if ( distance <= radius ) return false;
  1710. }
  1711. return true;
  1712. };
  1713. THREE.Frustum.__v1 = new THREE.Vector3();
  1714. /**
  1715. * @author mrdoob / http://mrdoob.com/
  1716. */
  1717. ( function ( THREE ) {
  1718. THREE.Ray = function ( origin, direction, near, far ) {
  1719. this.origin = origin || new THREE.Vector3();
  1720. this.direction = direction || new THREE.Vector3();
  1721. this.near = near || 0;
  1722. this.far = far || Infinity;
  1723. };
  1724. var originCopy = new THREE.Vector3();
  1725. var localOriginCopy = new THREE.Vector3();
  1726. var localDirectionCopy = new THREE.Vector3();
  1727. var vector = new THREE.Vector3();
  1728. var normal = new THREE.Vector3();
  1729. var intersectPoint = new THREE.Vector3();
  1730. var inverseMatrix = new THREE.Matrix4();
  1731. var descSort = function ( a, b ) {
  1732. return a.distance - b.distance;
  1733. };
  1734. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  1735. var distanceFromIntersection = function ( origin, direction, position ) {
  1736. v0.sub( position, origin );
  1737. var dot = v0.dot( direction );
  1738. var intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  1739. var distance = position.distanceTo( intersect );
  1740. return distance;
  1741. };
  1742. // http://www.blackpawn.com/texts/pointinpoly/default.html
  1743. var pointInFace3 = function ( p, a, b, c ) {
  1744. v0.sub( c, a );
  1745. v1.sub( b, a );
  1746. v2.sub( p, a );
  1747. var dot00 = v0.dot( v0 );
  1748. var dot01 = v0.dot( v1 );
  1749. var dot02 = v0.dot( v2 );
  1750. var dot11 = v1.dot( v1 );
  1751. var dot12 = v1.dot( v2 );
  1752. var invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  1753. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  1754. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  1755. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  1756. };
  1757. var intersectObject = function ( object, ray, intersects ) {
  1758. var distance,intersect;
  1759. if ( object instanceof THREE.Particle ) {
  1760. distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1761. if ( distance > object.scale.x ) {
  1762. return intersects;
  1763. }
  1764. intersect = {
  1765. distance: distance,
  1766. point: object.position,
  1767. face: null,
  1768. object: object
  1769. };
  1770. intersects.push( intersect );
  1771. } else if ( object instanceof THREE.Mesh ) {
  1772. // Checking boundingSphere
  1773. var scaledRadius = object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis();
  1774. // Checking distance to ray
  1775. distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1776. if ( distance > scaledRadius) {
  1777. return intersects;
  1778. }
  1779. // Checking faces
  1780. var f, fl, face, dot, scalar,
  1781. geometry = object.geometry,
  1782. vertices = geometry.vertices,
  1783. objMatrix, geometryMaterials,
  1784. isFaceMaterial, material, side, point;
  1785. geometryMaterials = object.geometry.materials;
  1786. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  1787. side = object.material.side;
  1788. var a, b, c, d;
  1789. var precision = ray.precision;
  1790. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  1791. originCopy.copy( ray.origin );
  1792. objMatrix = object.matrixWorld;
  1793. inverseMatrix.getInverse( objMatrix );
  1794. localOriginCopy.copy( originCopy );
  1795. inverseMatrix.multiplyVector3( localOriginCopy );
  1796. localDirectionCopy.copy( ray.direction );
  1797. inverseMatrix.rotateAxis( localDirectionCopy ).normalize();
  1798. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  1799. face = geometry.faces[ f ];
  1800. material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
  1801. if ( material === undefined ) continue;
  1802. side = material.side;
  1803. vector.sub( face.centroid, localOriginCopy );
  1804. normal = face.normal;
  1805. dot = localDirectionCopy.dot( normal );
  1806. // bail if ray and plane are parallel
  1807. if ( Math.abs( dot ) < precision ) continue;
  1808. // calc distance to plane
  1809. scalar = normal.dot( vector ) / dot;
  1810. // if negative distance, then plane is behind ray
  1811. if ( scalar < 0 ) continue;
  1812. if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {
  1813. intersectPoint.add( localOriginCopy, localDirectionCopy.multiplyScalar( scalar ) );
  1814. if ( face instanceof THREE.Face3 ) {
  1815. a = vertices[ face.a ];
  1816. b = vertices[ face.b ];
  1817. c = vertices[ face.c ];
  1818. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  1819. point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1820. distance = originCopy.distanceTo( point );
  1821. if ( distance < ray.near || distance > ray.far ) continue;
  1822. intersect = {
  1823. distance: distance,
  1824. point: point,
  1825. face: face,
  1826. faceIndex: f,
  1827. object: object
  1828. };
  1829. intersects.push( intersect );
  1830. }
  1831. } else if ( face instanceof THREE.Face4 ) {
  1832. a = vertices[ face.a ];
  1833. b = vertices[ face.b ];
  1834. c = vertices[ face.c ];
  1835. d = vertices[ face.d ];
  1836. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  1837. point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1838. distance = originCopy.distanceTo( point );
  1839. if ( distance < ray.near || distance > ray.far ) continue;
  1840. intersect = {
  1841. distance: distance,
  1842. point: point,
  1843. face: face,
  1844. faceIndex: f,
  1845. object: object
  1846. };
  1847. intersects.push( intersect );
  1848. }
  1849. }
  1850. }
  1851. }
  1852. }
  1853. };
  1854. var intersectDescendants = function ( object, ray, intersects ) {
  1855. var descendants = object.getDescendants();
  1856. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  1857. intersectObject( descendants[ i ], ray, intersects );
  1858. }
  1859. };
  1860. //
  1861. THREE.Ray.prototype.precision = 0.0001;
  1862. THREE.Ray.prototype.set = function ( origin, direction ) {
  1863. this.origin = origin;
  1864. this.direction = direction;
  1865. };
  1866. THREE.Ray.prototype.intersectObject = function ( object, recursive ) {
  1867. var intersects = [];
  1868. if ( recursive === true ) {
  1869. intersectDescendants( object, this, intersects );
  1870. }
  1871. intersectObject( object, this, intersects );
  1872. intersects.sort( descSort );
  1873. return intersects;
  1874. };
  1875. THREE.Ray.prototype.intersectObjects = function ( objects, recursive ) {
  1876. var intersects = [];
  1877. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  1878. intersectObject( objects[ i ], this, intersects );
  1879. if ( recursive === true ) {
  1880. intersectDescendants( objects[ i ], this, intersects );
  1881. }
  1882. }
  1883. intersects.sort( descSort );
  1884. return intersects;
  1885. };
  1886. }( THREE ) );
  1887. /**
  1888. * @author mrdoob / http://mrdoob.com/
  1889. */
  1890. THREE.Rectangle = function () {
  1891. var _left = 0;
  1892. var _top = 0;
  1893. var _right = 0;
  1894. var _bottom = 0;
  1895. var _width = 0;
  1896. var _height = 0;
  1897. var _isEmpty = true;
  1898. function resize() {
  1899. _width = _right - _left;
  1900. _height = _bottom - _top;
  1901. }
  1902. this.getX = function () {
  1903. return _left;
  1904. };
  1905. this.getY = function () {
  1906. return _top;
  1907. };
  1908. this.getWidth = function () {
  1909. return _width;
  1910. };
  1911. this.getHeight = function () {
  1912. return _height;
  1913. };
  1914. this.getLeft = function() {
  1915. return _left;
  1916. };
  1917. this.getTop = function() {
  1918. return _top;
  1919. };
  1920. this.getRight = function() {
  1921. return _right;
  1922. };
  1923. this.getBottom = function() {
  1924. return _bottom;
  1925. };
  1926. this.set = function ( left, top, right, bottom ) {
  1927. _isEmpty = false;
  1928. _left = left; _top = top;
  1929. _right = right; _bottom = bottom;
  1930. resize();
  1931. };
  1932. this.addPoint = function ( x, y ) {
  1933. if ( _isEmpty === true ) {
  1934. _isEmpty = false;
  1935. _left = x; _top = y;
  1936. _right = x; _bottom = y;
  1937. resize();
  1938. } else {
  1939. _left = _left < x ? _left : x; // Math.min( _left, x );
  1940. _top = _top < y ? _top : y; // Math.min( _top, y );
  1941. _right = _right > x ? _right : x; // Math.max( _right, x );
  1942. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  1943. resize();
  1944. }
  1945. };
  1946. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  1947. if ( _isEmpty === true ) {
  1948. _isEmpty = false;
  1949. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  1950. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  1951. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  1952. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  1953. resize();
  1954. } else {
  1955. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  1956. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  1957. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  1958. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  1959. resize();
  1960. };
  1961. };
  1962. this.addRectangle = function ( r ) {
  1963. if ( _isEmpty === true ) {
  1964. _isEmpty = false;
  1965. _left = r.getLeft(); _top = r.getTop();
  1966. _right = r.getRight(); _bottom = r.getBottom();
  1967. resize();
  1968. } else {
  1969. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  1970. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  1971. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  1972. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  1973. resize();
  1974. }
  1975. };
  1976. this.inflate = function ( v ) {
  1977. _left -= v; _top -= v;
  1978. _right += v; _bottom += v;
  1979. resize();
  1980. };
  1981. this.minSelf = function ( r ) {
  1982. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  1983. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  1984. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  1985. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  1986. resize();
  1987. };
  1988. this.intersects = function ( r ) {
  1989. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  1990. if ( _right < r.getLeft() ) return false;
  1991. if ( _left > r.getRight() ) return false;
  1992. if ( _bottom < r.getTop() ) return false;
  1993. if ( _top > r.getBottom() ) return false;
  1994. return true;
  1995. };
  1996. this.empty = function () {
  1997. _isEmpty = true;
  1998. _left = 0; _top = 0;
  1999. _right = 0; _bottom = 0;
  2000. resize();
  2001. };
  2002. this.isEmpty = function () {
  2003. return _isEmpty;
  2004. };
  2005. };
  2006. /**
  2007. * @author alteredq / http://alteredqualia.com/
  2008. */
  2009. THREE.Math = {
  2010. // Clamp value to range <a, b>
  2011. clamp: function ( x, a, b ) {
  2012. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2013. },
  2014. // Clamp value to range <a, inf)
  2015. clampBottom: function ( x, a ) {
  2016. return x < a ? a : x;
  2017. },
  2018. // Linear mapping from range <a1, a2> to range <b1, b2>
  2019. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2020. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2021. },
  2022. // Random float from <0, 1> with 16 bits of randomness
  2023. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2024. random16: function () {
  2025. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2026. },
  2027. // Random integer from <low, high> interval
  2028. randInt: function ( low, high ) {
  2029. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2030. },
  2031. // Random float from <low, high> interval
  2032. randFloat: function ( low, high ) {
  2033. return low + Math.random() * ( high - low );
  2034. },
  2035. // Random float from <-range/2, range/2> interval
  2036. randFloatSpread: function ( range ) {
  2037. return range * ( 0.5 - Math.random() );
  2038. },
  2039. sign: function ( x ) {
  2040. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2041. }
  2042. };
  2043. /**
  2044. * @author mrdoob / http://mrdoob.com/
  2045. * @author mikael emtinger / http://gomo.se/
  2046. * @author alteredq / http://alteredqualia.com/
  2047. */
  2048. THREE.Object3D = function () {
  2049. this.id = THREE.Object3DLib.length;
  2050. THREE.Object3DLib.push( this );
  2051. this.name = '';
  2052. this.properties = {};
  2053. this.parent = undefined;
  2054. this.children = [];
  2055. this.up = new THREE.Vector3( 0, 1, 0 );
  2056. this.position = new THREE.Vector3();
  2057. this.rotation = new THREE.Vector3();
  2058. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  2059. this.scale = new THREE.Vector3( 1, 1, 1 );
  2060. this.renderDepth = null;
  2061. this.rotationAutoUpdate = true;
  2062. this.matrix = new THREE.Matrix4();
  2063. this.matrixWorld = new THREE.Matrix4();
  2064. this.matrixRotationWorld = new THREE.Matrix4();
  2065. this.matrixAutoUpdate = true;
  2066. this.matrixWorldNeedsUpdate = true;
  2067. this.quaternion = new THREE.Quaternion();
  2068. this.useQuaternion = false;
  2069. this.boundRadius = 0.0;
  2070. this.boundRadiusScale = 1.0;
  2071. this.visible = true;
  2072. this.castShadow = false;
  2073. this.receiveShadow = false;
  2074. this.frustumCulled = true;
  2075. this._vector = new THREE.Vector3();
  2076. };
  2077. THREE.Object3D.prototype = {
  2078. constructor: THREE.Object3D,
  2079. applyMatrix: function ( matrix ) {
  2080. this.matrix.multiply( matrix, this.matrix );
  2081. this.scale.getScaleFromMatrix( this.matrix );
  2082. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  2083. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  2084. this.position.getPositionFromMatrix( this.matrix );
  2085. },
  2086. translate: function ( distance, axis ) {
  2087. this.matrix.rotateAxis( axis );
  2088. this.position.addSelf( axis.multiplyScalar( distance ) );
  2089. },
  2090. translateX: function ( distance ) {
  2091. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  2092. },
  2093. translateY: function ( distance ) {
  2094. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  2095. },
  2096. translateZ: function ( distance ) {
  2097. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  2098. },
  2099. localToWorld: function ( vector ) {
  2100. return this.matrixWorld.multiplyVector3( vector );
  2101. },
  2102. worldToLocal: function ( vector ) {
  2103. return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
  2104. },
  2105. lookAt: function ( vector ) {
  2106. // TODO: Add hierarchy support.
  2107. this.matrix.lookAt( vector, this.position, this.up );
  2108. if ( this.rotationAutoUpdate ) {
  2109. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  2110. }
  2111. },
  2112. add: function ( object ) {
  2113. if ( object === this ) {
  2114. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  2115. return;
  2116. }
  2117. if ( object instanceof THREE.Object3D ) {
  2118. if ( object.parent !== undefined ) {
  2119. object.parent.remove( object );
  2120. }
  2121. object.parent = this;
  2122. this.children.push( object );
  2123. // add to scene
  2124. var scene = this;
  2125. while ( scene.parent !== undefined ) {
  2126. scene = scene.parent;
  2127. }
  2128. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2129. scene.__addObject( object );
  2130. }
  2131. }
  2132. },
  2133. remove: function ( object ) {
  2134. var index = this.children.indexOf( object );
  2135. if ( index !== - 1 ) {
  2136. object.parent = undefined;
  2137. this.children.splice( index, 1 );
  2138. // remove from scene
  2139. var scene = this;
  2140. while ( scene.parent !== undefined ) {
  2141. scene = scene.parent;
  2142. }
  2143. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2144. scene.__removeObject( object );
  2145. }
  2146. }
  2147. },
  2148. traverse: function ( callback ) {
  2149. callback( this );
  2150. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2151. this.children[ i ].traverse( callback );
  2152. }
  2153. },
  2154. getChildByName: function ( name, recursive ) {
  2155. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2156. var child = this.children[ i ];
  2157. if ( child.name === name ) {
  2158. return child;
  2159. }
  2160. if ( recursive === true ) {
  2161. child = child.getChildByName( name, recursive );
  2162. if ( child !== undefined ) {
  2163. return child;
  2164. }
  2165. }
  2166. }
  2167. return undefined;
  2168. },
  2169. getDescendants: function ( array ) {
  2170. if ( array === undefined ) array = [];
  2171. Array.prototype.push.apply( array, this.children );
  2172. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2173. this.children[ i ].getDescendants( array );
  2174. }
  2175. return array;
  2176. },
  2177. updateMatrix: function () {
  2178. this.matrix.setPosition( this.position );
  2179. if ( this.useQuaternion === false ) {
  2180. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  2181. } else {
  2182. this.matrix.setRotationFromQuaternion( this.quaternion );
  2183. }
  2184. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  2185. this.matrix.scale( this.scale );
  2186. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  2187. }
  2188. this.matrixWorldNeedsUpdate = true;
  2189. },
  2190. updateMatrixWorld: function ( force ) {
  2191. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  2192. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  2193. if ( this.parent === undefined ) {
  2194. this.matrixWorld.copy( this.matrix );
  2195. } else {
  2196. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2197. }
  2198. this.matrixWorldNeedsUpdate = false;
  2199. force = true;
  2200. }
  2201. // update children
  2202. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2203. this.children[ i ].updateMatrixWorld( force );
  2204. }
  2205. },
  2206. clone: function ( object ) {
  2207. if ( object === undefined ) object = new THREE.Object3D();
  2208. object.name = this.name;
  2209. object.up.copy( this.up );
  2210. object.position.copy( this.position );
  2211. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  2212. object.eulerOrder = this.eulerOrder;
  2213. object.scale.copy( this.scale );
  2214. object.renderDepth = this.renderDepth;
  2215. object.rotationAutoUpdate = this.rotationAutoUpdate;
  2216. object.matrix.copy( this.matrix );
  2217. object.matrixWorld.copy( this.matrixWorld );
  2218. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  2219. object.matrixAutoUpdate = this.matrixAutoUpdate;
  2220. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  2221. object.quaternion.copy( this.quaternion );
  2222. object.useQuaternion = this.useQuaternion;
  2223. object.boundRadius = this.boundRadius;
  2224. object.boundRadiusScale = this.boundRadiusScale;
  2225. object.visible = this.visible;
  2226. object.castShadow = this.castShadow;
  2227. object.receiveShadow = this.receiveShadow;
  2228. object.frustumCulled = this.frustumCulled;
  2229. return object;
  2230. }
  2231. };
  2232. THREE.Object3D.__m1 = new THREE.Matrix4();
  2233. THREE.Object3D.defaultEulerOrder = 'XYZ',
  2234. THREE.Object3DLib = [];
  2235. /**
  2236. * @author mrdoob / http://mrdoob.com/
  2237. * @author supereggbert / http://www.paulbrunt.co.uk/
  2238. * @author julianwa / https://github.com/julianwa
  2239. */
  2240. THREE.Projector = function() {
  2241. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  2242. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  2243. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  2244. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  2245. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  2246. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  2247. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  2248. _vector3 = new THREE.Vector3(),
  2249. _vector4 = new THREE.Vector4(),
  2250. _viewProjectionMatrix = new THREE.Matrix4(),
  2251. _modelViewProjectionMatrix = new THREE.Matrix4(),
  2252. _frustum = new THREE.Frustum(),
  2253. _clippedVertex1PositionScreen = new THREE.Vector4(),
  2254. _clippedVertex2PositionScreen = new THREE.Vector4(),
  2255. _face3VertexNormals;
  2256. this.projectVector = function ( vector, camera ) {
  2257. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2258. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2259. _viewProjectionMatrix.multiplyVector3( vector );
  2260. return vector;
  2261. };
  2262. this.unprojectVector = function ( vector, camera ) {
  2263. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  2264. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  2265. _viewProjectionMatrix.multiplyVector3( vector );
  2266. return vector;
  2267. };
  2268. this.pickingRay = function ( vector, camera ) {
  2269. var end, ray, t;
  2270. // set two vectors with opposing z values
  2271. vector.z = -1.0;
  2272. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  2273. this.unprojectVector( vector, camera );
  2274. this.unprojectVector( end, camera );
  2275. // find direction from vector to end
  2276. end.subSelf( vector ).normalize();
  2277. return new THREE.Ray( vector, end );
  2278. };
  2279. var projectGraph = function ( root, sortObjects ) {
  2280. _objectCount = 0;
  2281. _renderData.objects.length = 0;
  2282. _renderData.sprites.length = 0;
  2283. _renderData.lights.length = 0;
  2284. var projectObject = function ( parent ) {
  2285. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  2286. var object = parent.children[ c ];
  2287. if ( object.visible === false ) continue;
  2288. if ( object instanceof THREE.Light ) {
  2289. _renderData.lights.push( object );
  2290. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  2291. if ( object.frustumCulled === false || _frustum.contains( object ) === true ) {
  2292. _object = getNextObjectInPool();
  2293. _object.object = object;
  2294. if ( object.renderDepth !== null ) {
  2295. _object.z = object.renderDepth;
  2296. } else {
  2297. _vector3.copy( object.matrixWorld.getPosition() );
  2298. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2299. _object.z = _vector3.z;
  2300. }
  2301. _renderData.objects.push( _object );
  2302. }
  2303. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  2304. _object = getNextObjectInPool();
  2305. _object.object = object;
  2306. // TODO: Find an elegant and performant solution and remove this dupe code.
  2307. if ( object.renderDepth !== null ) {
  2308. _object.z = object.renderDepth;
  2309. } else {
  2310. _vector3.copy( object.matrixWorld.getPosition() );
  2311. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2312. _object.z = _vector3.z;
  2313. }
  2314. _renderData.sprites.push( _object );
  2315. } else {
  2316. _object = getNextObjectInPool();
  2317. _object.object = object;
  2318. if ( object.renderDepth !== null ) {
  2319. _object.z = object.renderDepth;
  2320. } else {
  2321. _vector3.copy( object.matrixWorld.getPosition() );
  2322. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2323. _object.z = _vector3.z;
  2324. }
  2325. _renderData.objects.push( _object );
  2326. }
  2327. projectObject( object );
  2328. }
  2329. };
  2330. projectObject( root );
  2331. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  2332. return _renderData;
  2333. };
  2334. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  2335. var near = camera.near, far = camera.far, visible = false,
  2336. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  2337. modelMatrix, rotationMatrix,
  2338. geometry, geometryMaterials, vertices, vertex, vertexPositionScreen,
  2339. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  2340. v1, v2, v3, v4, isFaceMaterial, material, side;
  2341. _face3Count = 0;
  2342. _face4Count = 0;
  2343. _lineCount = 0;
  2344. _particleCount = 0;
  2345. _renderData.elements.length = 0;
  2346. scene.updateMatrixWorld();
  2347. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  2348. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2349. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2350. _frustum.setFromMatrix( _viewProjectionMatrix );
  2351. _renderData = projectGraph( scene, sortObjects );
  2352. for ( o = 0, ol = _renderData.objects.length; o < ol; o++ ) {
  2353. object = _renderData.objects[ o ].object;
  2354. modelMatrix = object.matrixWorld;
  2355. _vertexCount = 0;
  2356. if ( object instanceof THREE.Mesh ) {
  2357. geometry = object.geometry;
  2358. geometryMaterials = object.geometry.materials;
  2359. vertices = geometry.vertices;
  2360. faces = geometry.faces;
  2361. faceVertexUvs = geometry.faceVertexUvs;
  2362. rotationMatrix = object.matrixRotationWorld.extractRotation( modelMatrix );
  2363. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  2364. side = object.material.side;
  2365. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  2366. _vertex = getNextVertexInPool();
  2367. _vertex.positionWorld.copy( vertices[ v ] );
  2368. modelMatrix.multiplyVector3( _vertex.positionWorld );
  2369. _vertex.positionScreen.copy( _vertex.positionWorld );
  2370. _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
  2371. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  2372. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  2373. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  2374. }
  2375. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  2376. face = faces[ f ];
  2377. material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
  2378. if ( material === undefined ) continue;
  2379. side = material.side;
  2380. if ( face instanceof THREE.Face3 ) {
  2381. v1 = _vertexPool[ face.a ];
  2382. v2 = _vertexPool[ face.b ];
  2383. v3 = _vertexPool[ face.c ];
  2384. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  2385. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2386. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  2387. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2388. _face = getNextFace3InPool();
  2389. _face.v1.copy( v1 );
  2390. _face.v2.copy( v2 );
  2391. _face.v3.copy( v3 );
  2392. } else {
  2393. continue;
  2394. }
  2395. } else {
  2396. continue;
  2397. }
  2398. } else if ( face instanceof THREE.Face4 ) {
  2399. v1 = _vertexPool[ face.a ];
  2400. v2 = _vertexPool[ face.b ];
  2401. v3 = _vertexPool[ face.c ];
  2402. v4 = _vertexPool[ face.d ];
  2403. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  2404. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2405. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  2406. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  2407. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  2408. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2409. _face = getNextFace4InPool();
  2410. _face.v1.copy( v1 );
  2411. _face.v2.copy( v2 );
  2412. _face.v3.copy( v3 );
  2413. _face.v4.copy( v4 );
  2414. } else {
  2415. continue;
  2416. }
  2417. } else {
  2418. continue;
  2419. }
  2420. }
  2421. _face.normalWorld.copy( face.normal );
  2422. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
  2423. rotationMatrix.multiplyVector3( _face.normalWorld );
  2424. _face.centroidWorld.copy( face.centroid );
  2425. modelMatrix.multiplyVector3( _face.centroidWorld );
  2426. _face.centroidScreen.copy( _face.centroidWorld );
  2427. _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
  2428. faceVertexNormals = face.vertexNormals;
  2429. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  2430. normal = _face.vertexNormalsWorld[ n ];
  2431. normal.copy( faceVertexNormals[ n ] );
  2432. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
  2433. rotationMatrix.multiplyVector3( normal );
  2434. }
  2435. _face.vertexNormalsLength = faceVertexNormals.length;
  2436. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  2437. uvs = faceVertexUvs[ c ][ f ];
  2438. if ( uvs === undefined ) continue;
  2439. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  2440. _face.uvs[ c ][ u ] = uvs[ u ];
  2441. }
  2442. }
  2443. _face.color = face.color;
  2444. _face.material = material;
  2445. _face.z = _face.centroidScreen.z;
  2446. _renderData.elements.push( _face );
  2447. }
  2448. } else if ( object instanceof THREE.Line ) {
  2449. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
  2450. vertices = object.geometry.vertices;
  2451. v1 = getNextVertexInPool();
  2452. v1.positionScreen.copy( vertices[ 0 ] );
  2453. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2454. // Handle LineStrip and LinePieces
  2455. var step = object.type === THREE.LinePieces ? 2 : 1;
  2456. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2457. v1 = getNextVertexInPool();
  2458. v1.positionScreen.copy( vertices[ v ] );
  2459. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2460. if ( ( v + 1 ) % step > 0 ) continue;
  2461. v2 = _vertexPool[ _vertexCount - 2 ];
  2462. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2463. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2464. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  2465. // Perform the perspective divide
  2466. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2467. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2468. _line = getNextLineInPool();
  2469. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2470. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2471. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2472. _line.material = object.material;
  2473. _renderData.elements.push( _line );
  2474. }
  2475. }
  2476. }
  2477. }
  2478. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2479. object = _renderData.sprites[ o ].object;
  2480. modelMatrix = object.matrixWorld;
  2481. if ( object instanceof THREE.Particle ) {
  2482. _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
  2483. _viewProjectionMatrix.multiplyVector4( _vector4 );
  2484. _vector4.z /= _vector4.w;
  2485. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2486. _particle = getNextParticleInPool();
  2487. _particle.object = object;
  2488. _particle.x = _vector4.x / _vector4.w;
  2489. _particle.y = _vector4.y / _vector4.w;
  2490. _particle.z = _vector4.z;
  2491. _particle.rotation = object.rotation.z;
  2492. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2493. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2494. _particle.material = object.material;
  2495. _renderData.elements.push( _particle );
  2496. }
  2497. }
  2498. }
  2499. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  2500. return _renderData;
  2501. };
  2502. // Pools
  2503. function getNextObjectInPool() {
  2504. if ( _objectCount === _objectPoolLength ) {
  2505. var object = new THREE.RenderableObject();
  2506. _objectPool.push( object );
  2507. _objectPoolLength ++;
  2508. _objectCount ++;
  2509. return object;
  2510. }
  2511. return _objectPool[ _objectCount ++ ];
  2512. }
  2513. function getNextVertexInPool() {
  2514. if ( _vertexCount === _vertexPoolLength ) {
  2515. var vertex = new THREE.RenderableVertex();
  2516. _vertexPool.push( vertex );
  2517. _vertexPoolLength ++;
  2518. _vertexCount ++;
  2519. return vertex;
  2520. }
  2521. return _vertexPool[ _vertexCount ++ ];
  2522. }
  2523. function getNextFace3InPool() {
  2524. if ( _face3Count === _face3PoolLength ) {
  2525. var face = new THREE.RenderableFace3();
  2526. _face3Pool.push( face );
  2527. _face3PoolLength ++;
  2528. _face3Count ++;
  2529. return face;
  2530. }
  2531. return _face3Pool[ _face3Count ++ ];
  2532. }
  2533. function getNextFace4InPool() {
  2534. if ( _face4Count === _face4PoolLength ) {
  2535. var face = new THREE.RenderableFace4();
  2536. _face4Pool.push( face );
  2537. _face4PoolLength ++;
  2538. _face4Count ++;
  2539. return face;
  2540. }
  2541. return _face4Pool[ _face4Count ++ ];
  2542. }
  2543. function getNextLineInPool() {
  2544. if ( _lineCount === _linePoolLength ) {
  2545. var line = new THREE.RenderableLine();
  2546. _linePool.push( line );
  2547. _linePoolLength ++;
  2548. _lineCount ++
  2549. return line;
  2550. }
  2551. return _linePool[ _lineCount ++ ];
  2552. }
  2553. function getNextParticleInPool() {
  2554. if ( _particleCount === _particlePoolLength ) {
  2555. var particle = new THREE.RenderableParticle();
  2556. _particlePool.push( particle );
  2557. _particlePoolLength ++;
  2558. _particleCount ++
  2559. return particle;
  2560. }
  2561. return _particlePool[ _particleCount ++ ];
  2562. }
  2563. //
  2564. function painterSort( a, b ) {
  2565. return b.z - a.z;
  2566. }
  2567. function clipLine( s1, s2 ) {
  2568. var alpha1 = 0, alpha2 = 1,
  2569. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2570. // Z = -1 and Z = +1, respectively.
  2571. bc1near = s1.z + s1.w,
  2572. bc2near = s2.z + s2.w,
  2573. bc1far = - s1.z + s1.w,
  2574. bc2far = - s2.z + s2.w;
  2575. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2576. // Both vertices lie entirely within all clip planes.
  2577. return true;
  2578. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2579. // Both vertices lie entirely outside one of the clip planes.
  2580. return false;
  2581. } else {
  2582. // The line segment spans at least one clip plane.
  2583. if ( bc1near < 0 ) {
  2584. // v1 lies outside the near plane, v2 inside
  2585. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2586. } else if ( bc2near < 0 ) {
  2587. // v2 lies outside the near plane, v1 inside
  2588. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2589. }
  2590. if ( bc1far < 0 ) {
  2591. // v1 lies outside the far plane, v2 inside
  2592. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2593. } else if ( bc2far < 0 ) {
  2594. // v2 lies outside the far plane, v2 inside
  2595. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2596. }
  2597. if ( alpha2 < alpha1 ) {
  2598. // The line segment spans two boundaries, but is outside both of them.
  2599. // (This can't happen when we're only clipping against just near/far but good
  2600. // to leave the check here for future usage if other clip planes are added.)
  2601. return false;
  2602. } else {
  2603. // Update the s1 and s2 vertices to match the clipped line segment.
  2604. s1.lerpSelf( s2, alpha1 );
  2605. s2.lerpSelf( s1, 1 - alpha2 );
  2606. return true;
  2607. }
  2608. }
  2609. }
  2610. };
  2611. /**
  2612. * @author mikael emtinger / http://gomo.se/
  2613. * @author alteredq / http://alteredqualia.com/
  2614. * @author WestLangley / http://github.com/WestLangley
  2615. */
  2616. THREE.Quaternion = function( x, y, z, w ) {
  2617. this.x = x || 0;
  2618. this.y = y || 0;
  2619. this.z = z || 0;
  2620. this.w = ( w !== undefined ) ? w : 1;
  2621. };
  2622. THREE.Quaternion.prototype = {
  2623. constructor: THREE.Quaternion,
  2624. set: function ( x, y, z, w ) {
  2625. this.x = x;
  2626. this.y = y;
  2627. this.z = z;
  2628. this.w = w;
  2629. return this;
  2630. },
  2631. copy: function ( q ) {
  2632. this.x = q.x;
  2633. this.y = q.y;
  2634. this.z = q.z;
  2635. this.w = q.w;
  2636. return this;
  2637. },
  2638. setFromEuler: function ( v, order ) {
  2639. // http://www.mathworks.com/matlabcentral/fileexchange/
  2640. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2641. // content/SpinCalc.m
  2642. var c1 = Math.cos( v.x / 2 );
  2643. var c2 = Math.cos( v.y / 2 );
  2644. var c3 = Math.cos( v.z / 2 );
  2645. var s1 = Math.sin( v.x / 2 );
  2646. var s2 = Math.sin( v.y / 2 );
  2647. var s3 = Math.sin( v.z / 2 );
  2648. if ( order === undefined || order === 'XYZ' ) {
  2649. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2650. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2651. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2652. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2653. } else if ( order === 'YXZ' ) {
  2654. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2655. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2656. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2657. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2658. } else if ( order === 'ZXY' ) {
  2659. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2660. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2661. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2662. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2663. } else if ( order === 'ZYX' ) {
  2664. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2665. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2666. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2667. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2668. } else if ( order === 'YZX' ) {
  2669. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2670. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2671. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2672. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2673. } else if ( order === 'XZY' ) {
  2674. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2675. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2676. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2677. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2678. }
  2679. return this;
  2680. },
  2681. setFromAxisAngle: function ( axis, angle ) {
  2682. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2683. // axis have to be normalized
  2684. var halfAngle = angle / 2,
  2685. s = Math.sin( halfAngle );
  2686. this.x = axis.x * s;
  2687. this.y = axis.y * s;
  2688. this.z = axis.z * s;
  2689. this.w = Math.cos( halfAngle );
  2690. return this;
  2691. },
  2692. setFromRotationMatrix: function ( m ) {
  2693. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2694. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2695. var te = m.elements,
  2696. m11 = te[0], m12 = te[4], m13 = te[8],
  2697. m21 = te[1], m22 = te[5], m23 = te[9],
  2698. m31 = te[2], m32 = te[6], m33 = te[10],
  2699. trace = m11 + m22 + m33,
  2700. s;
  2701. if( trace > 0 ) {
  2702. s = 0.5 / Math.sqrt( trace + 1.0 );
  2703. this.w = 0.25 / s;
  2704. this.x = ( m32 - m23 ) * s;
  2705. this.y = ( m13 - m31 ) * s;
  2706. this.z = ( m21 - m12 ) * s;
  2707. } else if ( m11 > m22 && m11 > m33 ) {
  2708. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2709. this.w = (m32 - m23 ) / s;
  2710. this.x = 0.25 * s;
  2711. this.y = (m12 + m21 ) / s;
  2712. this.z = (m13 + m31 ) / s;
  2713. } else if (m22 > m33) {
  2714. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2715. this.w = (m13 - m31 ) / s;
  2716. this.x = (m12 + m21 ) / s;
  2717. this.y = 0.25 * s;
  2718. this.z = (m23 + m32 ) / s;
  2719. } else {
  2720. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2721. this.w = ( m21 - m12 ) / s;
  2722. this.x = ( m13 + m31 ) / s;
  2723. this.y = ( m23 + m32 ) / s;
  2724. this.z = 0.25 * s;
  2725. }
  2726. return this;
  2727. },
  2728. calculateW : function () {
  2729. this.w = - Math.sqrt( Math.abs( 1.0 - this.x * this.x - this.y * this.y - this.z * this.z ) );
  2730. return this;
  2731. },
  2732. inverse: function () {
  2733. this.x *= -1;
  2734. this.y *= -1;
  2735. this.z *= -1;
  2736. return this;
  2737. },
  2738. length: function () {
  2739. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2740. },
  2741. normalize: function () {
  2742. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2743. if ( l === 0 ) {
  2744. this.x = 0;
  2745. this.y = 0;
  2746. this.z = 0;
  2747. this.w = 0;
  2748. } else {
  2749. l = 1 / l;
  2750. this.x = this.x * l;
  2751. this.y = this.y * l;
  2752. this.z = this.z * l;
  2753. this.w = this.w * l;
  2754. }
  2755. return this;
  2756. },
  2757. multiply: function ( a, b ) {
  2758. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2759. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
  2760. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2761. this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
  2762. this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
  2763. this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
  2764. this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
  2765. return this;
  2766. },
  2767. multiplySelf: function ( b ) {
  2768. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2769. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2770. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2771. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2772. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2773. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2774. return this;
  2775. },
  2776. multiplyVector3: function ( vector, dest ) {
  2777. if ( !dest ) { dest = vector; }
  2778. var x = vector.x, y = vector.y, z = vector.z,
  2779. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2780. // calculate quat * vector
  2781. var ix = qw * x + qy * z - qz * y,
  2782. iy = qw * y + qz * x - qx * z,
  2783. iz = qw * z + qx * y - qy * x,
  2784. iw = -qx * x - qy * y - qz * z;
  2785. // calculate result * inverse quat
  2786. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2787. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2788. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2789. return dest;
  2790. },
  2791. slerpSelf: function ( qb, t ) {
  2792. var x = this.x, y = this.y, z = this.z, w = this.w;
  2793. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2794. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  2795. if ( cosHalfTheta < 0 ) {
  2796. this.w = -qb.w;
  2797. this.x = -qb.x;
  2798. this.y = -qb.y;
  2799. this.z = -qb.z;
  2800. cosHalfTheta = -cosHalfTheta;
  2801. } else {
  2802. this.copy( qb );
  2803. }
  2804. if ( cosHalfTheta >= 1.0 ) {
  2805. this.w = w;
  2806. this.x = x;
  2807. this.y = y;
  2808. this.z = z;
  2809. return this;
  2810. }
  2811. var halfTheta = Math.acos( cosHalfTheta );
  2812. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2813. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2814. this.w = 0.5 * ( w + this.w );
  2815. this.x = 0.5 * ( x + this.x );
  2816. this.y = 0.5 * ( y + this.y );
  2817. this.z = 0.5 * ( z + this.z );
  2818. return this;
  2819. }
  2820. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2821. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2822. this.w = ( w * ratioA + this.w * ratioB );
  2823. this.x = ( x * ratioA + this.x * ratioB );
  2824. this.y = ( y * ratioA + this.y * ratioB );
  2825. this.z = ( z * ratioA + this.z * ratioB );
  2826. return this;
  2827. },
  2828. clone: function () {
  2829. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2830. }
  2831. }
  2832. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2833. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2834. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2835. if ( cosHalfTheta < 0 ) {
  2836. qm.w = -qb.w;
  2837. qm.x = -qb.x;
  2838. qm.y = -qb.y;
  2839. qm.z = -qb.z;
  2840. cosHalfTheta = -cosHalfTheta;
  2841. } else {
  2842. qm.copy( qb );
  2843. }
  2844. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2845. qm.w = qa.w;
  2846. qm.x = qa.x;
  2847. qm.y = qa.y;
  2848. qm.z = qa.z;
  2849. return qm;
  2850. }
  2851. var halfTheta = Math.acos( cosHalfTheta );
  2852. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2853. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2854. qm.w = 0.5 * ( qa.w + qm.w );
  2855. qm.x = 0.5 * ( qa.x + qm.x );
  2856. qm.y = 0.5 * ( qa.y + qm.y );
  2857. qm.z = 0.5 * ( qa.z + qm.z );
  2858. return qm;
  2859. }
  2860. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
  2861. var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2862. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2863. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2864. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2865. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2866. return qm;
  2867. }
  2868. /**
  2869. * @author mrdoob / http://mrdoob.com/
  2870. */
  2871. THREE.Vertex = function ( v ) {
  2872. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  2873. return v;
  2874. };
  2875. /**
  2876. * @author mrdoob / http://mrdoob.com/
  2877. * @author alteredq / http://alteredqualia.com/
  2878. */
  2879. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  2880. this.a = a;
  2881. this.b = b;
  2882. this.c = c;
  2883. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2884. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2885. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2886. this.vertexColors = color instanceof Array ? color : [];
  2887. this.vertexTangents = [];
  2888. this.materialIndex = materialIndex;
  2889. this.centroid = new THREE.Vector3();
  2890. };
  2891. THREE.Face3.prototype = {
  2892. constructor: THREE.Face3,
  2893. clone: function () {
  2894. var face = new THREE.Face3( this.a, this.b, this.c );
  2895. face.normal.copy( this.normal );
  2896. face.color.copy( this.color );
  2897. face.centroid.copy( this.centroid );
  2898. face.materialIndex = this.materialIndex;
  2899. var i, il;
  2900. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2901. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2902. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2903. return face;
  2904. }
  2905. };
  2906. /**
  2907. * @author mrdoob / http://mrdoob.com/
  2908. * @author alteredq / http://alteredqualia.com/
  2909. */
  2910. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  2911. this.a = a;
  2912. this.b = b;
  2913. this.c = c;
  2914. this.d = d;
  2915. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2916. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2917. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2918. this.vertexColors = color instanceof Array ? color : [];
  2919. this.vertexTangents = [];
  2920. this.materialIndex = materialIndex;
  2921. this.centroid = new THREE.Vector3();
  2922. };
  2923. THREE.Face4.prototype = {
  2924. constructor: THREE.Face4,
  2925. clone: function () {
  2926. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  2927. face.normal.copy( this.normal );
  2928. face.color.copy( this.color );
  2929. face.centroid.copy( this.centroid );
  2930. face.materialIndex = this.materialIndex;
  2931. var i, il;
  2932. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2933. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2934. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2935. return face;
  2936. }
  2937. };
  2938. /**
  2939. * @author mrdoob / http://mrdoob.com/
  2940. */
  2941. THREE.UV = function ( u, v ) {
  2942. this.u = u || 0;
  2943. this.v = v || 0;
  2944. };
  2945. THREE.UV.prototype = {
  2946. constructor: THREE.UV,
  2947. set: function ( u, v ) {
  2948. this.u = u;
  2949. this.v = v;
  2950. return this;
  2951. },
  2952. copy: function ( uv ) {
  2953. this.u = uv.u;
  2954. this.v = uv.v;
  2955. return this;
  2956. },
  2957. lerpSelf: function ( uv, alpha ) {
  2958. this.u += ( uv.u - this.u ) * alpha;
  2959. this.v += ( uv.v - this.v ) * alpha;
  2960. return this;
  2961. },
  2962. clone: function () {
  2963. return new THREE.UV( this.u, this.v );
  2964. }
  2965. };
  2966. /**
  2967. * @author mrdoob / http://mrdoob.com/
  2968. * @author kile / http://kile.stravaganza.org/
  2969. * @author alteredq / http://alteredqualia.com/
  2970. * @author mikael emtinger / http://gomo.se/
  2971. * @author zz85 / http://www.lab4games.net/zz85/blog
  2972. */
  2973. THREE.Geometry = function () {
  2974. this.id = THREE.GeometryLib.length;
  2975. THREE.GeometryLib.push( this );
  2976. this.name = '';
  2977. this.vertices = [];
  2978. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  2979. this.materials = [];
  2980. this.faces = [];
  2981. this.faceUvs = [[]];
  2982. this.faceVertexUvs = [[]];
  2983. this.morphTargets = [];
  2984. this.morphColors = [];
  2985. this.morphNormals = [];
  2986. this.skinWeights = [];
  2987. this.skinIndices = [];
  2988. this.boundingBox = null;
  2989. this.boundingSphere = null;
  2990. this.hasTangents = false;
  2991. this.dynamic = true; // the intermediate typearrays will be deleted when set to false
  2992. // update flags
  2993. this.verticesNeedUpdate = false;
  2994. this.elementsNeedUpdate = false;
  2995. this.uvsNeedUpdate = false;
  2996. this.normalsNeedUpdate = false;
  2997. this.tangentsNeedUpdate = false;
  2998. this.colorsNeedUpdate = false;
  2999. };
  3000. THREE.Geometry.prototype = {
  3001. constructor : THREE.Geometry,
  3002. applyMatrix: function ( matrix ) {
  3003. var matrixRotation = new THREE.Matrix4();
  3004. matrixRotation.extractRotation( matrix );
  3005. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  3006. var vertex = this.vertices[ i ];
  3007. matrix.multiplyVector3( vertex );
  3008. }
  3009. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  3010. var face = this.faces[ i ];
  3011. matrixRotation.multiplyVector3( face.normal );
  3012. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  3013. matrixRotation.multiplyVector3( face.vertexNormals[ j ] );
  3014. }
  3015. matrix.multiplyVector3( face.centroid );
  3016. }
  3017. },
  3018. computeCentroids: function () {
  3019. var f, fl, face;
  3020. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3021. face = this.faces[ f ];
  3022. face.centroid.set( 0, 0, 0 );
  3023. if ( face instanceof THREE.Face3 ) {
  3024. face.centroid.addSelf( this.vertices[ face.a ] );
  3025. face.centroid.addSelf( this.vertices[ face.b ] );
  3026. face.centroid.addSelf( this.vertices[ face.c ] );
  3027. face.centroid.divideScalar( 3 );
  3028. } else if ( face instanceof THREE.Face4 ) {
  3029. face.centroid.addSelf( this.vertices[ face.a ] );
  3030. face.centroid.addSelf( this.vertices[ face.b ] );
  3031. face.centroid.addSelf( this.vertices[ face.c ] );
  3032. face.centroid.addSelf( this.vertices[ face.d ] );
  3033. face.centroid.divideScalar( 4 );
  3034. }
  3035. }
  3036. },
  3037. computeFaceNormals: function () {
  3038. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  3039. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  3040. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3041. face = this.faces[ f ];
  3042. vA = this.vertices[ face.a ];
  3043. vB = this.vertices[ face.b ];
  3044. vC = this.vertices[ face.c ];
  3045. cb.sub( vC, vB );
  3046. ab.sub( vA, vB );
  3047. cb.crossSelf( ab );
  3048. if ( !cb.isZero() ) {
  3049. cb.normalize();
  3050. }
  3051. face.normal.copy( cb );
  3052. }
  3053. },
  3054. computeVertexNormals: function () {
  3055. var v, vl, f, fl, face, vertices;
  3056. // create internal buffers for reuse when calling this method repeatedly
  3057. // (otherwise memory allocation / deallocation every frame is big resource hog)
  3058. if ( this.__tmpVertices === undefined ) {
  3059. this.__tmpVertices = new Array( this.vertices.length );
  3060. vertices = this.__tmpVertices;
  3061. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3062. vertices[ v ] = new THREE.Vector3();
  3063. }
  3064. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3065. face = this.faces[ f ];
  3066. if ( face instanceof THREE.Face3 ) {
  3067. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3068. } else if ( face instanceof THREE.Face4 ) {
  3069. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3070. }
  3071. }
  3072. } else {
  3073. vertices = this.__tmpVertices;
  3074. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3075. vertices[ v ].set( 0, 0, 0 );
  3076. }
  3077. }
  3078. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3079. face = this.faces[ f ];
  3080. if ( face instanceof THREE.Face3 ) {
  3081. vertices[ face.a ].addSelf( face.normal );
  3082. vertices[ face.b ].addSelf( face.normal );
  3083. vertices[ face.c ].addSelf( face.normal );
  3084. } else if ( face instanceof THREE.Face4 ) {
  3085. vertices[ face.a ].addSelf( face.normal );
  3086. vertices[ face.b ].addSelf( face.normal );
  3087. vertices[ face.c ].addSelf( face.normal );
  3088. vertices[ face.d ].addSelf( face.normal );
  3089. }
  3090. }
  3091. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3092. vertices[ v ].normalize();
  3093. }
  3094. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3095. face = this.faces[ f ];
  3096. if ( face instanceof THREE.Face3 ) {
  3097. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3098. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3099. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3100. } else if ( face instanceof THREE.Face4 ) {
  3101. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3102. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3103. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3104. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  3105. }
  3106. }
  3107. },
  3108. computeMorphNormals: function () {
  3109. var i, il, f, fl, face;
  3110. // save original normals
  3111. // - create temp variables on first access
  3112. // otherwise just copy (for faster repeated calls)
  3113. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3114. face = this.faces[ f ];
  3115. if ( ! face.__originalFaceNormal ) {
  3116. face.__originalFaceNormal = face.normal.clone();
  3117. } else {
  3118. face.__originalFaceNormal.copy( face.normal );
  3119. }
  3120. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  3121. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  3122. if ( ! face.__originalVertexNormals[ i ] ) {
  3123. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  3124. } else {
  3125. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  3126. }
  3127. }
  3128. }
  3129. // use temp geometry to compute face and vertex normals for each morph
  3130. var tmpGeo = new THREE.Geometry();
  3131. tmpGeo.faces = this.faces;
  3132. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  3133. // create on first access
  3134. if ( ! this.morphNormals[ i ] ) {
  3135. this.morphNormals[ i ] = {};
  3136. this.morphNormals[ i ].faceNormals = [];
  3137. this.morphNormals[ i ].vertexNormals = [];
  3138. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  3139. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  3140. var faceNormal, vertexNormals;
  3141. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3142. face = this.faces[ f ];
  3143. faceNormal = new THREE.Vector3();
  3144. if ( face instanceof THREE.Face3 ) {
  3145. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  3146. } else {
  3147. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  3148. }
  3149. dstNormalsFace.push( faceNormal );
  3150. dstNormalsVertex.push( vertexNormals );
  3151. }
  3152. }
  3153. var morphNormals = this.morphNormals[ i ];
  3154. // set vertices to morph target
  3155. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  3156. // compute morph normals
  3157. tmpGeo.computeFaceNormals();
  3158. tmpGeo.computeVertexNormals();
  3159. // store morph normals
  3160. var faceNormal, vertexNormals;
  3161. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3162. face = this.faces[ f ];
  3163. faceNormal = morphNormals.faceNormals[ f ];
  3164. vertexNormals = morphNormals.vertexNormals[ f ];
  3165. faceNormal.copy( face.normal );
  3166. if ( face instanceof THREE.Face3 ) {
  3167. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3168. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3169. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3170. } else {
  3171. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3172. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3173. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3174. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  3175. }
  3176. }
  3177. }
  3178. // restore original normals
  3179. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3180. face = this.faces[ f ];
  3181. face.normal = face.__originalFaceNormal;
  3182. face.vertexNormals = face.__originalVertexNormals;
  3183. }
  3184. },
  3185. computeTangents: function () {
  3186. // based on http://www.terathon.com/code/tangent.html
  3187. // tangents go to vertices
  3188. var f, fl, v, vl, i, il, vertexIndex,
  3189. face, uv, vA, vB, vC, uvA, uvB, uvC,
  3190. x1, x2, y1, y2, z1, z2,
  3191. s1, s2, t1, t2, r, t, test,
  3192. tan1 = [], tan2 = [],
  3193. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  3194. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  3195. n = new THREE.Vector3(), w;
  3196. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3197. tan1[ v ] = new THREE.Vector3();
  3198. tan2[ v ] = new THREE.Vector3();
  3199. }
  3200. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  3201. vA = context.vertices[ a ];
  3202. vB = context.vertices[ b ];
  3203. vC = context.vertices[ c ];
  3204. uvA = uv[ ua ];
  3205. uvB = uv[ ub ];
  3206. uvC = uv[ uc ];
  3207. x1 = vB.x - vA.x;
  3208. x2 = vC.x - vA.x;
  3209. y1 = vB.y - vA.y;
  3210. y2 = vC.y - vA.y;
  3211. z1 = vB.z - vA.z;
  3212. z2 = vC.z - vA.z;
  3213. s1 = uvB.u - uvA.u;
  3214. s2 = uvC.u - uvA.u;
  3215. t1 = uvB.v - uvA.v;
  3216. t2 = uvC.v - uvA.v;
  3217. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3218. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  3219. ( t2 * y1 - t1 * y2 ) * r,
  3220. ( t2 * z1 - t1 * z2 ) * r );
  3221. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  3222. ( s1 * y2 - s2 * y1 ) * r,
  3223. ( s1 * z2 - s2 * z1 ) * r );
  3224. tan1[ a ].addSelf( sdir );
  3225. tan1[ b ].addSelf( sdir );
  3226. tan1[ c ].addSelf( sdir );
  3227. tan2[ a ].addSelf( tdir );
  3228. tan2[ b ].addSelf( tdir );
  3229. tan2[ c ].addSelf( tdir );
  3230. }
  3231. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3232. face = this.faces[ f ];
  3233. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  3234. if ( face instanceof THREE.Face3 ) {
  3235. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  3236. } else if ( face instanceof THREE.Face4 ) {
  3237. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  3238. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  3239. }
  3240. }
  3241. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  3242. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3243. face = this.faces[ f ];
  3244. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  3245. n.copy( face.vertexNormals[ i ] );
  3246. vertexIndex = face[ faceIndex[ i ] ];
  3247. t = tan1[ vertexIndex ];
  3248. // Gram-Schmidt orthogonalize
  3249. tmp.copy( t );
  3250. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3251. // Calculate handedness
  3252. tmp2.cross( face.vertexNormals[ i ], t );
  3253. test = tmp2.dot( tan2[ vertexIndex ] );
  3254. w = (test < 0.0) ? -1.0 : 1.0;
  3255. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  3256. }
  3257. }
  3258. this.hasTangents = true;
  3259. },
  3260. computeBoundingBox: function () {
  3261. if ( ! this.boundingBox ) {
  3262. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  3263. }
  3264. if ( this.vertices.length > 0 ) {
  3265. var position, firstPosition = this.vertices[ 0 ];
  3266. this.boundingBox.min.copy( firstPosition );
  3267. this.boundingBox.max.copy( firstPosition );
  3268. var min = this.boundingBox.min,
  3269. max = this.boundingBox.max;
  3270. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  3271. position = this.vertices[ v ];
  3272. if ( position.x < min.x ) {
  3273. min.x = position.x;
  3274. } else if ( position.x > max.x ) {
  3275. max.x = position.x;
  3276. }
  3277. if ( position.y < min.y ) {
  3278. min.y = position.y;
  3279. } else if ( position.y > max.y ) {
  3280. max.y = position.y;
  3281. }
  3282. if ( position.z < min.z ) {
  3283. min.z = position.z;
  3284. } else if ( position.z > max.z ) {
  3285. max.z = position.z;
  3286. }
  3287. }
  3288. } else {
  3289. this.boundingBox.min.set( 0, 0, 0 );
  3290. this.boundingBox.max.set( 0, 0, 0 );
  3291. }
  3292. },
  3293. computeBoundingSphere: function () {
  3294. var maxRadiusSq = 0;
  3295. if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };
  3296. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  3297. var radiusSq = this.vertices[ i ].lengthSq();
  3298. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3299. }
  3300. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3301. },
  3302. /*
  3303. * Checks for duplicate vertices with hashmap.
  3304. * Duplicated vertices are removed
  3305. * and faces' vertices are updated.
  3306. */
  3307. mergeVertices: function () {
  3308. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  3309. var unique = [], changes = [];
  3310. var v, key;
  3311. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  3312. var precision = Math.pow( 10, precisionPoints );
  3313. var i,il, face;
  3314. var abcd = 'abcd', o, k, j, jl, u;
  3315. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  3316. v = this.vertices[ i ];
  3317. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  3318. if ( verticesMap[ key ] === undefined ) {
  3319. verticesMap[ key ] = i;
  3320. unique.push( this.vertices[ i ] );
  3321. changes[ i ] = unique.length - 1;
  3322. } else {
  3323. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  3324. changes[ i ] = changes[ verticesMap[ key ] ];
  3325. }
  3326. };
  3327. // Start to patch face indices
  3328. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  3329. face = this.faces[ i ];
  3330. if ( face instanceof THREE.Face3 ) {
  3331. face.a = changes[ face.a ];
  3332. face.b = changes[ face.b ];
  3333. face.c = changes[ face.c ];
  3334. } else if ( face instanceof THREE.Face4 ) {
  3335. face.a = changes[ face.a ];
  3336. face.b = changes[ face.b ];
  3337. face.c = changes[ face.c ];
  3338. face.d = changes[ face.d ];
  3339. // check dups in (a, b, c, d) and convert to -> face3
  3340. o = [ face.a, face.b, face.c, face.d ];
  3341. for ( k = 3; k > 0; k -- ) {
  3342. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  3343. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  3344. o.splice( k, 1 );
  3345. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  3346. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  3347. u = this.faceVertexUvs[ j ][ i ];
  3348. if ( u ) u.splice( k, 1 );
  3349. }
  3350. this.faces[ i ].vertexColors = face.vertexColors;
  3351. break;
  3352. }
  3353. }
  3354. }
  3355. }
  3356. // Use unique set of vertices
  3357. var diff = this.vertices.length - unique.length;
  3358. this.vertices = unique;
  3359. return diff;
  3360. },
  3361. clone: function () {
  3362. // TODO
  3363. }
  3364. };
  3365. THREE.GeometryLib = [];
  3366. /**
  3367. * @author alteredq / http://alteredqualia.com/
  3368. */
  3369. THREE.BufferGeometry = function () {
  3370. this.id = THREE.GeometryCount ++;
  3371. // attributes
  3372. this.attributes = {};
  3373. // attributes typed arrays are kept only if dynamic flag is set
  3374. this.dynamic = false;
  3375. // boundings
  3376. this.boundingBox = null;
  3377. this.boundingSphere = null;
  3378. this.hasTangents = false;
  3379. // for compatibility
  3380. this.morphTargets = [];
  3381. };
  3382. THREE.BufferGeometry.prototype = {
  3383. constructor : THREE.BufferGeometry,
  3384. applyMatrix: function ( matrix ) {
  3385. var positionArray;
  3386. var normalArray;
  3387. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  3388. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  3389. if ( positionArray !== undefined ) {
  3390. matrix.multiplyVector3Array( positionArray );
  3391. this.verticesNeedUpdate = true;
  3392. }
  3393. if ( normalArray !== undefined ) {
  3394. var matrixRotation = new THREE.Matrix4();
  3395. matrixRotation.extractRotation( matrix );
  3396. matrixRotation.multiplyVector3Array( normalArray );
  3397. this.normalsNeedUpdate = true;
  3398. }
  3399. },
  3400. computeBoundingBox: function () {
  3401. if ( ! this.boundingBox ) {
  3402. this.boundingBox = {
  3403. min: new THREE.Vector3( Infinity, Infinity, Infinity ),
  3404. max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
  3405. };
  3406. }
  3407. var positions = this.attributes[ "position" ].array;
  3408. if ( positions ) {
  3409. var bb = this.boundingBox;
  3410. var x, y, z;
  3411. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3412. x = positions[ i ];
  3413. y = positions[ i + 1 ];
  3414. z = positions[ i + 2 ];
  3415. // bounding box
  3416. if ( x < bb.min.x ) {
  3417. bb.min.x = x;
  3418. } else if ( x > bb.max.x ) {
  3419. bb.max.x = x;
  3420. }
  3421. if ( y < bb.min.y ) {
  3422. bb.min.y = y;
  3423. } else if ( y > bb.max.y ) {
  3424. bb.max.y = y;
  3425. }
  3426. if ( z < bb.min.z ) {
  3427. bb.min.z = z;
  3428. } else if ( z > bb.max.z ) {
  3429. bb.max.z = z;
  3430. }
  3431. }
  3432. }
  3433. if ( positions === undefined || positions.length === 0 ) {
  3434. this.boundingBox.min.set( 0, 0, 0 );
  3435. this.boundingBox.max.set( 0, 0, 0 );
  3436. }
  3437. },
  3438. computeBoundingSphere: function () {
  3439. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  3440. var positions = this.attributes[ "position" ].array;
  3441. if ( positions ) {
  3442. var radiusSq, maxRadiusSq = 0;
  3443. var x, y, z;
  3444. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3445. x = positions[ i ];
  3446. y = positions[ i + 1 ];
  3447. z = positions[ i + 2 ];
  3448. radiusSq = x * x + y * y + z * z;
  3449. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3450. }
  3451. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3452. }
  3453. },
  3454. computeVertexNormals: function () {
  3455. if ( this.attributes[ "position" ] && this.attributes[ "index" ] ) {
  3456. var i, il;
  3457. var j, jl;
  3458. var nVertexElements = this.attributes[ "position" ].array.length;
  3459. if ( this.attributes[ "normal" ] === undefined ) {
  3460. this.attributes[ "normal" ] = {
  3461. itemSize: 3,
  3462. array: new Float32Array( nVertexElements ),
  3463. numItems: nVertexElements
  3464. };
  3465. } else {
  3466. // reset existing normals to zero
  3467. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  3468. this.attributes[ "normal" ].array[ i ] = 0;
  3469. }
  3470. }
  3471. var offsets = this.offsets;
  3472. var indices = this.attributes[ "index" ].array;
  3473. var positions = this.attributes[ "position" ].array;
  3474. var normals = this.attributes[ "normal" ].array;
  3475. var vA, vB, vC, x, y, z,
  3476. pA = new THREE.Vector3(),
  3477. pB = new THREE.Vector3(),
  3478. pC = new THREE.Vector3(),
  3479. cb = new THREE.Vector3(),
  3480. ab = new THREE.Vector3();
  3481. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3482. var start = offsets[ j ].start;
  3483. var count = offsets[ j ].count;
  3484. var index = offsets[ j ].index;
  3485. for ( i = start, il = start + count; i < il; i += 3 ) {
  3486. vA = index + indices[ i ];
  3487. vB = index + indices[ i + 1 ];
  3488. vC = index + indices[ i + 2 ];
  3489. x = positions[ vA * 3 ];
  3490. y = positions[ vA * 3 + 1 ];
  3491. z = positions[ vA * 3 + 2 ];
  3492. pA.set( x, y, z );
  3493. x = positions[ vB * 3 ];
  3494. y = positions[ vB * 3 + 1 ];
  3495. z = positions[ vB * 3 + 2 ];
  3496. pB.set( x, y, z );
  3497. x = positions[ vC * 3 ];
  3498. y = positions[ vC * 3 + 1 ];
  3499. z = positions[ vC * 3 + 2 ];
  3500. pC.set( x, y, z );
  3501. cb.sub( pC, pB );
  3502. ab.sub( pA, pB );
  3503. cb.crossSelf( ab );
  3504. normals[ vA * 3 ] += cb.x;
  3505. normals[ vA * 3 + 1 ] += cb.y;
  3506. normals[ vA * 3 + 2 ] += cb.z;
  3507. normals[ vB * 3 ] += cb.x;
  3508. normals[ vB * 3 + 1 ] += cb.y;
  3509. normals[ vB * 3 + 2 ] += cb.z;
  3510. normals[ vC * 3 ] += cb.x;
  3511. normals[ vC * 3 + 1 ] += cb.y;
  3512. normals[ vC * 3 + 2 ] += cb.z;
  3513. }
  3514. }
  3515. // normalize normals
  3516. for ( i = 0, il = normals.length; i < il; i += 3 ) {
  3517. x = normals[ i ];
  3518. y = normals[ i + 1 ];
  3519. z = normals[ i + 2 ];
  3520. var n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  3521. normals[ i ] *= n;
  3522. normals[ i + 1 ] *= n;
  3523. normals[ i + 2 ] *= n;
  3524. }
  3525. this.normalsNeedUpdate = true;
  3526. }
  3527. },
  3528. computeTangents: function () {
  3529. // based on http://www.terathon.com/code/tangent.html
  3530. // (per vertex tangents)
  3531. if ( this.attributes[ "index" ] === undefined ||
  3532. this.attributes[ "position" ] === undefined ||
  3533. this.attributes[ "normal" ] === undefined ||
  3534. this.attributes[ "uv" ] === undefined ) {
  3535. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  3536. return;
  3537. }
  3538. var indices = this.attributes[ "index" ].array;
  3539. var positions = this.attributes[ "position" ].array;
  3540. var normals = this.attributes[ "normal" ].array;
  3541. var uvs = this.attributes[ "uv" ].array;
  3542. var nVertices = positions.length / 3;
  3543. if ( this.attributes[ "tangent" ] === undefined ) {
  3544. var nTangentElements = 4 * nVertices;
  3545. this.attributes[ "tangent" ] = {
  3546. itemSize: 4,
  3547. array: new Float32Array( nTangentElements ),
  3548. numItems: nTangentElements
  3549. };
  3550. }
  3551. var tangents = this.attributes[ "tangent" ].array;
  3552. var tan1 = [], tan2 = [];
  3553. for ( var k = 0; k < nVertices; k ++ ) {
  3554. tan1[ k ] = new THREE.Vector3();
  3555. tan2[ k ] = new THREE.Vector3();
  3556. }
  3557. var xA, yA, zA,
  3558. xB, yB, zB,
  3559. xC, yC, zC,
  3560. uA, vA,
  3561. uB, vB,
  3562. uC, vC,
  3563. x1, x2, y1, y2, z1, z2,
  3564. s1, s2, t1, t2, r;
  3565. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  3566. function handleTriangle( a, b, c ) {
  3567. xA = positions[ a * 3 ];
  3568. yA = positions[ a * 3 + 1 ];
  3569. zA = positions[ a * 3 + 2 ];
  3570. xB = positions[ b * 3 ];
  3571. yB = positions[ b * 3 + 1 ];
  3572. zB = positions[ b * 3 + 2 ];
  3573. xC = positions[ c * 3 ];
  3574. yC = positions[ c * 3 + 1 ];
  3575. zC = positions[ c * 3 + 2 ];
  3576. uA = uvs[ a * 2 ];
  3577. vA = uvs[ a * 2 + 1 ];
  3578. uB = uvs[ b * 2 ];
  3579. vB = uvs[ b * 2 + 1 ];
  3580. uC = uvs[ c * 2 ];
  3581. vC = uvs[ c * 2 + 1 ];
  3582. x1 = xB - xA;
  3583. x2 = xC - xA;
  3584. y1 = yB - yA;
  3585. y2 = yC - yA;
  3586. z1 = zB - zA;
  3587. z2 = zC - zA;
  3588. s1 = uB - uA;
  3589. s2 = uC - uA;
  3590. t1 = vB - vA;
  3591. t2 = vC - vA;
  3592. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3593. sdir.set(
  3594. ( t2 * x1 - t1 * x2 ) * r,
  3595. ( t2 * y1 - t1 * y2 ) * r,
  3596. ( t2 * z1 - t1 * z2 ) * r
  3597. );
  3598. tdir.set(
  3599. ( s1 * x2 - s2 * x1 ) * r,
  3600. ( s1 * y2 - s2 * y1 ) * r,
  3601. ( s1 * z2 - s2 * z1 ) * r
  3602. );
  3603. tan1[ a ].addSelf( sdir );
  3604. tan1[ b ].addSelf( sdir );
  3605. tan1[ c ].addSelf( sdir );
  3606. tan2[ a ].addSelf( tdir );
  3607. tan2[ b ].addSelf( tdir );
  3608. tan2[ c ].addSelf( tdir );
  3609. }
  3610. var i, il;
  3611. var j, jl;
  3612. var iA, iB, iC;
  3613. var offsets = this.offsets;
  3614. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3615. var start = offsets[ j ].start;
  3616. var count = offsets[ j ].count;
  3617. var index = offsets[ j ].index;
  3618. for ( i = start, il = start + count; i < il; i += 3 ) {
  3619. iA = index + indices[ i ];
  3620. iB = index + indices[ i + 1 ];
  3621. iC = index + indices[ i + 2 ];
  3622. handleTriangle( iA, iB, iC );
  3623. }
  3624. }
  3625. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  3626. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  3627. var w, t, test;
  3628. var nx, ny, nz;
  3629. function handleVertex( v ) {
  3630. n.x = normals[ v * 3 ];
  3631. n.y = normals[ v * 3 + 1 ];
  3632. n.z = normals[ v * 3 + 2 ];
  3633. n2.copy( n );
  3634. t = tan1[ v ];
  3635. // Gram-Schmidt orthogonalize
  3636. tmp.copy( t );
  3637. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3638. // Calculate handedness
  3639. tmp2.cross( n2, t );
  3640. test = tmp2.dot( tan2[ v ] );
  3641. w = ( test < 0.0 ) ? -1.0 : 1.0;
  3642. tangents[ v * 4 ] = tmp.x;
  3643. tangents[ v * 4 + 1 ] = tmp.y;
  3644. tangents[ v * 4 + 2 ] = tmp.z;
  3645. tangents[ v * 4 + 3 ] = w;
  3646. }
  3647. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3648. var start = offsets[ j ].start;
  3649. var count = offsets[ j ].count;
  3650. var index = offsets[ j ].index;
  3651. for ( i = start, il = start + count; i < il; i += 3 ) {
  3652. iA = index + indices[ i ];
  3653. iB = index + indices[ i + 1 ];
  3654. iC = index + indices[ i + 2 ];
  3655. handleVertex( iA );
  3656. handleVertex( iB );
  3657. handleVertex( iC );
  3658. }
  3659. }
  3660. this.hasTangents = true;
  3661. this.tangentsNeedUpdate = true;
  3662. }
  3663. };
  3664. /**
  3665. * Spline from Tween.js, slightly optimized (and trashed)
  3666. * http://sole.github.com/tween.js/examples/05_spline.html
  3667. *
  3668. * @author mrdoob / http://mrdoob.com/
  3669. * @author alteredq / http://alteredqualia.com/
  3670. */
  3671. THREE.Spline = function ( points ) {
  3672. this.points = points;
  3673. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3674. point, intPoint, weight, w2, w3,
  3675. pa, pb, pc, pd;
  3676. this.initFromArray = function( a ) {
  3677. this.points = [];
  3678. for ( var i = 0; i < a.length; i++ ) {
  3679. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3680. }
  3681. };
  3682. this.getPoint = function ( k ) {
  3683. point = ( this.points.length - 1 ) * k;
  3684. intPoint = Math.floor( point );
  3685. weight = point - intPoint;
  3686. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3687. c[ 1 ] = intPoint;
  3688. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3689. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3690. pa = this.points[ c[ 0 ] ];
  3691. pb = this.points[ c[ 1 ] ];
  3692. pc = this.points[ c[ 2 ] ];
  3693. pd = this.points[ c[ 3 ] ];
  3694. w2 = weight * weight;
  3695. w3 = weight * w2;
  3696. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3697. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3698. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3699. return v3;
  3700. };
  3701. this.getControlPointsArray = function () {
  3702. var i, p, l = this.points.length,
  3703. coords = [];
  3704. for ( i = 0; i < l; i ++ ) {
  3705. p = this.points[ i ];
  3706. coords[ i ] = [ p.x, p.y, p.z ];
  3707. }
  3708. return coords;
  3709. };
  3710. // approximate length by summing linear segments
  3711. this.getLength = function ( nSubDivisions ) {
  3712. var i, index, nSamples, position,
  3713. point = 0, intPoint = 0, oldIntPoint = 0,
  3714. oldPosition = new THREE.Vector3(),
  3715. tmpVec = new THREE.Vector3(),
  3716. chunkLengths = [],
  3717. totalLength = 0;
  3718. // first point has 0 length
  3719. chunkLengths[ 0 ] = 0;
  3720. if ( !nSubDivisions ) nSubDivisions = 100;
  3721. nSamples = this.points.length * nSubDivisions;
  3722. oldPosition.copy( this.points[ 0 ] );
  3723. for ( i = 1; i < nSamples; i ++ ) {
  3724. index = i / nSamples;
  3725. position = this.getPoint( index );
  3726. tmpVec.copy( position );
  3727. totalLength += tmpVec.distanceTo( oldPosition );
  3728. oldPosition.copy( position );
  3729. point = ( this.points.length - 1 ) * index;
  3730. intPoint = Math.floor( point );
  3731. if ( intPoint != oldIntPoint ) {
  3732. chunkLengths[ intPoint ] = totalLength;
  3733. oldIntPoint = intPoint;
  3734. }
  3735. }
  3736. // last point ends with total length
  3737. chunkLengths[ chunkLengths.length ] = totalLength;
  3738. return { chunks: chunkLengths, total: totalLength };
  3739. };
  3740. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3741. var i, j,
  3742. index, indexCurrent, indexNext,
  3743. linearDistance, realDistance,
  3744. sampling, position,
  3745. newpoints = [],
  3746. tmpVec = new THREE.Vector3(),
  3747. sl = this.getLength();
  3748. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3749. for ( i = 1; i < this.points.length; i++ ) {
  3750. //tmpVec.copy( this.points[ i - 1 ] );
  3751. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3752. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3753. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3754. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3755. indexNext = i / ( this.points.length - 1 );
  3756. for ( j = 1; j < sampling - 1; j++ ) {
  3757. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3758. position = this.getPoint( index );
  3759. newpoints.push( tmpVec.copy( position ).clone() );
  3760. }
  3761. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3762. }
  3763. this.points = newpoints;
  3764. };
  3765. // Catmull-Rom
  3766. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3767. var v0 = ( p2 - p0 ) * 0.5,
  3768. v1 = ( p3 - p1 ) * 0.5;
  3769. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3770. };
  3771. };
  3772. /**
  3773. * @author mrdoob / http://mrdoob.com/
  3774. * @author mikael emtinger / http://gomo.se/
  3775. */
  3776. THREE.Camera = function () {
  3777. THREE.Object3D.call( this );
  3778. this.matrixWorldInverse = new THREE.Matrix4();
  3779. this.projectionMatrix = new THREE.Matrix4();
  3780. this.projectionMatrixInverse = new THREE.Matrix4();
  3781. };
  3782. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  3783. THREE.Camera.prototype.lookAt = function ( vector ) {
  3784. // TODO: Add hierarchy support.
  3785. this.matrix.lookAt( this.position, vector, this.up );
  3786. if ( this.rotationAutoUpdate === true ) {
  3787. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3788. }
  3789. };
  3790. /**
  3791. * @author alteredq / http://alteredqualia.com/
  3792. */
  3793. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  3794. THREE.Camera.call( this );
  3795. this.left = left;
  3796. this.right = right;
  3797. this.top = top;
  3798. this.bottom = bottom;
  3799. this.near = ( near !== undefined ) ? near : 0.1;
  3800. this.far = ( far !== undefined ) ? far : 2000;
  3801. this.updateProjectionMatrix();
  3802. };
  3803. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  3804. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  3805. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  3806. };
  3807. /**
  3808. * @author mrdoob / http://mrdoob.com/
  3809. * @author greggman / http://games.greggman.com/
  3810. * @author zz85 / http://www.lab4games.net/zz85/blog
  3811. */
  3812. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  3813. THREE.Camera.call( this );
  3814. this.fov = fov !== undefined ? fov : 50;
  3815. this.aspect = aspect !== undefined ? aspect : 1;
  3816. this.near = near !== undefined ? near : 0.1;
  3817. this.far = far !== undefined ? far : 2000;
  3818. this.updateProjectionMatrix();
  3819. };
  3820. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  3821. /**
  3822. * Uses Focal Length (in mm) to estimate and set FOV
  3823. * 35mm (fullframe) camera is used if frame size is not specified;
  3824. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  3825. */
  3826. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  3827. if ( frameHeight === undefined ) frameHeight = 24;
  3828. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  3829. this.updateProjectionMatrix();
  3830. }
  3831. /**
  3832. * Sets an offset in a larger frustum. This is useful for multi-window or
  3833. * multi-monitor/multi-machine setups.
  3834. *
  3835. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  3836. * the monitors are in grid like this
  3837. *
  3838. * +---+---+---+
  3839. * | A | B | C |
  3840. * +---+---+---+
  3841. * | D | E | F |
  3842. * +---+---+---+
  3843. *
  3844. * then for each monitor you would call it like this
  3845. *
  3846. * var w = 1920;
  3847. * var h = 1080;
  3848. * var fullWidth = w * 3;
  3849. * var fullHeight = h * 2;
  3850. *
  3851. * --A--
  3852. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  3853. * --B--
  3854. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  3855. * --C--
  3856. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  3857. * --D--
  3858. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  3859. * --E--
  3860. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  3861. * --F--
  3862. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  3863. *
  3864. * Note there is no reason monitors have to be the same size or in a grid.
  3865. */
  3866. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  3867. this.fullWidth = fullWidth;
  3868. this.fullHeight = fullHeight;
  3869. this.x = x;
  3870. this.y = y;
  3871. this.width = width;
  3872. this.height = height;
  3873. this.updateProjectionMatrix();
  3874. };
  3875. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  3876. if ( this.fullWidth ) {
  3877. var aspect = this.fullWidth / this.fullHeight;
  3878. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  3879. var bottom = -top;
  3880. var left = aspect * bottom;
  3881. var right = aspect * top;
  3882. var width = Math.abs( right - left );
  3883. var height = Math.abs( top - bottom );
  3884. this.projectionMatrix.makeFrustum(
  3885. left + this.x * width / this.fullWidth,
  3886. left + ( this.x + this.width ) * width / this.fullWidth,
  3887. top - ( this.y + this.height ) * height / this.fullHeight,
  3888. top - this.y * height / this.fullHeight,
  3889. this.near,
  3890. this.far
  3891. );
  3892. } else {
  3893. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  3894. }
  3895. };
  3896. /**
  3897. * @author mrdoob / http://mrdoob.com/
  3898. * @author alteredq / http://alteredqualia.com/
  3899. */
  3900. THREE.Light = function ( hex ) {
  3901. THREE.Object3D.call( this );
  3902. this.color = new THREE.Color( hex );
  3903. };
  3904. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  3905. /**
  3906. * @author mrdoob / http://mrdoob.com/
  3907. */
  3908. THREE.AmbientLight = function ( hex ) {
  3909. THREE.Light.call( this, hex );
  3910. };
  3911. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  3912. /**
  3913. * @author mrdoob / http://mrdoob.com/
  3914. * @author alteredq / http://alteredqualia.com/
  3915. */
  3916. THREE.DirectionalLight = function ( hex, intensity, distance ) {
  3917. THREE.Light.call( this, hex );
  3918. this.position = new THREE.Vector3( 0, 1, 0 );
  3919. this.target = new THREE.Object3D();
  3920. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3921. this.distance = ( distance !== undefined ) ? distance : 0;
  3922. this.castShadow = false;
  3923. this.onlyShadow = false;
  3924. //
  3925. this.shadowCameraNear = 50;
  3926. this.shadowCameraFar = 5000;
  3927. this.shadowCameraLeft = -500;
  3928. this.shadowCameraRight = 500;
  3929. this.shadowCameraTop = 500;
  3930. this.shadowCameraBottom = -500;
  3931. this.shadowCameraVisible = false;
  3932. this.shadowBias = 0;
  3933. this.shadowDarkness = 0.5;
  3934. this.shadowMapWidth = 512;
  3935. this.shadowMapHeight = 512;
  3936. //
  3937. this.shadowCascade = false;
  3938. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  3939. this.shadowCascadeCount = 2;
  3940. this.shadowCascadeBias = [ 0, 0, 0 ];
  3941. this.shadowCascadeWidth = [ 512, 512, 512 ];
  3942. this.shadowCascadeHeight = [ 512, 512, 512 ];
  3943. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  3944. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  3945. this.shadowCascadeArray = [];
  3946. //
  3947. this.shadowMap = null;
  3948. this.shadowMapSize = null;
  3949. this.shadowCamera = null;
  3950. this.shadowMatrix = null;
  3951. };
  3952. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  3953. /**
  3954. * @author alteredq / http://alteredqualia.com/
  3955. */
  3956. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  3957. THREE.Light.call( this, skyColorHex );
  3958. this.groundColor = new THREE.Color( groundColorHex );
  3959. this.position = new THREE.Vector3( 0, 100, 0 );
  3960. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3961. };
  3962. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  3963. /**
  3964. * @author mrdoob / http://mrdoob.com/
  3965. */
  3966. THREE.PointLight = function ( hex, intensity, distance ) {
  3967. THREE.Light.call( this, hex );
  3968. this.position = new THREE.Vector3( 0, 0, 0 );
  3969. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3970. this.distance = ( distance !== undefined ) ? distance : 0;
  3971. };
  3972. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  3973. /**
  3974. * @author alteredq / http://alteredqualia.com/
  3975. */
  3976. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  3977. THREE.Light.call( this, hex );
  3978. this.position = new THREE.Vector3( 0, 1, 0 );
  3979. this.target = new THREE.Object3D();
  3980. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3981. this.distance = ( distance !== undefined ) ? distance : 0;
  3982. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  3983. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  3984. this.castShadow = false;
  3985. this.onlyShadow = false;
  3986. //
  3987. this.shadowCameraNear = 50;
  3988. this.shadowCameraFar = 5000;
  3989. this.shadowCameraFov = 50;
  3990. this.shadowCameraVisible = false;
  3991. this.shadowBias = 0;
  3992. this.shadowDarkness = 0.5;
  3993. this.shadowMapWidth = 512;
  3994. this.shadowMapHeight = 512;
  3995. //
  3996. this.shadowMap = null;
  3997. this.shadowMapSize = null;
  3998. this.shadowCamera = null;
  3999. this.shadowMatrix = null;
  4000. };
  4001. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  4002. /**
  4003. * @author alteredq / http://alteredqualia.com/
  4004. */
  4005. THREE.Loader = function ( showStatus ) {
  4006. this.showStatus = showStatus;
  4007. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  4008. this.onLoadStart = function () {};
  4009. this.onLoadProgress = function () {};
  4010. this.onLoadComplete = function () {};
  4011. };
  4012. THREE.Loader.prototype = {
  4013. constructor: THREE.Loader,
  4014. crossOrigin: 'anonymous',
  4015. addStatusElement: function () {
  4016. var e = document.createElement( "div" );
  4017. e.style.position = "absolute";
  4018. e.style.right = "0px";
  4019. e.style.top = "0px";
  4020. e.style.fontSize = "0.8em";
  4021. e.style.textAlign = "left";
  4022. e.style.background = "rgba(0,0,0,0.25)";
  4023. e.style.color = "#fff";
  4024. e.style.width = "120px";
  4025. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  4026. e.style.zIndex = 1000;
  4027. e.innerHTML = "Loading ...";
  4028. return e;
  4029. },
  4030. updateProgress: function ( progress ) {
  4031. var message = "Loaded ";
  4032. if ( progress.total ) {
  4033. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  4034. } else {
  4035. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  4036. }
  4037. this.statusDomElement.innerHTML = message;
  4038. },
  4039. extractUrlBase: function ( url ) {
  4040. var parts = url.split( '/' );
  4041. parts.pop();
  4042. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  4043. },
  4044. initMaterials: function ( scope, materials, texturePath ) {
  4045. scope.materials = [];
  4046. for ( var i = 0; i < materials.length; ++ i ) {
  4047. scope.materials[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  4048. }
  4049. },
  4050. hasNormals: function ( scope ) {
  4051. var m, i, il = scope.materials.length;
  4052. for( i = 0; i < il; i ++ ) {
  4053. m = scope.materials[ i ];
  4054. if ( m instanceof THREE.ShaderMaterial ) return true;
  4055. }
  4056. return false;
  4057. },
  4058. createMaterial: function ( m, texturePath ) {
  4059. var _this = this;
  4060. function is_pow2( n ) {
  4061. var l = Math.log( n ) / Math.LN2;
  4062. return Math.floor( l ) == l;
  4063. }
  4064. function nearest_pow2( n ) {
  4065. var l = Math.log( n ) / Math.LN2;
  4066. return Math.pow( 2, Math.round( l ) );
  4067. }
  4068. function load_image( where, url ) {
  4069. var image = new Image();
  4070. image.onload = function () {
  4071. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  4072. var width = nearest_pow2( this.width );
  4073. var height = nearest_pow2( this.height );
  4074. where.image.width = width;
  4075. where.image.height = height;
  4076. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  4077. } else {
  4078. where.image = this;
  4079. }
  4080. where.needsUpdate = true;
  4081. };
  4082. image.crossOrigin = _this.crossOrigin;
  4083. image.src = url;
  4084. }
  4085. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  4086. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  4087. var fullPath = texturePath + "/" + sourceFile;
  4088. if ( isCompressed ) {
  4089. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  4090. where[ name ] = texture;
  4091. } else {
  4092. var texture = document.createElement( 'canvas' );
  4093. where[ name ] = new THREE.Texture( texture );
  4094. }
  4095. where[ name ].sourceFile = sourceFile;
  4096. if( repeat ) {
  4097. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4098. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4099. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4100. }
  4101. if ( offset ) {
  4102. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4103. }
  4104. if ( wrap ) {
  4105. var wrapMap = {
  4106. "repeat": THREE.RepeatWrapping,
  4107. "mirror": THREE.MirroredRepeatWrapping
  4108. }
  4109. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4110. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4111. }
  4112. if ( anisotropy ) {
  4113. where[ name ].anisotropy = anisotropy;
  4114. }
  4115. if ( ! isCompressed ) {
  4116. load_image( where[ name ], fullPath );
  4117. }
  4118. }
  4119. function rgb2hex( rgb ) {
  4120. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4121. }
  4122. // defaults
  4123. var mtype = "MeshLambertMaterial";
  4124. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4125. // parameters from model file
  4126. if ( m.shading ) {
  4127. var shading = m.shading.toLowerCase();
  4128. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4129. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4130. }
  4131. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4132. mpars.blending = THREE[ m.blending ];
  4133. }
  4134. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4135. mpars.transparent = m.transparent;
  4136. }
  4137. if ( m.depthTest !== undefined ) {
  4138. mpars.depthTest = m.depthTest;
  4139. }
  4140. if ( m.depthWrite !== undefined ) {
  4141. mpars.depthWrite = m.depthWrite;
  4142. }
  4143. if ( m.visible !== undefined ) {
  4144. mpars.visible = m.visible;
  4145. }
  4146. if ( m.flipSided !== undefined ) {
  4147. mpars.side = THREE.BackSide;
  4148. }
  4149. if ( m.doubleSided !== undefined ) {
  4150. mpars.side = THREE.DoubleSide;
  4151. }
  4152. if ( m.wireframe !== undefined ) {
  4153. mpars.wireframe = m.wireframe;
  4154. }
  4155. if ( m.vertexColors !== undefined ) {
  4156. if ( m.vertexColors === "face" ) {
  4157. mpars.vertexColors = THREE.FaceColors;
  4158. } else if ( m.vertexColors ) {
  4159. mpars.vertexColors = THREE.VertexColors;
  4160. }
  4161. }
  4162. // colors
  4163. if ( m.colorDiffuse ) {
  4164. mpars.color = rgb2hex( m.colorDiffuse );
  4165. } else if ( m.DbgColor ) {
  4166. mpars.color = m.DbgColor;
  4167. }
  4168. if ( m.colorSpecular ) {
  4169. mpars.specular = rgb2hex( m.colorSpecular );
  4170. }
  4171. if ( m.colorAmbient ) {
  4172. mpars.ambient = rgb2hex( m.colorAmbient );
  4173. }
  4174. // modifiers
  4175. if ( m.transparency ) {
  4176. mpars.opacity = m.transparency;
  4177. }
  4178. if ( m.specularCoef ) {
  4179. mpars.shininess = m.specularCoef;
  4180. }
  4181. // textures
  4182. if ( m.mapDiffuse && texturePath ) {
  4183. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  4184. }
  4185. if ( m.mapLight && texturePath ) {
  4186. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  4187. }
  4188. if ( m.mapBump && texturePath ) {
  4189. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  4190. }
  4191. if ( m.mapNormal && texturePath ) {
  4192. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  4193. }
  4194. if ( m.mapSpecular && texturePath ) {
  4195. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  4196. }
  4197. //
  4198. if ( m.mapBumpScale ) {
  4199. mpars.bumpScale = m.mapBumpScale;
  4200. }
  4201. // special case for normal mapped material
  4202. if ( m.mapNormal ) {
  4203. var shader = THREE.ShaderUtils.lib[ "normal" ];
  4204. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  4205. uniforms[ "tNormal" ].value = mpars.normalMap;
  4206. if ( m.mapNormalFactor ) {
  4207. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  4208. }
  4209. if ( mpars.map ) {
  4210. uniforms[ "tDiffuse" ].value = mpars.map;
  4211. uniforms[ "enableDiffuse" ].value = true;
  4212. }
  4213. if ( mpars.specularMap ) {
  4214. uniforms[ "tSpecular" ].value = mpars.specularMap;
  4215. uniforms[ "enableSpecular" ].value = true;
  4216. }
  4217. if ( mpars.lightMap ) {
  4218. uniforms[ "tAO" ].value = mpars.lightMap;
  4219. uniforms[ "enableAO" ].value = true;
  4220. }
  4221. // for the moment don't handle displacement texture
  4222. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  4223. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  4224. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  4225. uniforms[ "uShininess" ].value = mpars.shininess;
  4226. if ( mpars.opacity !== undefined ) {
  4227. uniforms[ "uOpacity" ].value = mpars.opacity;
  4228. }
  4229. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  4230. var material = new THREE.ShaderMaterial( parameters );
  4231. } else {
  4232. var material = new THREE[ mtype ]( mpars );
  4233. }
  4234. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  4235. return material;
  4236. }
  4237. };
  4238. /**
  4239. * @author alteredq / http://alteredqualia.com/
  4240. */
  4241. THREE.BinaryLoader = function ( showStatus ) {
  4242. THREE.Loader.call( this, showStatus );
  4243. };
  4244. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  4245. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  4246. // - binary models consist of two files: JS and BIN
  4247. // - parameters
  4248. // - url (required)
  4249. // - callback (required)
  4250. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  4251. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  4252. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  4253. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  4254. binaryPath = binaryPath ? binaryPath : this.extractUrlBase( url );
  4255. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  4256. this.onLoadStart();
  4257. // #1 load JS part via web worker
  4258. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  4259. };
  4260. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  4261. var xhr = new XMLHttpRequest();
  4262. xhr.onreadystatechange = function () {
  4263. if ( xhr.readyState == 4 ) {
  4264. if ( xhr.status == 200 || xhr.status == 0 ) {
  4265. var json = JSON.parse( xhr.responseText );
  4266. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  4267. } else {
  4268. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4269. }
  4270. }
  4271. };
  4272. xhr.open( "GET", url, true );
  4273. xhr.send( null );
  4274. };
  4275. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  4276. var xhr = new XMLHttpRequest(),
  4277. url = binaryPath + "/" + json.buffers;
  4278. var length = 0;
  4279. xhr.onreadystatechange = function () {
  4280. if ( xhr.readyState == 4 ) {
  4281. if ( xhr.status == 200 || xhr.status == 0 ) {
  4282. var buffer = xhr.response;
  4283. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  4284. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  4285. } else {
  4286. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4287. }
  4288. } else if ( xhr.readyState == 3 ) {
  4289. if ( callbackProgress ) {
  4290. if ( length == 0 ) {
  4291. length = xhr.getResponseHeader( "Content-Length" );
  4292. }
  4293. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4294. }
  4295. } else if ( xhr.readyState == 2 ) {
  4296. length = xhr.getResponseHeader( "Content-Length" );
  4297. }
  4298. };
  4299. xhr.open( "GET", url, true );
  4300. xhr.responseType = "arraybuffer";
  4301. xhr.send( null );
  4302. };
  4303. // Binary AJAX parser
  4304. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, materials ) {
  4305. var Model = function ( texturePath ) {
  4306. var scope = this,
  4307. currentOffset = 0,
  4308. md,
  4309. normals = [],
  4310. uvs = [],
  4311. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  4312. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  4313. tri_size, quad_size,
  4314. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  4315. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  4316. THREE.Geometry.call( this );
  4317. THREE.Loader.prototype.initMaterials( scope, materials, texturePath );
  4318. md = parseMetaData( data, currentOffset );
  4319. currentOffset += md.header_bytes;
  4320. /*
  4321. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4322. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  4323. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4324. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4325. */
  4326. // buffers sizes
  4327. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  4328. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  4329. len_tri_flat = md.ntri_flat * ( tri_size );
  4330. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  4331. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  4332. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  4333. len_quad_flat = md.nquad_flat * ( quad_size );
  4334. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  4335. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  4336. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  4337. // read buffers
  4338. currentOffset += init_vertices( currentOffset );
  4339. currentOffset += init_normals( currentOffset );
  4340. currentOffset += handlePadding( md.nnormals * 3 );
  4341. currentOffset += init_uvs( currentOffset );
  4342. start_tri_flat = currentOffset;
  4343. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  4344. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  4345. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  4346. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  4347. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  4348. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  4349. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  4350. // have to first process faces with uvs
  4351. // so that face and uv indices match
  4352. init_triangles_flat_uv( start_tri_flat_uv );
  4353. init_triangles_smooth_uv( start_tri_smooth_uv );
  4354. init_quads_flat_uv( start_quad_flat_uv );
  4355. init_quads_smooth_uv( start_quad_smooth_uv );
  4356. // now we can process untextured faces
  4357. init_triangles_flat( start_tri_flat );
  4358. init_triangles_smooth( start_tri_smooth );
  4359. init_quads_flat( start_quad_flat );
  4360. init_quads_smooth( start_quad_smooth );
  4361. this.computeCentroids();
  4362. this.computeFaceNormals();
  4363. if ( THREE.Loader.prototype.hasNormals( this ) ) this.computeTangents();
  4364. function handlePadding( n ) {
  4365. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  4366. };
  4367. function parseMetaData( data, offset ) {
  4368. var metaData = {
  4369. 'signature' :parseString( data, offset, 12 ),
  4370. 'header_bytes' :parseUChar8( data, offset + 12 ),
  4371. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  4372. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  4373. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  4374. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  4375. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  4376. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  4377. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  4378. 'nvertices' :parseUInt32( data, offset + 20 ),
  4379. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  4380. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  4381. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  4382. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  4383. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  4384. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  4385. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  4386. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  4387. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  4388. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  4389. };
  4390. /*
  4391. console.log( "signature: " + metaData.signature );
  4392. console.log( "header_bytes: " + metaData.header_bytes );
  4393. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  4394. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  4395. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  4396. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  4397. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  4398. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  4399. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  4400. console.log( "nvertices: " + metaData.nvertices );
  4401. console.log( "nnormals: " + metaData.nnormals );
  4402. console.log( "nuvs: " + metaData.nuvs );
  4403. console.log( "ntri_flat: " + metaData.ntri_flat );
  4404. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  4405. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  4406. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  4407. console.log( "nquad_flat: " + metaData.nquad_flat );
  4408. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  4409. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  4410. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  4411. var total = metaData.header_bytes
  4412. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  4413. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  4414. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  4415. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  4416. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  4417. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  4418. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  4419. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  4420. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  4421. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  4422. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  4423. console.log( "total bytes: " + total );
  4424. */
  4425. return metaData;
  4426. };
  4427. function parseString( data, offset, length ) {
  4428. var charArray = new Uint8Array( data, offset, length );
  4429. var text = "";
  4430. for ( var i = 0; i < length; i ++ ) {
  4431. text += String.fromCharCode( charArray[ offset + i ] );
  4432. }
  4433. return text;
  4434. };
  4435. function parseUChar8( data, offset ) {
  4436. var charArray = new Uint8Array( data, offset, 1 );
  4437. return charArray[ 0 ];
  4438. };
  4439. function parseUInt32( data, offset ) {
  4440. var intArray = new Uint32Array( data, offset, 1 );
  4441. return intArray[ 0 ];
  4442. };
  4443. function init_vertices( start ) {
  4444. var nElements = md.nvertices;
  4445. var coordArray = new Float32Array( data, start, nElements * 3 );
  4446. var i, x, y, z;
  4447. for( i = 0; i < nElements; i ++ ) {
  4448. x = coordArray[ i * 3 ];
  4449. y = coordArray[ i * 3 + 1 ];
  4450. z = coordArray[ i * 3 + 2 ];
  4451. vertex( scope, x, y, z );
  4452. }
  4453. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  4454. };
  4455. function init_normals( start ) {
  4456. var nElements = md.nnormals;
  4457. if ( nElements ) {
  4458. var normalArray = new Int8Array( data, start, nElements * 3 );
  4459. var i, x, y, z;
  4460. for( i = 0; i < nElements; i ++ ) {
  4461. x = normalArray[ i * 3 ];
  4462. y = normalArray[ i * 3 + 1 ];
  4463. z = normalArray[ i * 3 + 2 ];
  4464. normals.push( x/127, y/127, z/127 );
  4465. }
  4466. }
  4467. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  4468. };
  4469. function init_uvs( start ) {
  4470. var nElements = md.nuvs;
  4471. if ( nElements ) {
  4472. var uvArray = new Float32Array( data, start, nElements * 2 );
  4473. var i, u, v;
  4474. for( i = 0; i < nElements; i ++ ) {
  4475. u = uvArray[ i * 2 ];
  4476. v = uvArray[ i * 2 + 1 ];
  4477. uvs.push( u, v );
  4478. }
  4479. }
  4480. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  4481. };
  4482. function init_uvs3( nElements, offset ) {
  4483. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  4484. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  4485. for( i = 0; i < nElements; i ++ ) {
  4486. uva = uvIndexBuffer[ i * 3 ];
  4487. uvb = uvIndexBuffer[ i * 3 + 1 ];
  4488. uvc = uvIndexBuffer[ i * 3 + 2 ];
  4489. u1 = uvs[ uva*2 ];
  4490. v1 = uvs[ uva*2 + 1 ];
  4491. u2 = uvs[ uvb*2 ];
  4492. v2 = uvs[ uvb*2 + 1 ];
  4493. u3 = uvs[ uvc*2 ];
  4494. v3 = uvs[ uvc*2 + 1 ];
  4495. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  4496. }
  4497. };
  4498. function init_uvs4( nElements, offset ) {
  4499. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  4500. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  4501. for( i = 0; i < nElements; i ++ ) {
  4502. uva = uvIndexBuffer[ i * 4 ];
  4503. uvb = uvIndexBuffer[ i * 4 + 1 ];
  4504. uvc = uvIndexBuffer[ i * 4 + 2 ];
  4505. uvd = uvIndexBuffer[ i * 4 + 3 ];
  4506. u1 = uvs[ uva*2 ];
  4507. v1 = uvs[ uva*2 + 1 ];
  4508. u2 = uvs[ uvb*2 ];
  4509. v2 = uvs[ uvb*2 + 1 ];
  4510. u3 = uvs[ uvc*2 ];
  4511. v3 = uvs[ uvc*2 + 1 ];
  4512. u4 = uvs[ uvd*2 ];
  4513. v4 = uvs[ uvd*2 + 1 ];
  4514. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  4515. }
  4516. };
  4517. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  4518. var i, a, b, c, m;
  4519. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4520. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4521. for( i = 0; i < nElements; i ++ ) {
  4522. a = vertexIndexBuffer[ i * 3 ];
  4523. b = vertexIndexBuffer[ i * 3 + 1 ];
  4524. c = vertexIndexBuffer[ i * 3 + 2 ];
  4525. m = materialIndexBuffer[ i ];
  4526. f3( scope, a, b, c, m );
  4527. }
  4528. };
  4529. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  4530. var i, a, b, c, d, m;
  4531. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4532. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4533. for( i = 0; i < nElements; i ++ ) {
  4534. a = vertexIndexBuffer[ i * 4 ];
  4535. b = vertexIndexBuffer[ i * 4 + 1 ];
  4536. c = vertexIndexBuffer[ i * 4 + 2 ];
  4537. d = vertexIndexBuffer[ i * 4 + 3 ];
  4538. m = materialIndexBuffer[ i ];
  4539. f4( scope, a, b, c, d, m );
  4540. }
  4541. };
  4542. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4543. var i, a, b, c, m;
  4544. var na, nb, nc;
  4545. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4546. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  4547. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4548. for( i = 0; i < nElements; i ++ ) {
  4549. a = vertexIndexBuffer[ i * 3 ];
  4550. b = vertexIndexBuffer[ i * 3 + 1 ];
  4551. c = vertexIndexBuffer[ i * 3 + 2 ];
  4552. na = normalIndexBuffer[ i * 3 ];
  4553. nb = normalIndexBuffer[ i * 3 + 1 ];
  4554. nc = normalIndexBuffer[ i * 3 + 2 ];
  4555. m = materialIndexBuffer[ i ];
  4556. f3n( scope, normals, a, b, c, m, na, nb, nc );
  4557. }
  4558. };
  4559. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4560. var i, a, b, c, d, m;
  4561. var na, nb, nc, nd;
  4562. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4563. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  4564. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4565. for( i = 0; i < nElements; i ++ ) {
  4566. a = vertexIndexBuffer[ i * 4 ];
  4567. b = vertexIndexBuffer[ i * 4 + 1 ];
  4568. c = vertexIndexBuffer[ i * 4 + 2 ];
  4569. d = vertexIndexBuffer[ i * 4 + 3 ];
  4570. na = normalIndexBuffer[ i * 4 ];
  4571. nb = normalIndexBuffer[ i * 4 + 1 ];
  4572. nc = normalIndexBuffer[ i * 4 + 2 ];
  4573. nd = normalIndexBuffer[ i * 4 + 3 ];
  4574. m = materialIndexBuffer[ i ];
  4575. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  4576. }
  4577. };
  4578. function init_triangles_flat( start ) {
  4579. var nElements = md.ntri_flat;
  4580. if ( nElements ) {
  4581. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4582. init_faces3_flat( nElements, start, offsetMaterials );
  4583. }
  4584. };
  4585. function init_triangles_flat_uv( start ) {
  4586. var nElements = md.ntri_flat_uv;
  4587. if ( nElements ) {
  4588. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4589. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4590. init_faces3_flat( nElements, start, offsetMaterials );
  4591. init_uvs3( nElements, offsetUvs );
  4592. }
  4593. };
  4594. function init_triangles_smooth( start ) {
  4595. var nElements = md.ntri_smooth;
  4596. if ( nElements ) {
  4597. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4598. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4599. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4600. }
  4601. };
  4602. function init_triangles_smooth_uv( start ) {
  4603. var nElements = md.ntri_smooth_uv;
  4604. if ( nElements ) {
  4605. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4606. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4607. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4608. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4609. init_uvs3( nElements, offsetUvs );
  4610. }
  4611. };
  4612. function init_quads_flat( start ) {
  4613. var nElements = md.nquad_flat;
  4614. if ( nElements ) {
  4615. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4616. init_faces4_flat( nElements, start, offsetMaterials );
  4617. }
  4618. };
  4619. function init_quads_flat_uv( start ) {
  4620. var nElements = md.nquad_flat_uv;
  4621. if ( nElements ) {
  4622. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4623. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4624. init_faces4_flat( nElements, start, offsetMaterials );
  4625. init_uvs4( nElements, offsetUvs );
  4626. }
  4627. };
  4628. function init_quads_smooth( start ) {
  4629. var nElements = md.nquad_smooth;
  4630. if ( nElements ) {
  4631. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4632. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4633. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4634. }
  4635. };
  4636. function init_quads_smooth_uv( start ) {
  4637. var nElements = md.nquad_smooth_uv;
  4638. if ( nElements ) {
  4639. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4640. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4641. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4642. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4643. init_uvs4( nElements, offsetUvs );
  4644. }
  4645. };
  4646. };
  4647. function vertex ( scope, x, y, z ) {
  4648. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  4649. };
  4650. function f3 ( scope, a, b, c, mi ) {
  4651. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  4652. };
  4653. function f4 ( scope, a, b, c, d, mi ) {
  4654. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  4655. };
  4656. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  4657. var nax = normals[ na*3 ],
  4658. nay = normals[ na*3 + 1 ],
  4659. naz = normals[ na*3 + 2 ],
  4660. nbx = normals[ nb*3 ],
  4661. nby = normals[ nb*3 + 1 ],
  4662. nbz = normals[ nb*3 + 2 ],
  4663. ncx = normals[ nc*3 ],
  4664. ncy = normals[ nc*3 + 1 ],
  4665. ncz = normals[ nc*3 + 2 ];
  4666. scope.faces.push( new THREE.Face3( a, b, c,
  4667. [new THREE.Vector3( nax, nay, naz ),
  4668. new THREE.Vector3( nbx, nby, nbz ),
  4669. new THREE.Vector3( ncx, ncy, ncz )],
  4670. null,
  4671. mi ) );
  4672. };
  4673. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  4674. var nax = normals[ na*3 ],
  4675. nay = normals[ na*3 + 1 ],
  4676. naz = normals[ na*3 + 2 ],
  4677. nbx = normals[ nb*3 ],
  4678. nby = normals[ nb*3 + 1 ],
  4679. nbz = normals[ nb*3 + 2 ],
  4680. ncx = normals[ nc*3 ],
  4681. ncy = normals[ nc*3 + 1 ],
  4682. ncz = normals[ nc*3 + 2 ],
  4683. ndx = normals[ nd*3 ],
  4684. ndy = normals[ nd*3 + 1 ],
  4685. ndz = normals[ nd*3 + 2 ];
  4686. scope.faces.push( new THREE.Face4( a, b, c, d,
  4687. [new THREE.Vector3( nax, nay, naz ),
  4688. new THREE.Vector3( nbx, nby, nbz ),
  4689. new THREE.Vector3( ncx, ncy, ncz ),
  4690. new THREE.Vector3( ndx, ndy, ndz )],
  4691. null,
  4692. mi ) );
  4693. };
  4694. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  4695. var uv = [];
  4696. uv.push( new THREE.UV( u1, v1 ) );
  4697. uv.push( new THREE.UV( u2, v2 ) );
  4698. uv.push( new THREE.UV( u3, v3 ) );
  4699. where.push( uv );
  4700. };
  4701. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  4702. var uv = [];
  4703. uv.push( new THREE.UV( u1, v1 ) );
  4704. uv.push( new THREE.UV( u2, v2 ) );
  4705. uv.push( new THREE.UV( u3, v3 ) );
  4706. uv.push( new THREE.UV( u4, v4 ) );
  4707. where.push( uv );
  4708. };
  4709. Model.prototype = Object.create( THREE.Geometry.prototype );
  4710. callback( new Model( texturePath ) );
  4711. };
  4712. /**
  4713. * @author mrdoob / http://mrdoob.com/
  4714. */
  4715. THREE.ImageLoader = function () {
  4716. THREE.EventTarget.call( this );
  4717. this.crossOrigin = null;
  4718. };
  4719. THREE.ImageLoader.prototype = {
  4720. constructor: THREE.ImageLoader,
  4721. load: function ( url, image ) {
  4722. var scope = this;
  4723. if ( image === undefined ) image = new Image();
  4724. image.addEventListener( 'load', function () {
  4725. scope.dispatchEvent( { type: 'load', content: image } );
  4726. }, false );
  4727. image.addEventListener( 'error', function () {
  4728. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4729. }, false );
  4730. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  4731. image.src = url;
  4732. }
  4733. }
  4734. /**
  4735. * @author mrdoob / http://mrdoob.com/
  4736. * @author alteredq / http://alteredqualia.com/
  4737. */
  4738. THREE.JSONLoader = function ( showStatus ) {
  4739. THREE.Loader.call( this, showStatus );
  4740. };
  4741. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  4742. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  4743. var scope = this;
  4744. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  4745. this.onLoadStart();
  4746. this.loadAjaxJSON( this, url, callback, texturePath );
  4747. };
  4748. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  4749. var xhr = new XMLHttpRequest();
  4750. var length = 0;
  4751. xhr.onreadystatechange = function () {
  4752. if ( xhr.readyState === xhr.DONE ) {
  4753. if ( xhr.status === 200 || xhr.status === 0 ) {
  4754. if ( xhr.responseText ) {
  4755. var json = JSON.parse( xhr.responseText );
  4756. context.createModel( json, callback, texturePath );
  4757. } else {
  4758. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  4759. }
  4760. // in context of more complex asset initialization
  4761. // do not block on single failed file
  4762. // maybe should go even one more level up
  4763. context.onLoadComplete();
  4764. } else {
  4765. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4766. }
  4767. } else if ( xhr.readyState === xhr.LOADING ) {
  4768. if ( callbackProgress ) {
  4769. if ( length === 0 ) {
  4770. length = xhr.getResponseHeader( "Content-Length" );
  4771. }
  4772. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4773. }
  4774. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  4775. length = xhr.getResponseHeader( "Content-Length" );
  4776. }
  4777. };
  4778. xhr.open( "GET", url, true );
  4779. xhr.send( null );
  4780. };
  4781. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  4782. var scope = this,
  4783. geometry = new THREE.Geometry(),
  4784. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  4785. this.initMaterials( geometry, json.materials, texturePath );
  4786. parseModel( scale );
  4787. parseSkin();
  4788. parseMorphing( scale );
  4789. geometry.computeCentroids();
  4790. geometry.computeFaceNormals();
  4791. if ( this.hasNormals( geometry ) ) geometry.computeTangents();
  4792. function parseModel( scale ) {
  4793. function isBitSet( value, position ) {
  4794. return value & ( 1 << position );
  4795. }
  4796. var i, j, fi,
  4797. offset, zLength, nVertices,
  4798. colorIndex, normalIndex, uvIndex, materialIndex,
  4799. type,
  4800. isQuad,
  4801. hasMaterial,
  4802. hasFaceUv, hasFaceVertexUv,
  4803. hasFaceNormal, hasFaceVertexNormal,
  4804. hasFaceColor, hasFaceVertexColor,
  4805. vertex, face, color, normal,
  4806. uvLayer, uvs, u, v,
  4807. faces = json.faces,
  4808. vertices = json.vertices,
  4809. normals = json.normals,
  4810. colors = json.colors,
  4811. nUvLayers = 0;
  4812. // disregard empty arrays
  4813. for ( i = 0; i < json.uvs.length; i++ ) {
  4814. if ( json.uvs[ i ].length ) nUvLayers ++;
  4815. }
  4816. for ( i = 0; i < nUvLayers; i++ ) {
  4817. geometry.faceUvs[ i ] = [];
  4818. geometry.faceVertexUvs[ i ] = [];
  4819. }
  4820. offset = 0;
  4821. zLength = vertices.length;
  4822. while ( offset < zLength ) {
  4823. vertex = new THREE.Vector3();
  4824. vertex.x = vertices[ offset ++ ] * scale;
  4825. vertex.y = vertices[ offset ++ ] * scale;
  4826. vertex.z = vertices[ offset ++ ] * scale;
  4827. geometry.vertices.push( vertex );
  4828. }
  4829. offset = 0;
  4830. zLength = faces.length;
  4831. while ( offset < zLength ) {
  4832. type = faces[ offset ++ ];
  4833. isQuad = isBitSet( type, 0 );
  4834. hasMaterial = isBitSet( type, 1 );
  4835. hasFaceUv = isBitSet( type, 2 );
  4836. hasFaceVertexUv = isBitSet( type, 3 );
  4837. hasFaceNormal = isBitSet( type, 4 );
  4838. hasFaceVertexNormal = isBitSet( type, 5 );
  4839. hasFaceColor = isBitSet( type, 6 );
  4840. hasFaceVertexColor = isBitSet( type, 7 );
  4841. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  4842. if ( isQuad ) {
  4843. face = new THREE.Face4();
  4844. face.a = faces[ offset ++ ];
  4845. face.b = faces[ offset ++ ];
  4846. face.c = faces[ offset ++ ];
  4847. face.d = faces[ offset ++ ];
  4848. nVertices = 4;
  4849. } else {
  4850. face = new THREE.Face3();
  4851. face.a = faces[ offset ++ ];
  4852. face.b = faces[ offset ++ ];
  4853. face.c = faces[ offset ++ ];
  4854. nVertices = 3;
  4855. }
  4856. if ( hasMaterial ) {
  4857. materialIndex = faces[ offset ++ ];
  4858. face.materialIndex = materialIndex;
  4859. }
  4860. // to get face <=> uv index correspondence
  4861. fi = geometry.faces.length;
  4862. if ( hasFaceUv ) {
  4863. for ( i = 0; i < nUvLayers; i++ ) {
  4864. uvLayer = json.uvs[ i ];
  4865. uvIndex = faces[ offset ++ ];
  4866. u = uvLayer[ uvIndex * 2 ];
  4867. v = uvLayer[ uvIndex * 2 + 1 ];
  4868. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  4869. }
  4870. }
  4871. if ( hasFaceVertexUv ) {
  4872. for ( i = 0; i < nUvLayers; i++ ) {
  4873. uvLayer = json.uvs[ i ];
  4874. uvs = [];
  4875. for ( j = 0; j < nVertices; j ++ ) {
  4876. uvIndex = faces[ offset ++ ];
  4877. u = uvLayer[ uvIndex * 2 ];
  4878. v = uvLayer[ uvIndex * 2 + 1 ];
  4879. uvs[ j ] = new THREE.UV( u, v );
  4880. }
  4881. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  4882. }
  4883. }
  4884. if ( hasFaceNormal ) {
  4885. normalIndex = faces[ offset ++ ] * 3;
  4886. normal = new THREE.Vector3();
  4887. normal.x = normals[ normalIndex ++ ];
  4888. normal.y = normals[ normalIndex ++ ];
  4889. normal.z = normals[ normalIndex ];
  4890. face.normal = normal;
  4891. }
  4892. if ( hasFaceVertexNormal ) {
  4893. for ( i = 0; i < nVertices; i++ ) {
  4894. normalIndex = faces[ offset ++ ] * 3;
  4895. normal = new THREE.Vector3();
  4896. normal.x = normals[ normalIndex ++ ];
  4897. normal.y = normals[ normalIndex ++ ];
  4898. normal.z = normals[ normalIndex ];
  4899. face.vertexNormals.push( normal );
  4900. }
  4901. }
  4902. if ( hasFaceColor ) {
  4903. colorIndex = faces[ offset ++ ];
  4904. color = new THREE.Color( colors[ colorIndex ] );
  4905. face.color = color;
  4906. }
  4907. if ( hasFaceVertexColor ) {
  4908. for ( i = 0; i < nVertices; i++ ) {
  4909. colorIndex = faces[ offset ++ ];
  4910. color = new THREE.Color( colors[ colorIndex ] );
  4911. face.vertexColors.push( color );
  4912. }
  4913. }
  4914. geometry.faces.push( face );
  4915. }
  4916. };
  4917. function parseSkin() {
  4918. var i, l, x, y, z, w, a, b, c, d;
  4919. if ( json.skinWeights ) {
  4920. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  4921. x = json.skinWeights[ i ];
  4922. y = json.skinWeights[ i + 1 ];
  4923. z = 0;
  4924. w = 0;
  4925. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  4926. }
  4927. }
  4928. if ( json.skinIndices ) {
  4929. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  4930. a = json.skinIndices[ i ];
  4931. b = json.skinIndices[ i + 1 ];
  4932. c = 0;
  4933. d = 0;
  4934. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  4935. }
  4936. }
  4937. geometry.bones = json.bones;
  4938. geometry.animation = json.animation;
  4939. };
  4940. function parseMorphing( scale ) {
  4941. if ( json.morphTargets !== undefined ) {
  4942. var i, l, v, vl, dstVertices, srcVertices;
  4943. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  4944. geometry.morphTargets[ i ] = {};
  4945. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  4946. geometry.morphTargets[ i ].vertices = [];
  4947. dstVertices = geometry.morphTargets[ i ].vertices;
  4948. srcVertices = json.morphTargets [ i ].vertices;
  4949. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  4950. var vertex = new THREE.Vector3();
  4951. vertex.x = srcVertices[ v ] * scale;
  4952. vertex.y = srcVertices[ v + 1 ] * scale;
  4953. vertex.z = srcVertices[ v + 2 ] * scale;
  4954. dstVertices.push( vertex );
  4955. }
  4956. }
  4957. }
  4958. if ( json.morphColors !== undefined ) {
  4959. var i, l, c, cl, dstColors, srcColors, color;
  4960. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  4961. geometry.morphColors[ i ] = {};
  4962. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  4963. geometry.morphColors[ i ].colors = [];
  4964. dstColors = geometry.morphColors[ i ].colors;
  4965. srcColors = json.morphColors [ i ].colors;
  4966. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  4967. color = new THREE.Color( 0xffaa00 );
  4968. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  4969. dstColors.push( color );
  4970. }
  4971. }
  4972. }
  4973. };
  4974. callback( geometry );
  4975. };
  4976. /**
  4977. * @author mrdoob / http://mrdoob.com/
  4978. */
  4979. THREE.LoadingMonitor = function () {
  4980. THREE.EventTarget.call( this );
  4981. var scope = this;
  4982. var loaded = 0;
  4983. var total = 0;
  4984. var onLoad = function ( event ) {
  4985. loaded ++;
  4986. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  4987. if ( loaded === total ) {
  4988. scope.dispatchEvent( { type: 'load' } );
  4989. }
  4990. };
  4991. this.add = function ( loader ) {
  4992. total ++;
  4993. loader.addEventListener( 'load', onLoad, false );
  4994. };
  4995. };
  4996. /**
  4997. * @author mrdoob / http://mrdoob.com/
  4998. * @author alteredq / http://alteredqualia.com/
  4999. */
  5000. THREE.GeometryLoader = function () {
  5001. THREE.EventTarget.call( this );
  5002. this.crossOrigin = null;
  5003. this.path = null;
  5004. };
  5005. THREE.GeometryLoader.prototype = {
  5006. constructor: THREE.GeometryLoader,
  5007. load: function ( url ) {
  5008. var scope = this;
  5009. var geometry = null;
  5010. if ( scope.path === null ) {
  5011. var parts = url.split( '/' ); parts.pop();
  5012. scope.path = ( parts.length < 1 ? '.' : parts.join( '/' ) );
  5013. }
  5014. //
  5015. var xhr = new XMLHttpRequest();
  5016. xhr.addEventListener( 'load', function ( event ) {
  5017. if ( event.target.responseText ) {
  5018. geometry = scope.parse( JSON.parse( event.target.responseText ), monitor );
  5019. } else {
  5020. scope.dispatchEvent( { type: 'error', message: 'Invalid file [' + url + ']' } );
  5021. }
  5022. }, false );
  5023. xhr.addEventListener( 'error', function () {
  5024. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5025. }, false );
  5026. xhr.open( 'GET', url, true );
  5027. xhr.send( null );
  5028. //
  5029. var monitor = new THREE.LoadingMonitor();
  5030. monitor.addEventListener( 'load', function ( event ) {
  5031. scope.dispatchEvent( { type: 'load', content: geometry } );
  5032. } );
  5033. monitor.add( xhr );
  5034. },
  5035. parse: function ( data, monitor ) {
  5036. var scope = this;
  5037. var geometry = new THREE.Geometry();
  5038. var scale = ( data.scale !== undefined ) ? 1 / data.scale : 1;
  5039. // materials
  5040. if ( data.materials ) {
  5041. geometry.materials = [];
  5042. for ( var i = 0; i < data.materials.length; ++ i ) {
  5043. var m = data.materials[ i ];
  5044. function isPow2( n ) {
  5045. var l = Math.log( n ) / Math.LN2;
  5046. return Math.floor( l ) == l;
  5047. }
  5048. function nearestPow2( n ) {
  5049. var l = Math.log( n ) / Math.LN2;
  5050. return Math.pow( 2, Math.round( l ) );
  5051. }
  5052. function createTexture( where, name, sourceFile, repeat, offset, wrap ) {
  5053. where[ name ] = new THREE.Texture();
  5054. where[ name ].sourceFile = sourceFile;
  5055. if ( repeat ) {
  5056. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5057. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5058. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5059. }
  5060. if ( offset ) {
  5061. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5062. }
  5063. if ( wrap ) {
  5064. var wrapMap = {
  5065. "repeat": THREE.RepeatWrapping,
  5066. "mirror": THREE.MirroredRepeatWrapping
  5067. }
  5068. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5069. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5070. }
  5071. // load image
  5072. var texture = where[ name ];
  5073. var loader = new THREE.ImageLoader();
  5074. loader.addEventListener( 'load', function ( event ) {
  5075. var image = event.content;
  5076. if ( !isPow2( image.width ) || !isPow2( image.height ) ) {
  5077. var width = nearestPow2( image.width );
  5078. var height = nearestPow2( image.height );
  5079. texture.image = document.createElement( 'canvas' );
  5080. texture.image.width = width;
  5081. texture.image.height = height;
  5082. texture.image.getContext( '2d' ).drawImage( image, 0, 0, width, height );
  5083. } else {
  5084. texture.image = image;
  5085. }
  5086. texture.needsUpdate = true;
  5087. } );
  5088. loader.crossOrigin = scope.crossOrigin;
  5089. loader.load( scope.path + '/' + sourceFile );
  5090. if ( monitor ) monitor.add( loader );
  5091. }
  5092. function rgb2hex( rgb ) {
  5093. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5094. }
  5095. // defaults
  5096. var mtype = "MeshLambertMaterial";
  5097. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5098. // parameters from model file
  5099. if ( m.shading ) {
  5100. var shading = m.shading.toLowerCase();
  5101. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5102. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5103. }
  5104. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5105. mpars.blending = THREE[ m.blending ];
  5106. }
  5107. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5108. mpars.transparent = m.transparent;
  5109. }
  5110. if ( m.depthTest !== undefined ) {
  5111. mpars.depthTest = m.depthTest;
  5112. }
  5113. if ( m.depthWrite !== undefined ) {
  5114. mpars.depthWrite = m.depthWrite;
  5115. }
  5116. if ( m.vertexColors !== undefined ) {
  5117. if ( m.vertexColors == "face" ) {
  5118. mpars.vertexColors = THREE.FaceColors;
  5119. } else if ( m.vertexColors ) {
  5120. mpars.vertexColors = THREE.VertexColors;
  5121. }
  5122. }
  5123. // colors
  5124. if ( m.colorDiffuse ) {
  5125. mpars.color = rgb2hex( m.colorDiffuse );
  5126. } else if ( m.DbgColor ) {
  5127. mpars.color = m.DbgColor;
  5128. }
  5129. if ( m.colorSpecular ) {
  5130. mpars.specular = rgb2hex( m.colorSpecular );
  5131. }
  5132. if ( m.colorAmbient ) {
  5133. mpars.ambient = rgb2hex( m.colorAmbient );
  5134. }
  5135. // modifiers
  5136. if ( m.transparency ) {
  5137. mpars.opacity = m.transparency;
  5138. }
  5139. if ( m.specularCoef ) {
  5140. mpars.shininess = m.specularCoef;
  5141. }
  5142. if ( m.visible !== undefined ) {
  5143. mpars.visible = m.visible;
  5144. }
  5145. if ( m.flipSided !== undefined ) {
  5146. mpars.side = THREE.BackSide;
  5147. }
  5148. if ( m.doubleSided !== undefined ) {
  5149. mpars.side = THREE.DoubleSide;
  5150. }
  5151. if ( m.wireframe !== undefined ) {
  5152. mpars.wireframe = m.wireframe;
  5153. }
  5154. // textures
  5155. if ( m.mapDiffuse ) {
  5156. createTexture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  5157. }
  5158. if ( m.mapLight ) {
  5159. createTexture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  5160. }
  5161. if ( m.mapBump ) {
  5162. createTexture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap );
  5163. }
  5164. if ( m.mapNormal ) {
  5165. createTexture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  5166. }
  5167. if ( m.mapSpecular ) {
  5168. createTexture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  5169. }
  5170. // special case for normal mapped material
  5171. if ( m.mapNormal ) {
  5172. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5173. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5174. uniforms[ "tNormal" ].value = mpars.normalMap;
  5175. if ( m.mapNormalFactor ) {
  5176. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5177. }
  5178. if ( mpars.map ) {
  5179. uniforms[ "tDiffuse" ].value = mpars.map;
  5180. uniforms[ "enableDiffuse" ].value = true;
  5181. }
  5182. if ( mpars.specularMap ) {
  5183. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5184. uniforms[ "enableSpecular" ].value = true;
  5185. }
  5186. if ( mpars.lightMap ) {
  5187. uniforms[ "tAO" ].value = mpars.lightMap;
  5188. uniforms[ "enableAO" ].value = true;
  5189. }
  5190. // for the moment don't handle displacement texture
  5191. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5192. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5193. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5194. uniforms[ "uShininess" ].value = mpars.shininess;
  5195. if ( mpars.opacity !== undefined ) {
  5196. uniforms[ "uOpacity" ].value = mpars.opacity;
  5197. }
  5198. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5199. var material = new THREE.ShaderMaterial( parameters );
  5200. } else {
  5201. var material = new THREE[ mtype ]( mpars );
  5202. }
  5203. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5204. geometry.materials[ i ] = material;
  5205. }
  5206. }
  5207. // geometry
  5208. function isBitSet( value, position ) {
  5209. return value & ( 1 << position );
  5210. }
  5211. var faces = data.faces;
  5212. var vertices = data.vertices;
  5213. var normals = data.normals;
  5214. var colors = data.colors;
  5215. var nUvLayers = 0;
  5216. // disregard empty arrays
  5217. if ( data.uvs ) {
  5218. for ( var i = 0; i < data.uvs.length; i ++ ) {
  5219. if ( data.uvs[ i ].length ) nUvLayers ++;
  5220. }
  5221. }
  5222. for ( var i = 0; i < nUvLayers; i ++ ) {
  5223. geometry.faceUvs[ i ] = [];
  5224. geometry.faceVertexUvs[ i ] = [];
  5225. }
  5226. var offset = 0;
  5227. var zLength = vertices.length;
  5228. while ( offset < zLength ) {
  5229. var vertex = new THREE.Vector3();
  5230. vertex.x = vertices[ offset ++ ] * scale;
  5231. vertex.y = vertices[ offset ++ ] * scale;
  5232. vertex.z = vertices[ offset ++ ] * scale;
  5233. geometry.vertices.push( vertex );
  5234. }
  5235. offset = 0;
  5236. zLength = faces.length;
  5237. while ( offset < zLength ) {
  5238. var type = faces[ offset ++ ];
  5239. var isQuad = isBitSet( type, 0 );
  5240. var hasMaterial = isBitSet( type, 1 );
  5241. var hasFaceUv = isBitSet( type, 2 );
  5242. var hasFaceVertexUv = isBitSet( type, 3 );
  5243. var hasFaceNormal = isBitSet( type, 4 );
  5244. var hasFaceVertexNormal = isBitSet( type, 5 );
  5245. var hasFaceColor = isBitSet( type, 6 );
  5246. var hasFaceVertexColor = isBitSet( type, 7 );
  5247. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5248. if ( isQuad ) {
  5249. var face = new THREE.Face4();
  5250. face.a = faces[ offset ++ ];
  5251. face.b = faces[ offset ++ ];
  5252. face.c = faces[ offset ++ ];
  5253. face.d = faces[ offset ++ ];
  5254. var nVertices = 4;
  5255. } else {
  5256. var face = new THREE.Face3();
  5257. face.a = faces[ offset ++ ];
  5258. face.b = faces[ offset ++ ];
  5259. face.c = faces[ offset ++ ];
  5260. var nVertices = 3;
  5261. }
  5262. if ( hasMaterial ) {
  5263. var materialIndex = faces[ offset ++ ];
  5264. face.materialIndex = materialIndex;
  5265. }
  5266. // to get face <=> uv index correspondence
  5267. var fi = geometry.faces.length;
  5268. if ( hasFaceUv ) {
  5269. for ( var i = 0; i < nUvLayers; i ++ ) {
  5270. var uvLayer = data.uvs[ i ];
  5271. var uvIndex = faces[ offset ++ ];
  5272. var u = uvLayer[ uvIndex * 2 ];
  5273. var v = uvLayer[ uvIndex * 2 + 1 ];
  5274. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  5275. }
  5276. }
  5277. if ( hasFaceVertexUv ) {
  5278. for ( var i = 0; i < nUvLayers; i ++ ) {
  5279. var uvLayer = data.uvs[ i ];
  5280. var uvs = [];
  5281. for ( var j = 0; j < nVertices; j ++ ) {
  5282. var uvIndex = faces[ offset ++ ];
  5283. var u = uvLayer[ uvIndex * 2 ];
  5284. var v = uvLayer[ uvIndex * 2 + 1 ];
  5285. uvs[ j ] = new THREE.UV( u, v );
  5286. }
  5287. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5288. }
  5289. }
  5290. if ( hasFaceNormal ) {
  5291. var normalIndex = faces[ offset ++ ] * 3;
  5292. var normal = new THREE.Vector3();
  5293. normal.x = normals[ normalIndex ++ ];
  5294. normal.y = normals[ normalIndex ++ ];
  5295. normal.z = normals[ normalIndex ];
  5296. face.normal = normal;
  5297. }
  5298. if ( hasFaceVertexNormal ) {
  5299. for ( i = 0; i < nVertices; i ++ ) {
  5300. var normalIndex = faces[ offset ++ ] * 3;
  5301. var normal = new THREE.Vector3();
  5302. normal.x = normals[ normalIndex ++ ];
  5303. normal.y = normals[ normalIndex ++ ];
  5304. normal.z = normals[ normalIndex ];
  5305. face.vertexNormals.push( normal );
  5306. }
  5307. }
  5308. if ( hasFaceColor ) {
  5309. var colorIndex = faces[ offset ++ ];
  5310. face.color = new THREE.Color( colors[ colorIndex ] );
  5311. }
  5312. if ( hasFaceVertexColor ) {
  5313. for ( var i = 0; i < nVertices; i ++ ) {
  5314. var colorIndex = faces[ offset ++ ];
  5315. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  5316. }
  5317. }
  5318. geometry.faces.push( face );
  5319. }
  5320. // skin
  5321. if ( data.skinWeights ) {
  5322. for ( var i = 0, l = data.skinWeights.length; i < l; i += 2 ) {
  5323. var x = data.skinWeights[ i ];
  5324. var y = data.skinWeights[ i + 1 ];
  5325. var z = 0;
  5326. var w = 0;
  5327. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5328. }
  5329. }
  5330. if ( data.skinIndices ) {
  5331. for ( var i = 0, l = data.skinIndices.length; i < l; i += 2 ) {
  5332. var a = data.skinIndices[ i ];
  5333. var b = data.skinIndices[ i + 1 ];
  5334. var c = 0;
  5335. var d = 0;
  5336. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5337. }
  5338. }
  5339. geometry.bones = data.bones;
  5340. geometry.animation = data.animation;
  5341. // morphing
  5342. if ( data.morphTargets ) {
  5343. for ( var i = 0, l = data.morphTargets.length; i < l; i ++ ) {
  5344. geometry.morphTargets[ i ] = {};
  5345. geometry.morphTargets[ i ].name = data.morphTargets[ i ].name;
  5346. geometry.morphTargets[ i ].vertices = [];
  5347. var dstVertices = geometry.morphTargets[ i ].vertices;
  5348. var srcVertices = data.morphTargets [ i ].vertices;
  5349. for( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5350. var vertex = new THREE.Vector3();
  5351. vertex.x = srcVertices[ v ] * scale;
  5352. vertex.y = srcVertices[ v + 1 ] * scale;
  5353. vertex.z = srcVertices[ v + 2 ] * scale;
  5354. dstVertices.push( vertex );
  5355. }
  5356. }
  5357. }
  5358. if ( data.morphColors ) {
  5359. for ( var i = 0, l = data.morphColors.length; i < l; i++ ) {
  5360. geometry.morphColors[ i ] = {};
  5361. geometry.morphColors[ i ].name = data.morphColors[ i ].name;
  5362. geometry.morphColors[ i ].colors = [];
  5363. var dstColors = geometry.morphColors[ i ].colors;
  5364. var srcColors = data.morphColors [ i ].colors;
  5365. for ( var c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5366. var color = new THREE.Color( 0xffaa00 );
  5367. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5368. dstColors.push( color );
  5369. }
  5370. }
  5371. }
  5372. geometry.computeCentroids();
  5373. geometry.computeFaceNormals();
  5374. return geometry;
  5375. }
  5376. };
  5377. /**
  5378. * @author alteredq / http://alteredqualia.com/
  5379. */
  5380. THREE.SceneLoader = function () {
  5381. this.onLoadStart = function () {};
  5382. this.onLoadProgress = function() {};
  5383. this.onLoadComplete = function () {};
  5384. this.callbackSync = function () {};
  5385. this.callbackProgress = function () {};
  5386. this.geometryHandlerMap = {};
  5387. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5388. this.addGeometryHandler( "binary", THREE.BinaryLoader );
  5389. };
  5390. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5391. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5392. var scope = this;
  5393. var xhr = new XMLHttpRequest();
  5394. xhr.onreadystatechange = function () {
  5395. if ( xhr.readyState === 4 ) {
  5396. if ( xhr.status === 200 || xhr.status === 0 ) {
  5397. var json = JSON.parse( xhr.responseText );
  5398. scope.parse( json, callbackFinished, url );
  5399. } else {
  5400. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5401. }
  5402. }
  5403. };
  5404. xhr.open( "GET", url, true );
  5405. xhr.send( null );
  5406. };
  5407. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5408. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5409. };
  5410. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5411. var scope = this;
  5412. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5413. var dg, dm, dl, dc, df, dt,
  5414. g, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  5415. geometry, material, camera, fog,
  5416. texture, images,
  5417. light,
  5418. counter_models, counter_textures,
  5419. total_models, total_textures,
  5420. result;
  5421. var data = json;
  5422. // async geometry loaders
  5423. for ( var typeID in this.geometryHandlerMap ) {
  5424. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5425. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5426. }
  5427. counter_models = 0;
  5428. counter_textures = 0;
  5429. result = {
  5430. scene: new THREE.Scene(),
  5431. geometries: {},
  5432. materials: {},
  5433. textures: {},
  5434. objects: {},
  5435. cameras: {},
  5436. lights: {},
  5437. fogs: {},
  5438. empties: {}
  5439. };
  5440. if ( data.transform ) {
  5441. var position = data.transform.position,
  5442. rotation = data.transform.rotation,
  5443. scale = data.transform.scale;
  5444. if ( position )
  5445. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5446. if ( rotation )
  5447. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5448. if ( scale )
  5449. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5450. if ( position || rotation || scale ) {
  5451. result.scene.updateMatrix();
  5452. result.scene.updateMatrixWorld();
  5453. }
  5454. }
  5455. function get_url( source_url, url_type ) {
  5456. if ( url_type == "relativeToHTML" ) {
  5457. return source_url;
  5458. } else {
  5459. return urlBase + "/" + source_url;
  5460. }
  5461. };
  5462. // toplevel loader function, delegates to handle_children
  5463. function handle_objects() {
  5464. handle_children( result.scene, data.objects );
  5465. }
  5466. // handle all the children from the loaded json and attach them to given parent
  5467. function handle_children( parent, children ) {
  5468. for ( var dd in children ) {
  5469. // check by id if child has already been handled,
  5470. // if not, create new object
  5471. if ( result.objects[ dd ] === undefined ) {
  5472. var o = children[ dd ];
  5473. var object = null;
  5474. if ( o.geometry !== undefined ) {
  5475. geometry = result.geometries[ o.geometry ];
  5476. // geometry already loaded
  5477. if ( geometry ) {
  5478. var hasNormals = false;
  5479. // not anymore support for multiple materials
  5480. // shouldn't really be array
  5481. material = result.materials[ o.materials[ 0 ] ];
  5482. hasNormals = material instanceof THREE.ShaderMaterial;
  5483. if ( hasNormals ) {
  5484. geometry.computeTangents();
  5485. }
  5486. p = o.position;
  5487. r = o.rotation;
  5488. q = o.quaternion;
  5489. s = o.scale;
  5490. m = o.matrix;
  5491. // turn off quaternions, for the moment
  5492. q = 0;
  5493. if ( o.materials.length === 0 ) {
  5494. material = new THREE.MeshFaceMaterial();
  5495. }
  5496. // dirty hack to handle meshes with multiple materials
  5497. // just use face materials defined in model
  5498. if ( o.materials.length > 1 ) {
  5499. material = new THREE.MeshFaceMaterial();
  5500. }
  5501. if ( o.morph ) {
  5502. object = new THREE.MorphAnimMesh( geometry, material );
  5503. if ( o.duration !== undefined ) {
  5504. object.duration = o.duration;
  5505. }
  5506. if ( o.time !== undefined ) {
  5507. object.time = o.time;
  5508. }
  5509. if ( o.mirroredLoop !== undefined ) {
  5510. object.mirroredLoop = o.mirroredLoop;
  5511. }
  5512. if ( material.morphNormals ) {
  5513. geometry.computeMorphNormals();
  5514. }
  5515. } else {
  5516. object = new THREE.Mesh( geometry, material );
  5517. }
  5518. object.name = dd;
  5519. if ( m ) {
  5520. object.matrixAutoUpdate = false;
  5521. object.matrix.set(
  5522. m[0], m[1], m[2], m[3],
  5523. m[4], m[5], m[6], m[7],
  5524. m[8], m[9], m[10], m[11],
  5525. m[12], m[13], m[14], m[15]
  5526. );
  5527. } else {
  5528. object.position.set( p[0], p[1], p[2] );
  5529. if ( q ) {
  5530. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5531. object.useQuaternion = true;
  5532. } else {
  5533. object.rotation.set( r[0], r[1], r[2] );
  5534. }
  5535. object.scale.set( s[0], s[1], s[2] );
  5536. }
  5537. object.visible = o.visible;
  5538. object.castShadow = o.castShadow;
  5539. object.receiveShadow = o.receiveShadow;
  5540. parent.add( object );
  5541. result.objects[ dd ] = object;
  5542. }
  5543. // pure Object3D
  5544. } else {
  5545. p = o.position;
  5546. r = o.rotation;
  5547. q = o.quaternion;
  5548. s = o.scale;
  5549. // turn off quaternions, for the moment
  5550. q = 0;
  5551. object = new THREE.Object3D();
  5552. object.name = dd;
  5553. object.position.set( p[0], p[1], p[2] );
  5554. if ( q ) {
  5555. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5556. object.useQuaternion = true;
  5557. } else {
  5558. object.rotation.set( r[0], r[1], r[2] );
  5559. }
  5560. object.scale.set( s[0], s[1], s[2] );
  5561. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  5562. parent.add( object );
  5563. result.objects[ dd ] = object;
  5564. result.empties[ dd ] = object;
  5565. }
  5566. if ( object ) {
  5567. if ( o.properties !== undefined ) {
  5568. for ( var key in o.properties ) {
  5569. var value = o.properties[ key ];
  5570. object.properties[ key ] = value;
  5571. }
  5572. }
  5573. if ( o.children !== undefined ) {
  5574. handle_children( object, o.children );
  5575. }
  5576. }
  5577. }
  5578. }
  5579. };
  5580. function handle_mesh( geo, id ) {
  5581. result.geometries[ id ] = geo;
  5582. handle_objects();
  5583. };
  5584. function create_callback( id ) {
  5585. return function( geo ) {
  5586. handle_mesh( geo, id );
  5587. counter_models -= 1;
  5588. scope.onLoadComplete();
  5589. async_callback_gate();
  5590. }
  5591. };
  5592. function create_callback_embed( id ) {
  5593. return function( geo ) {
  5594. result.geometries[ id ] = geo;
  5595. }
  5596. };
  5597. function async_callback_gate() {
  5598. var progress = {
  5599. totalModels : total_models,
  5600. totalTextures : total_textures,
  5601. loadedModels : total_models - counter_models,
  5602. loadedTextures : total_textures - counter_textures
  5603. };
  5604. scope.callbackProgress( progress, result );
  5605. scope.onLoadProgress();
  5606. if ( counter_models === 0 && counter_textures === 0 ) {
  5607. callbackFinished( result );
  5608. }
  5609. };
  5610. var callbackTexture = function ( count ) {
  5611. counter_textures -= count;
  5612. async_callback_gate();
  5613. scope.onLoadComplete();
  5614. };
  5615. // must use this instead of just directly calling callbackTexture
  5616. // because of closure in the calling context loop
  5617. var generateTextureCallback = function ( count ) {
  5618. return function() {
  5619. callbackTexture( count );
  5620. };
  5621. };
  5622. // first go synchronous elements
  5623. // cameras
  5624. for( dc in data.cameras ) {
  5625. c = data.cameras[ dc ];
  5626. if ( c.type === "perspective" ) {
  5627. camera = new THREE.PerspectiveCamera( c.fov, c.aspect, c.near, c.far );
  5628. } else if ( c.type === "ortho" ) {
  5629. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  5630. }
  5631. p = c.position;
  5632. t = c.target;
  5633. u = c.up;
  5634. camera.position.set( p[0], p[1], p[2] );
  5635. camera.target = new THREE.Vector3( t[0], t[1], t[2] );
  5636. if ( u ) camera.up.set( u[0], u[1], u[2] );
  5637. result.cameras[ dc ] = camera;
  5638. }
  5639. // lights
  5640. var hex, intensity;
  5641. for ( dl in data.lights ) {
  5642. l = data.lights[ dl ];
  5643. hex = ( l.color !== undefined ) ? l.color : 0xffffff;
  5644. intensity = ( l.intensity !== undefined ) ? l.intensity : 1;
  5645. if ( l.type === "directional" ) {
  5646. p = l.direction;
  5647. light = new THREE.DirectionalLight( hex, intensity );
  5648. light.position.set( p[0], p[1], p[2] );
  5649. light.position.normalize();
  5650. } else if ( l.type === "point" ) {
  5651. p = l.position;
  5652. d = l.distance;
  5653. light = new THREE.PointLight( hex, intensity, d );
  5654. light.position.set( p[0], p[1], p[2] );
  5655. } else if ( l.type === "ambient" ) {
  5656. light = new THREE.AmbientLight( hex );
  5657. }
  5658. result.scene.add( light );
  5659. result.lights[ dl ] = light;
  5660. }
  5661. // fogs
  5662. for( df in data.fogs ) {
  5663. f = data.fogs[ df ];
  5664. if ( f.type === "linear" ) {
  5665. fog = new THREE.Fog( 0x000000, f.near, f.far );
  5666. } else if ( f.type === "exp2" ) {
  5667. fog = new THREE.FogExp2( 0x000000, f.density );
  5668. }
  5669. c = f.color;
  5670. fog.color.setRGB( c[0], c[1], c[2] );
  5671. result.fogs[ df ] = fog;
  5672. }
  5673. // defaults
  5674. if ( result.cameras && data.defaults.camera ) {
  5675. result.currentCamera = result.cameras[ data.defaults.camera ];
  5676. }
  5677. if ( result.fogs && data.defaults.fog ) {
  5678. result.scene.fog = result.fogs[ data.defaults.fog ];
  5679. }
  5680. c = data.defaults.bgcolor;
  5681. result.bgColor = new THREE.Color();
  5682. result.bgColor.setRGB( c[0], c[1], c[2] );
  5683. result.bgColorAlpha = data.defaults.bgalpha;
  5684. // now come potentially asynchronous elements
  5685. // geometries
  5686. // count how many models will be loaded asynchronously
  5687. for( dg in data.geometries ) {
  5688. g = data.geometries[ dg ];
  5689. if ( g.type in this.geometryHandlerMap ) {
  5690. counter_models += 1;
  5691. scope.onLoadStart();
  5692. }
  5693. }
  5694. total_models = counter_models;
  5695. for ( dg in data.geometries ) {
  5696. g = data.geometries[ dg ];
  5697. if ( g.type === "cube" ) {
  5698. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.segmentsWidth, g.segmentsHeight, g.segmentsDepth, null, g.flipped, g.sides );
  5699. result.geometries[ dg ] = geometry;
  5700. } else if ( g.type === "plane" ) {
  5701. geometry = new THREE.PlaneGeometry( g.width, g.height, g.segmentsWidth, g.segmentsHeight );
  5702. result.geometries[ dg ] = geometry;
  5703. } else if ( g.type === "sphere" ) {
  5704. geometry = new THREE.SphereGeometry( g.radius, g.segmentsWidth, g.segmentsHeight );
  5705. result.geometries[ dg ] = geometry;
  5706. } else if ( g.type === "cylinder" ) {
  5707. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  5708. result.geometries[ dg ] = geometry;
  5709. } else if ( g.type === "torus" ) {
  5710. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  5711. result.geometries[ dg ] = geometry;
  5712. } else if ( g.type === "icosahedron" ) {
  5713. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  5714. result.geometries[ dg ] = geometry;
  5715. } else if ( g.type in this.geometryHandlerMap ) {
  5716. var loaderParameters = {};
  5717. for ( var parType in g ) {
  5718. if ( parType !== "type" && parType !== "url" ) {
  5719. loaderParameters[ parType ] = g[ parType ];
  5720. }
  5721. }
  5722. var loader = this.geometryHandlerMap[ g.type ][ "loaderObject" ];
  5723. loader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ), loaderParameters );
  5724. } else if ( g.type === "embedded" ) {
  5725. var modelJson = data.embeds[ g.id ],
  5726. texture_path = "";
  5727. // pass metadata along to jsonLoader so it knows the format version
  5728. modelJson.metadata = data.metadata;
  5729. if ( modelJson ) {
  5730. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  5731. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  5732. }
  5733. }
  5734. }
  5735. // textures
  5736. // count how many textures will be loaded asynchronously
  5737. for( dt in data.textures ) {
  5738. tt = data.textures[ dt ];
  5739. if( tt.url instanceof Array ) {
  5740. counter_textures += tt.url.length;
  5741. for( var n = 0; n < tt.url.length; n ++ ) {
  5742. scope.onLoadStart();
  5743. }
  5744. } else {
  5745. counter_textures += 1;
  5746. scope.onLoadStart();
  5747. }
  5748. }
  5749. total_textures = counter_textures;
  5750. for ( dt in data.textures ) {
  5751. tt = data.textures[ dt ];
  5752. if ( tt.mapping !== undefined && THREE[ tt.mapping ] !== undefined ) {
  5753. tt.mapping = new THREE[ tt.mapping ]();
  5754. }
  5755. if ( tt.url instanceof Array ) {
  5756. var count = tt.url.length;
  5757. var url_array = [];
  5758. for( var i = 0; i < count; i ++ ) {
  5759. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  5760. }
  5761. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  5762. if ( isCompressed ) {
  5763. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5764. } else {
  5765. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5766. }
  5767. } else {
  5768. var isCompressed = tt.url.toLowerCase().endsWith( ".dds" );
  5769. var fullUrl = get_url( tt.url, data.urlBaseType );
  5770. var textureCallback = generateTextureCallback( 1 );
  5771. if ( isCompressed ) {
  5772. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, tt.mapping, textureCallback );
  5773. } else {
  5774. texture = THREE.ImageUtils.loadTexture( fullUrl, tt.mapping, textureCallback );
  5775. }
  5776. if ( THREE[ tt.minFilter ] !== undefined )
  5777. texture.minFilter = THREE[ tt.minFilter ];
  5778. if ( THREE[ tt.magFilter ] !== undefined )
  5779. texture.magFilter = THREE[ tt.magFilter ];
  5780. if ( tt.anisotropy ) texture.anisotropy = tt.anisotropy;
  5781. if ( tt.repeat ) {
  5782. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  5783. if ( tt.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  5784. if ( tt.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  5785. }
  5786. if ( tt.offset ) {
  5787. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  5788. }
  5789. // handle wrap after repeat so that default repeat can be overriden
  5790. if ( tt.wrap ) {
  5791. var wrapMap = {
  5792. "repeat" : THREE.RepeatWrapping,
  5793. "mirror" : THREE.MirroredRepeatWrapping
  5794. }
  5795. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  5796. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  5797. }
  5798. }
  5799. result.textures[ dt ] = texture;
  5800. }
  5801. // materials
  5802. for ( dm in data.materials ) {
  5803. m = data.materials[ dm ];
  5804. for ( pp in m.parameters ) {
  5805. if ( pp === "envMap" || pp === "map" || pp === "lightMap" || pp === "bumpMap" ) {
  5806. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  5807. } else if ( pp === "shading" ) {
  5808. m.parameters[ pp ] = ( m.parameters[ pp ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  5809. } else if ( pp === "side" ) {
  5810. if ( m.parameters[ pp ] == "double" ) {
  5811. m.parameters[ pp ] = THREE.DoubleSide;
  5812. } else if ( m.parameters[ pp ] == "back" ) {
  5813. m.parameters[ pp ] = THREE.BackSide;
  5814. } else {
  5815. m.parameters[ pp ] = THREE.FrontSide;
  5816. }
  5817. } else if ( pp === "blending" ) {
  5818. m.parameters[ pp ] = m.parameters[ pp ] in THREE ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  5819. } else if ( pp === "combine" ) {
  5820. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  5821. } else if ( pp === "vertexColors" ) {
  5822. if ( m.parameters[ pp ] == "face" ) {
  5823. m.parameters[ pp ] = THREE.FaceColors;
  5824. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  5825. } else if ( m.parameters[ pp ] ) {
  5826. m.parameters[ pp ] = THREE.VertexColors;
  5827. }
  5828. } else if ( pp === "wrapRGB" ) {
  5829. var v3 = m.parameters[ pp ];
  5830. m.parameters[ pp ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  5831. }
  5832. }
  5833. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  5834. m.parameters.transparent = true;
  5835. }
  5836. if ( m.parameters.normalMap ) {
  5837. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5838. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5839. var diffuse = m.parameters.color;
  5840. var specular = m.parameters.specular;
  5841. var ambient = m.parameters.ambient;
  5842. var shininess = m.parameters.shininess;
  5843. uniforms[ "tNormal" ].value = result.textures[ m.parameters.normalMap ];
  5844. if ( m.parameters.normalScale ) {
  5845. uniforms[ "uNormalScale" ].value.set( m.parameters.normalScale[ 0 ], m.parameters.normalScale[ 1 ] );
  5846. }
  5847. if ( m.parameters.map ) {
  5848. uniforms[ "tDiffuse" ].value = m.parameters.map;
  5849. uniforms[ "enableDiffuse" ].value = true;
  5850. }
  5851. if ( m.parameters.envMap ) {
  5852. uniforms[ "tCube" ].value = m.parameters.envMap;
  5853. uniforms[ "enableReflection" ].value = true;
  5854. uniforms[ "uReflectivity" ].value = m.parameters.reflectivity;
  5855. }
  5856. if ( m.parameters.lightMap ) {
  5857. uniforms[ "tAO" ].value = m.parameters.lightMap;
  5858. uniforms[ "enableAO" ].value = true;
  5859. }
  5860. if ( m.parameters.specularMap ) {
  5861. uniforms[ "tSpecular" ].value = result.textures[ m.parameters.specularMap ];
  5862. uniforms[ "enableSpecular" ].value = true;
  5863. }
  5864. if ( m.parameters.displacementMap ) {
  5865. uniforms[ "tDisplacement" ].value = result.textures[ m.parameters.displacementMap ];
  5866. uniforms[ "enableDisplacement" ].value = true;
  5867. uniforms[ "uDisplacementBias" ].value = m.parameters.displacementBias;
  5868. uniforms[ "uDisplacementScale" ].value = m.parameters.displacementScale;
  5869. }
  5870. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  5871. uniforms[ "uSpecularColor" ].value.setHex( specular );
  5872. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  5873. uniforms[ "uShininess" ].value = shininess;
  5874. if ( m.parameters.opacity ) {
  5875. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  5876. }
  5877. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5878. material = new THREE.ShaderMaterial( parameters );
  5879. } else {
  5880. material = new THREE[ m.type ]( m.parameters );
  5881. }
  5882. result.materials[ dm ] = material;
  5883. }
  5884. // objects ( synchronous init of procedural primitives )
  5885. handle_objects();
  5886. // synchronous callback
  5887. scope.callbackSync( result );
  5888. // just in case there are no async elements
  5889. async_callback_gate();
  5890. };
  5891. /**
  5892. * @author mrdoob / http://mrdoob.com/
  5893. */
  5894. THREE.TextureLoader = function () {
  5895. THREE.EventTarget.call( this );
  5896. this.crossOrigin = null;
  5897. };
  5898. THREE.TextureLoader.prototype = {
  5899. constructor: THREE.TextureLoader,
  5900. load: function ( url ) {
  5901. var scope = this;
  5902. var image = new Image();
  5903. image.addEventListener( 'load', function () {
  5904. var texture = new THREE.Texture( image );
  5905. texture.needsUpdate = true;
  5906. scope.dispatchEvent( { type: 'load', content: texture } );
  5907. }, false );
  5908. image.addEventListener( 'error', function () {
  5909. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5910. }, false );
  5911. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5912. image.src = url;
  5913. }
  5914. }
  5915. /**
  5916. * @author mrdoob / http://mrdoob.com/
  5917. * @author alteredq / http://alteredqualia.com/
  5918. */
  5919. THREE.Material = function () {
  5920. this.id = THREE.MaterialLib.length;
  5921. THREE.MaterialLib.push( this );
  5922. this.name = '';
  5923. this.side = THREE.FrontSide;
  5924. this.opacity = 1;
  5925. this.transparent = false;
  5926. this.blending = THREE.NormalBlending;
  5927. this.blendSrc = THREE.SrcAlphaFactor;
  5928. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  5929. this.blendEquation = THREE.AddEquation;
  5930. this.depthTest = true;
  5931. this.depthWrite = true;
  5932. this.polygonOffset = false;
  5933. this.polygonOffsetFactor = 0;
  5934. this.polygonOffsetUnits = 0;
  5935. this.alphaTest = 0;
  5936. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  5937. this.visible = true;
  5938. this.needsUpdate = true;
  5939. };
  5940. THREE.Material.prototype.setValues = function ( values ) {
  5941. if ( values === undefined ) return;
  5942. for ( var key in values ) {
  5943. var newValue = values[ key ];
  5944. if ( newValue === undefined ) {
  5945. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5946. continue;
  5947. }
  5948. if ( key in this ) {
  5949. var currentValue = this[ key ];
  5950. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  5951. currentValue.copy( newValue );
  5952. } else if ( currentValue instanceof THREE.Color && typeof( newValue ) === "number" ) {
  5953. currentValue.setHex( newValue );
  5954. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  5955. currentValue.copy( newValue );
  5956. } else {
  5957. this[ key ] = newValue;
  5958. }
  5959. }
  5960. }
  5961. };
  5962. THREE.Material.prototype.clone = function ( material ) {
  5963. if ( material === undefined ) material = new THREE.Material();
  5964. material.name = this.name;
  5965. material.side = this.side;
  5966. material.opacity = this.opacity;
  5967. material.transparent = this.transparent;
  5968. material.blending = this.blending;
  5969. material.blendSrc = this.blendSrc;
  5970. material.blendDst = this.blendDst;
  5971. material.blendEquation = this.blendEquation;
  5972. material.depthTest = this.depthTest;
  5973. material.depthWrite = this.depthWrite;
  5974. material.polygonOffset = this.polygonOffset;
  5975. material.polygonOffsetFactor = this.polygonOffsetFactor;
  5976. material.polygonOffsetUnits = this.polygonOffsetUnits;
  5977. material.alphaTest = this.alphaTest;
  5978. material.overdraw = this.overdraw;
  5979. material.visible = this.visible;
  5980. return material;
  5981. };
  5982. THREE.MaterialLib = [];
  5983. /**
  5984. * @author mrdoob / http://mrdoob.com/
  5985. * @author alteredq / http://alteredqualia.com/
  5986. *
  5987. * parameters = {
  5988. * color: <hex>,
  5989. * opacity: <float>,
  5990. *
  5991. * blending: THREE.NormalBlending,
  5992. * depthTest: <bool>,
  5993. *
  5994. * linewidth: <float>,
  5995. * linecap: "round",
  5996. * linejoin: "round",
  5997. *
  5998. * vertexColors: <bool>
  5999. *
  6000. * fog: <bool>
  6001. * }
  6002. */
  6003. THREE.LineBasicMaterial = function ( parameters ) {
  6004. THREE.Material.call( this );
  6005. this.color = new THREE.Color( 0xffffff );
  6006. this.linewidth = 1;
  6007. this.linecap = 'round';
  6008. this.linejoin = 'round';
  6009. this.vertexColors = false;
  6010. this.fog = true;
  6011. this.setValues( parameters );
  6012. };
  6013. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6014. THREE.LineBasicMaterial.prototype.clone = function () {
  6015. var material = new THREE.LineBasicMaterial();
  6016. THREE.Material.prototype.clone.call( this, material );
  6017. material.color.copy( this.color );
  6018. material.linewidth = this.linewidth;
  6019. material.linecap = this.linecap;
  6020. material.linejoin = this.linejoin;
  6021. material.vertexColors = this.vertexColors;
  6022. material.fog = this.fog;
  6023. return material;
  6024. };
  6025. /**
  6026. * @author mrdoob / http://mrdoob.com/
  6027. * @author alteredq / http://alteredqualia.com/
  6028. *
  6029. * parameters = {
  6030. * color: <hex>,
  6031. * opacity: <float>,
  6032. * map: new THREE.Texture( <Image> ),
  6033. *
  6034. * lightMap: new THREE.Texture( <Image> ),
  6035. *
  6036. * specularMap: new THREE.Texture( <Image> ),
  6037. *
  6038. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6039. * combine: THREE.Multiply,
  6040. * reflectivity: <float>,
  6041. * refractionRatio: <float>,
  6042. *
  6043. * shading: THREE.SmoothShading,
  6044. * blending: THREE.NormalBlending,
  6045. * depthTest: <bool>,
  6046. *
  6047. * wireframe: <boolean>,
  6048. * wireframeLinewidth: <float>,
  6049. *
  6050. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6051. *
  6052. * skinning: <bool>,
  6053. * morphTargets: <bool>,
  6054. *
  6055. * fog: <bool>
  6056. * }
  6057. */
  6058. THREE.MeshBasicMaterial = function ( parameters ) {
  6059. THREE.Material.call( this );
  6060. this.color = new THREE.Color( 0xffffff ); // emissive
  6061. this.map = null;
  6062. this.lightMap = null;
  6063. this.specularMap = null;
  6064. this.envMap = null;
  6065. this.combine = THREE.MultiplyOperation;
  6066. this.reflectivity = 1;
  6067. this.refractionRatio = 0.98;
  6068. this.fog = true;
  6069. this.shading = THREE.SmoothShading;
  6070. this.wireframe = false;
  6071. this.wireframeLinewidth = 1;
  6072. this.wireframeLinecap = 'round';
  6073. this.wireframeLinejoin = 'round';
  6074. this.vertexColors = THREE.NoColors;
  6075. this.skinning = false;
  6076. this.morphTargets = false;
  6077. this.setValues( parameters );
  6078. };
  6079. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6080. THREE.MeshBasicMaterial.prototype.clone = function () {
  6081. var material = new THREE.MeshBasicMaterial();
  6082. THREE.Material.prototype.clone.call( this, material );
  6083. material.color.copy( this.color );
  6084. material.map = this.map;
  6085. material.lightMap = this.lightMap;
  6086. material.specularMap = this.specularMap;
  6087. material.envMap = this.envMap;
  6088. material.combine = this.combine;
  6089. material.reflectivity = this.reflectivity;
  6090. material.refractionRatio = this.refractionRatio;
  6091. material.fog = this.fog;
  6092. material.shading = this.shading;
  6093. material.wireframe = this.wireframe;
  6094. material.wireframeLinewidth = this.wireframeLinewidth;
  6095. material.wireframeLinecap = this.wireframeLinecap;
  6096. material.wireframeLinejoin = this.wireframeLinejoin;
  6097. material.vertexColors = this.vertexColors;
  6098. material.skinning = this.skinning;
  6099. material.morphTargets = this.morphTargets;
  6100. return material;
  6101. };
  6102. /**
  6103. * @author mrdoob / http://mrdoob.com/
  6104. * @author alteredq / http://alteredqualia.com/
  6105. *
  6106. * parameters = {
  6107. * color: <hex>,
  6108. * ambient: <hex>,
  6109. * emissive: <hex>,
  6110. * opacity: <float>,
  6111. *
  6112. * map: new THREE.Texture( <Image> ),
  6113. *
  6114. * lightMap: new THREE.Texture( <Image> ),
  6115. *
  6116. * specularMap: new THREE.Texture( <Image> ),
  6117. *
  6118. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6119. * combine: THREE.Multiply,
  6120. * reflectivity: <float>,
  6121. * refractionRatio: <float>,
  6122. *
  6123. * shading: THREE.SmoothShading,
  6124. * blending: THREE.NormalBlending,
  6125. * depthTest: <bool>,
  6126. *
  6127. * wireframe: <boolean>,
  6128. * wireframeLinewidth: <float>,
  6129. *
  6130. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6131. *
  6132. * skinning: <bool>,
  6133. * morphTargets: <bool>,
  6134. * morphNormals: <bool>,
  6135. *
  6136. * fog: <bool>
  6137. * }
  6138. */
  6139. THREE.MeshLambertMaterial = function ( parameters ) {
  6140. THREE.Material.call( this );
  6141. this.color = new THREE.Color( 0xffffff ); // diffuse
  6142. this.ambient = new THREE.Color( 0xffffff );
  6143. this.emissive = new THREE.Color( 0x000000 );
  6144. this.wrapAround = false;
  6145. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6146. this.map = null;
  6147. this.lightMap = null;
  6148. this.specularMap = null;
  6149. this.envMap = null;
  6150. this.combine = THREE.MultiplyOperation;
  6151. this.reflectivity = 1;
  6152. this.refractionRatio = 0.98;
  6153. this.fog = true;
  6154. this.shading = THREE.SmoothShading;
  6155. this.wireframe = false;
  6156. this.wireframeLinewidth = 1;
  6157. this.wireframeLinecap = 'round';
  6158. this.wireframeLinejoin = 'round';
  6159. this.vertexColors = THREE.NoColors;
  6160. this.skinning = false;
  6161. this.morphTargets = false;
  6162. this.morphNormals = false;
  6163. this.setValues( parameters );
  6164. };
  6165. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6166. THREE.MeshLambertMaterial.prototype.clone = function () {
  6167. var material = new THREE.MeshLambertMaterial();
  6168. THREE.Material.prototype.clone.call( this, material );
  6169. material.color.copy( this.color );
  6170. material.ambient.copy( this.ambient );
  6171. material.emissive.copy( this.emissive );
  6172. material.wrapAround = this.wrapAround;
  6173. material.wrapRGB.copy( this.wrapRGB );
  6174. material.map = this.map;
  6175. material.lightMap = this.lightMap;
  6176. material.specularMap = this.specularMap;
  6177. material.envMap = this.envMap;
  6178. material.combine = this.combine;
  6179. material.reflectivity = this.reflectivity;
  6180. material.refractionRatio = this.refractionRatio;
  6181. material.fog = this.fog;
  6182. material.shading = this.shading;
  6183. material.wireframe = this.wireframe;
  6184. material.wireframeLinewidth = this.wireframeLinewidth;
  6185. material.wireframeLinecap = this.wireframeLinecap;
  6186. material.wireframeLinejoin = this.wireframeLinejoin;
  6187. material.vertexColors = this.vertexColors;
  6188. material.skinning = this.skinning;
  6189. material.morphTargets = this.morphTargets;
  6190. material.morphNormals = this.morphNormals;
  6191. return material;
  6192. };
  6193. /**
  6194. * @author mrdoob / http://mrdoob.com/
  6195. * @author alteredq / http://alteredqualia.com/
  6196. *
  6197. * parameters = {
  6198. * color: <hex>,
  6199. * ambient: <hex>,
  6200. * emissive: <hex>,
  6201. * specular: <hex>,
  6202. * shininess: <float>,
  6203. * opacity: <float>,
  6204. *
  6205. * map: new THREE.Texture( <Image> ),
  6206. *
  6207. * lightMap: new THREE.Texture( <Image> ),
  6208. *
  6209. * bumpMap: new THREE.Texture( <Image> ),
  6210. * bumpScale: <float>,
  6211. *
  6212. * normalMap: new THREE.Texture( <Image> ),
  6213. * normalScale: <Vector2>,
  6214. *
  6215. * specularMap: new THREE.Texture( <Image> ),
  6216. *
  6217. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6218. * combine: THREE.Multiply,
  6219. * reflectivity: <float>,
  6220. * refractionRatio: <float>,
  6221. *
  6222. * shading: THREE.SmoothShading,
  6223. * blending: THREE.NormalBlending,
  6224. * depthTest: <bool>,
  6225. *
  6226. * wireframe: <boolean>,
  6227. * wireframeLinewidth: <float>,
  6228. *
  6229. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6230. *
  6231. * skinning: <bool>,
  6232. * morphTargets: <bool>,
  6233. * morphNormals: <bool>,
  6234. *
  6235. * fog: <bool>
  6236. * }
  6237. */
  6238. THREE.MeshPhongMaterial = function ( parameters ) {
  6239. THREE.Material.call( this );
  6240. this.color = new THREE.Color( 0xffffff ); // diffuse
  6241. this.ambient = new THREE.Color( 0xffffff );
  6242. this.emissive = new THREE.Color( 0x000000 );
  6243. this.specular = new THREE.Color( 0x111111 );
  6244. this.shininess = 30;
  6245. this.metal = false;
  6246. this.perPixel = false;
  6247. this.wrapAround = false;
  6248. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6249. this.map = null;
  6250. this.lightMap = null;
  6251. this.bumpMap = null;
  6252. this.bumpScale = 1;
  6253. this.normalMap = null;
  6254. this.normalScale = new THREE.Vector2( 1, 1 );
  6255. this.specularMap = null;
  6256. this.envMap = null;
  6257. this.combine = THREE.MultiplyOperation;
  6258. this.reflectivity = 1;
  6259. this.refractionRatio = 0.98;
  6260. this.fog = true;
  6261. this.shading = THREE.SmoothShading;
  6262. this.wireframe = false;
  6263. this.wireframeLinewidth = 1;
  6264. this.wireframeLinecap = 'round';
  6265. this.wireframeLinejoin = 'round';
  6266. this.vertexColors = THREE.NoColors;
  6267. this.skinning = false;
  6268. this.morphTargets = false;
  6269. this.morphNormals = false;
  6270. this.setValues( parameters );
  6271. };
  6272. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6273. THREE.MeshPhongMaterial.prototype.clone = function () {
  6274. var material = new THREE.MeshPhongMaterial();
  6275. THREE.Material.prototype.clone.call( this, material );
  6276. material.color.copy( this.color );
  6277. material.ambient.copy( this.ambient );
  6278. material.emissive.copy( this.emissive );
  6279. material.specular.copy( this.specular );
  6280. material.shininess = this.shininess;
  6281. material.metal = this.metal;
  6282. material.perPixel = this.perPixel;
  6283. material.wrapAround = this.wrapAround;
  6284. material.wrapRGB.copy( this.wrapRGB );
  6285. material.map = this.map;
  6286. material.lightMap = this.lightMap;
  6287. material.bumpMap = this.bumpMap;
  6288. material.bumpScale = this.bumpScale;
  6289. material.normalMap = this.normalMap;
  6290. material.normalScale.copy( this.normalScale );
  6291. material.specularMap = this.specularMap;
  6292. material.envMap = this.envMap;
  6293. material.combine = this.combine;
  6294. material.reflectivity = this.reflectivity;
  6295. material.refractionRatio = this.refractionRatio;
  6296. material.fog = this.fog;
  6297. material.shading = this.shading;
  6298. material.wireframe = this.wireframe;
  6299. material.wireframeLinewidth = this.wireframeLinewidth;
  6300. material.wireframeLinecap = this.wireframeLinecap;
  6301. material.wireframeLinejoin = this.wireframeLinejoin;
  6302. material.vertexColors = this.vertexColors;
  6303. material.skinning = this.skinning;
  6304. material.morphTargets = this.morphTargets;
  6305. material.morphNormals = this.morphNormals;
  6306. return material;
  6307. };
  6308. /**
  6309. * @author mrdoob / http://mrdoob.com/
  6310. * @author alteredq / http://alteredqualia.com/
  6311. *
  6312. * parameters = {
  6313. * opacity: <float>,
  6314. * blending: THREE.NormalBlending,
  6315. * depthTest: <bool>,
  6316. * wireframe: <boolean>,
  6317. * wireframeLinewidth: <float>
  6318. * }
  6319. */
  6320. THREE.MeshDepthMaterial = function ( parameters ) {
  6321. THREE.Material.call( this );
  6322. this.wireframe = false;
  6323. this.wireframeLinewidth = 1;
  6324. this.setValues( parameters );
  6325. };
  6326. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6327. THREE.MeshDepthMaterial.prototype.clone = function () {
  6328. var material = new THREE.LineBasicMaterial();
  6329. THREE.Material.prototype.clone.call( this, material );
  6330. material.wireframe = this.wireframe;
  6331. material.wireframeLinewidth = this.wireframeLinewidth;
  6332. return material;
  6333. };
  6334. /**
  6335. * @author mrdoob / http://mrdoob.com/
  6336. *
  6337. * parameters = {
  6338. * opacity: <float>,
  6339. * shading: THREE.FlatShading,
  6340. * blending: THREE.NormalBlending,
  6341. * depthTest: <bool>,
  6342. * wireframe: <boolean>,
  6343. * wireframeLinewidth: <float>
  6344. * }
  6345. */
  6346. THREE.MeshNormalMaterial = function ( parameters ) {
  6347. THREE.Material.call( this, parameters );
  6348. this.shading = THREE.FlatShading;
  6349. this.wireframe = false;
  6350. this.wireframeLinewidth = 1;
  6351. this.setValues( parameters );
  6352. };
  6353. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  6354. THREE.MeshNormalMaterial.prototype.clone = function () {
  6355. var material = new THREE.MeshNormalMaterial();
  6356. THREE.Material.prototype.clone.call( this, material );
  6357. material.shading = this.shading;
  6358. material.wireframe = this.wireframe;
  6359. material.wireframeLinewidth = this.wireframeLinewidth;
  6360. return material;
  6361. };
  6362. /**
  6363. * @author mrdoob / http://mrdoob.com/
  6364. */
  6365. THREE.MeshFaceMaterial = function () {};
  6366. THREE.MeshFaceMaterial.prototype.clone = function () {
  6367. return new THREE.MeshFaceMaterial();
  6368. };
  6369. /**
  6370. * @author mrdoob / http://mrdoob.com/
  6371. * @author alteredq / http://alteredqualia.com/
  6372. *
  6373. * parameters = {
  6374. * color: <hex>,
  6375. * opacity: <float>,
  6376. * map: new THREE.Texture( <Image> ),
  6377. *
  6378. * size: <float>,
  6379. *
  6380. * blending: THREE.NormalBlending,
  6381. * depthTest: <bool>,
  6382. *
  6383. * vertexColors: <bool>,
  6384. *
  6385. * fog: <bool>
  6386. * }
  6387. */
  6388. THREE.ParticleBasicMaterial = function ( parameters ) {
  6389. THREE.Material.call( this );
  6390. this.color = new THREE.Color( 0xffffff );
  6391. this.map = null;
  6392. this.size = 1;
  6393. this.sizeAttenuation = true;
  6394. this.vertexColors = false;
  6395. this.fog = true;
  6396. this.setValues( parameters );
  6397. };
  6398. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6399. THREE.ParticleBasicMaterial.prototype.clone = function () {
  6400. var material = new THREE.ParticleBasicMaterial();
  6401. THREE.Material.prototype.clone.call( this, material );
  6402. material.color.copy( this.color );
  6403. material.map = this.map;
  6404. material.size = this.size;
  6405. material.sizeAttenuation = this.sizeAttenuation;
  6406. material.vertexColors = this.vertexColors;
  6407. material.fog = this.fog;
  6408. return material;
  6409. };
  6410. /**
  6411. * @author mrdoob / http://mrdoob.com/
  6412. *
  6413. * parameters = {
  6414. * color: <hex>,
  6415. * program: <function>,
  6416. * opacity: <float>,
  6417. * blending: THREE.NormalBlending
  6418. * }
  6419. */
  6420. THREE.ParticleCanvasMaterial = function ( parameters ) {
  6421. THREE.Material.call( this );
  6422. this.color = new THREE.Color( 0xffffff );
  6423. this.program = function ( context, color ) {};
  6424. this.setValues( parameters );
  6425. };
  6426. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  6427. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  6428. var material = new THREE.ParticleCanvasMaterial();
  6429. THREE.Material.prototype.clone.call( this, material );
  6430. material.color.copy( this.color );
  6431. material.program = this.program;
  6432. return material;
  6433. };
  6434. /**
  6435. * @author mrdoob / http://mrdoob.com/
  6436. */
  6437. THREE.ParticleDOMMaterial = function ( element ) {
  6438. this.element = element;
  6439. };
  6440. THREE.ParticleDOMMaterial.prototype.clone = function(){
  6441. return new THREE.ParticleDOMMaterial( this.element );
  6442. };
  6443. /**
  6444. * @author alteredq / http://alteredqualia.com/
  6445. *
  6446. * parameters = {
  6447. * fragmentShader: <string>,
  6448. * vertexShader: <string>,
  6449. *
  6450. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  6451. *
  6452. * defines: { "label" : "value" },
  6453. *
  6454. * shading: THREE.SmoothShading,
  6455. * blending: THREE.NormalBlending,
  6456. * depthTest: <bool>,
  6457. *
  6458. * wireframe: <boolean>,
  6459. * wireframeLinewidth: <float>,
  6460. *
  6461. * lights: <bool>,
  6462. *
  6463. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6464. *
  6465. * skinning: <bool>,
  6466. * morphTargets: <bool>,
  6467. * morphNormals: <bool>,
  6468. *
  6469. * fog: <bool>
  6470. * }
  6471. */
  6472. THREE.ShaderMaterial = function ( parameters ) {
  6473. THREE.Material.call( this );
  6474. this.fragmentShader = "void main() {}";
  6475. this.vertexShader = "void main() {}";
  6476. this.uniforms = {};
  6477. this.defines = {};
  6478. this.attributes = null;
  6479. this.shading = THREE.SmoothShading;
  6480. this.wireframe = false;
  6481. this.wireframeLinewidth = 1;
  6482. this.fog = false; // set to use scene fog
  6483. this.lights = false; // set to use scene lights
  6484. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  6485. this.skinning = false; // set to use skinning attribute streams
  6486. this.morphTargets = false; // set to use morph targets
  6487. this.morphNormals = false; // set to use morph normals
  6488. this.setValues( parameters );
  6489. };
  6490. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  6491. THREE.ShaderMaterial.prototype.clone = function () {
  6492. var material = new THREE.ShaderMaterial();
  6493. THREE.Material.prototype.clone.call( this, material );
  6494. material.fragmentShader = this.fragmentShader;
  6495. material.vertexShader = this.vertexShader;
  6496. material.uniforms = this.uniforms;
  6497. material.attributes = this.attributes;
  6498. material.defines = this.defines;
  6499. material.shading = this.shading;
  6500. material.wireframe = this.wireframe;
  6501. material.wireframeLinewidth = this.wireframeLinewidth;
  6502. material.fog = this.fog;
  6503. material.lights = this.lights;
  6504. material.vertexColors = this.vertexColors;
  6505. material.skinning = this.skinning;
  6506. material.morphTargets = this.morphTargets;
  6507. material.morphNormals = this.morphNormals;
  6508. return material;
  6509. };
  6510. /**
  6511. * @author mrdoob / http://mrdoob.com/
  6512. * @author alteredq / http://alteredqualia.com/
  6513. * @author szimek / https://github.com/szimek/
  6514. */
  6515. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  6516. this.id = THREE.TextureLib.length;
  6517. THREE.TextureLib.push( this );
  6518. this.image = image;
  6519. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  6520. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  6521. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  6522. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  6523. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  6524. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6525. this.format = format !== undefined ? format : THREE.RGBAFormat;
  6526. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  6527. this.offset = new THREE.Vector2( 0, 0 );
  6528. this.repeat = new THREE.Vector2( 1, 1 );
  6529. this.generateMipmaps = true;
  6530. this.premultiplyAlpha = false;
  6531. this.flipY = true;
  6532. this.needsUpdate = false;
  6533. this.onUpdate = null;
  6534. };
  6535. THREE.Texture.prototype = {
  6536. constructor: THREE.Texture,
  6537. clone: function () {
  6538. var texture = new THREE.Texture();
  6539. texture.image = this.image;
  6540. texture.mapping = this.mapping;
  6541. texture.wrapS = this.wrapS;
  6542. texture.wrapT = this.wrapT;
  6543. texture.magFilter = this.magFilter;
  6544. texture.minFilter = this.minFilter;
  6545. texture.anisotropy = this.anisotropy;
  6546. texture.format = this.format;
  6547. texture.type = this.type;
  6548. texture.offset.copy( this.offset );
  6549. texture.repeat.copy( this.repeat );
  6550. texture.generateMipmaps = this.generateMipmaps;
  6551. texture.premultiplyAlpha = this.premultiplyAlpha;
  6552. texture.flipY = this.flipY;
  6553. return texture;
  6554. }
  6555. };
  6556. THREE.TextureLib = [];
  6557. /**
  6558. * @author alteredq / http://alteredqualia.com/
  6559. */
  6560. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  6561. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  6562. this.image = { width: width, height: height };
  6563. this.mipmaps = mipmaps;
  6564. };
  6565. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  6566. THREE.CompressedTexture.prototype.clone = function () {
  6567. var texture = new THREE.CompressedTexture();
  6568. texture.image = this.image;
  6569. texture.mipmaps = this.mipmaps;
  6570. texture.format = this.format;
  6571. texture.type = this.type;
  6572. texture.mapping = this.mapping;
  6573. texture.wrapS = this.wrapS;
  6574. texture.wrapT = this.wrapT;
  6575. texture.magFilter = this.magFilter;
  6576. texture.minFilter = this.minFilter;
  6577. texture.anisotropy = this.anisotropy;
  6578. texture.offset.copy( this.offset );
  6579. texture.repeat.copy( this.repeat );
  6580. return texture;
  6581. };
  6582. /**
  6583. * @author alteredq / http://alteredqualia.com/
  6584. */
  6585. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  6586. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  6587. this.image = { data: data, width: width, height: height };
  6588. };
  6589. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  6590. THREE.DataTexture.prototype.clone = function () {
  6591. 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 );
  6592. clonedTexture.offset.copy( this.offset );
  6593. clonedTexture.repeat.copy( this.repeat );
  6594. return clonedTexture;
  6595. };
  6596. /**
  6597. * @author mrdoob / http://mrdoob.com/
  6598. */
  6599. THREE.Particle = function ( material ) {
  6600. THREE.Object3D.call( this );
  6601. this.material = material;
  6602. };
  6603. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  6604. THREE.Particle.prototype.clone = function ( object ) {
  6605. if ( object === undefined ) object = new THREE.Particle( this.material );
  6606. THREE.Object3D.prototype.clone.call( this, object );
  6607. return object;
  6608. };
  6609. /**
  6610. * @author alteredq / http://alteredqualia.com/
  6611. */
  6612. THREE.ParticleSystem = function ( geometry, material ) {
  6613. THREE.Object3D.call( this );
  6614. this.geometry = geometry;
  6615. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  6616. this.sortParticles = false;
  6617. if ( this.geometry ) {
  6618. // calc bound radius
  6619. if( this.geometry.boundingSphere === null ) {
  6620. this.geometry.computeBoundingSphere();
  6621. }
  6622. this.boundRadius = geometry.boundingSphere.radius;
  6623. }
  6624. this.frustumCulled = false;
  6625. };
  6626. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  6627. THREE.ParticleSystem.prototype.clone = function ( object ) {
  6628. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  6629. object.sortParticles = this.sortParticles;
  6630. THREE.Object3D.prototype.clone.call( this, object );
  6631. return object;
  6632. };
  6633. /**
  6634. * @author mrdoob / http://mrdoob.com/
  6635. */
  6636. THREE.Line = function ( geometry, material, type ) {
  6637. THREE.Object3D.call( this );
  6638. this.geometry = geometry;
  6639. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  6640. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  6641. if ( this.geometry ) {
  6642. if ( ! this.geometry.boundingSphere ) {
  6643. this.geometry.computeBoundingSphere();
  6644. }
  6645. }
  6646. };
  6647. THREE.LineStrip = 0;
  6648. THREE.LinePieces = 1;
  6649. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  6650. THREE.Line.prototype.clone = function ( object ) {
  6651. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  6652. THREE.Object3D.prototype.clone.call( this, object );
  6653. return object;
  6654. };
  6655. /**
  6656. * @author mrdoob / http://mrdoob.com/
  6657. * @author alteredq / http://alteredqualia.com/
  6658. * @author mikael emtinger / http://gomo.se/
  6659. */
  6660. THREE.Mesh = function ( geometry, material ) {
  6661. THREE.Object3D.call( this );
  6662. this.geometry = geometry;
  6663. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  6664. if ( this.geometry ) {
  6665. // calc bound radius
  6666. if ( this.geometry.boundingSphere === null ) {
  6667. this.geometry.computeBoundingSphere();
  6668. }
  6669. this.boundRadius = geometry.boundingSphere.radius;
  6670. // setup morph targets
  6671. if ( this.geometry.morphTargets.length ) {
  6672. this.morphTargetBase = -1;
  6673. this.morphTargetForcedOrder = [];
  6674. this.morphTargetInfluences = [];
  6675. this.morphTargetDictionary = {};
  6676. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  6677. this.morphTargetInfluences.push( 0 );
  6678. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  6679. }
  6680. }
  6681. }
  6682. }
  6683. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  6684. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  6685. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  6686. return this.morphTargetDictionary[ name ];
  6687. }
  6688. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  6689. return 0;
  6690. };
  6691. THREE.Mesh.prototype.clone = function ( object ) {
  6692. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  6693. THREE.Object3D.prototype.clone.call( this, object );
  6694. return object;
  6695. };
  6696. /**
  6697. * @author mikael emtinger / http://gomo.se/
  6698. * @author alteredq / http://alteredqualia.com/
  6699. */
  6700. THREE.Bone = function( belongsToSkin ) {
  6701. THREE.Object3D.call( this );
  6702. this.skin = belongsToSkin;
  6703. this.skinMatrix = new THREE.Matrix4();
  6704. };
  6705. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  6706. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  6707. // update local
  6708. if ( this.matrixAutoUpdate ) {
  6709. forceUpdate |= this.updateMatrix();
  6710. }
  6711. // update skin matrix
  6712. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  6713. if( parentSkinMatrix ) {
  6714. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  6715. } else {
  6716. this.skinMatrix.copy( this.matrix );
  6717. }
  6718. this.matrixWorldNeedsUpdate = false;
  6719. forceUpdate = true;
  6720. }
  6721. // update children
  6722. var child, i, l = this.children.length;
  6723. for ( i = 0; i < l; i ++ ) {
  6724. this.children[ i ].update( this.skinMatrix, forceUpdate );
  6725. }
  6726. };
  6727. /**
  6728. * @author mikael emtinger / http://gomo.se/
  6729. * @author alteredq / http://alteredqualia.com/
  6730. */
  6731. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  6732. THREE.Mesh.call( this, geometry, material );
  6733. //
  6734. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  6735. // init bones
  6736. this.identityMatrix = new THREE.Matrix4();
  6737. this.bones = [];
  6738. this.boneMatrices = [];
  6739. var b, bone, gbone, p, q, s;
  6740. if ( this.geometry.bones !== undefined ) {
  6741. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  6742. gbone = this.geometry.bones[ b ];
  6743. p = gbone.pos;
  6744. q = gbone.rotq;
  6745. s = gbone.scl;
  6746. bone = this.addBone();
  6747. bone.name = gbone.name;
  6748. bone.position.set( p[0], p[1], p[2] );
  6749. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  6750. bone.useQuaternion = true;
  6751. if ( s !== undefined ) {
  6752. bone.scale.set( s[0], s[1], s[2] );
  6753. } else {
  6754. bone.scale.set( 1, 1, 1 );
  6755. }
  6756. }
  6757. for ( b = 0; b < this.bones.length; b ++ ) {
  6758. gbone = this.geometry.bones[ b ];
  6759. bone = this.bones[ b ];
  6760. if ( gbone.parent === -1 ) {
  6761. this.add( bone );
  6762. } else {
  6763. this.bones[ gbone.parent ].add( bone );
  6764. }
  6765. }
  6766. //
  6767. var nBones = this.bones.length;
  6768. if ( this.useVertexTexture ) {
  6769. // layout (1 matrix = 4 pixels)
  6770. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  6771. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  6772. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  6773. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  6774. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  6775. var size;
  6776. if ( nBones > 256 )
  6777. size = 64;
  6778. else if ( nBones > 64 )
  6779. size = 32;
  6780. else if ( nBones > 16 )
  6781. size = 16;
  6782. else
  6783. size = 8;
  6784. this.boneTextureWidth = size;
  6785. this.boneTextureHeight = size;
  6786. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  6787. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  6788. this.boneTexture.minFilter = THREE.NearestFilter;
  6789. this.boneTexture.magFilter = THREE.NearestFilter;
  6790. this.boneTexture.generateMipmaps = false;
  6791. this.boneTexture.flipY = false;
  6792. } else {
  6793. this.boneMatrices = new Float32Array( 16 * nBones );
  6794. }
  6795. this.pose();
  6796. }
  6797. };
  6798. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  6799. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  6800. if ( bone === undefined ) {
  6801. bone = new THREE.Bone( this );
  6802. }
  6803. this.bones.push( bone );
  6804. return bone;
  6805. };
  6806. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  6807. this.matrixAutoUpdate && this.updateMatrix();
  6808. // update matrixWorld
  6809. if ( this.matrixWorldNeedsUpdate || force ) {
  6810. if ( this.parent ) {
  6811. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  6812. } else {
  6813. this.matrixWorld.copy( this.matrix );
  6814. }
  6815. this.matrixWorldNeedsUpdate = false;
  6816. force = true;
  6817. }
  6818. // update children
  6819. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6820. var child = this.children[ i ];
  6821. if ( child instanceof THREE.Bone ) {
  6822. child.update( this.identityMatrix, false );
  6823. } else {
  6824. child.updateMatrixWorld( true );
  6825. }
  6826. }
  6827. // make a snapshot of the bones' rest position
  6828. if ( this.boneInverses == undefined ) {
  6829. this.boneInverses = [];
  6830. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6831. var inverse = new THREE.Matrix4();
  6832. inverse.getInverse( this.bones[ b ].skinMatrix );
  6833. this.boneInverses.push( inverse );
  6834. }
  6835. }
  6836. // flatten bone matrices to array
  6837. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6838. // compute the offset between the current and the original transform;
  6839. //TODO: we could get rid of this multiplication step if the skinMatrix
  6840. // was already representing the offset; however, this requires some
  6841. // major changes to the animation system
  6842. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  6843. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  6844. }
  6845. if ( this.useVertexTexture ) {
  6846. this.boneTexture.needsUpdate = true;
  6847. }
  6848. };
  6849. THREE.SkinnedMesh.prototype.pose = function() {
  6850. this.updateMatrixWorld( true );
  6851. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  6852. // normalize weights
  6853. var sw = this.geometry.skinWeights[ i ];
  6854. var scale = 1.0 / sw.lengthManhattan();
  6855. if ( scale !== Infinity ) {
  6856. sw.multiplyScalar( scale );
  6857. } else {
  6858. sw.set( 1 ); // this will be normalized by the shader anyway
  6859. }
  6860. }
  6861. };
  6862. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  6863. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  6864. THREE.Mesh.prototype.clone.call( this, object );
  6865. return object;
  6866. };
  6867. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  6868. /**
  6869. * @author alteredq / http://alteredqualia.com/
  6870. */
  6871. THREE.MorphAnimMesh = function ( geometry, material ) {
  6872. THREE.Mesh.call( this, geometry, material );
  6873. // API
  6874. this.duration = 1000; // milliseconds
  6875. this.mirroredLoop = false;
  6876. this.time = 0;
  6877. // internals
  6878. this.lastKeyframe = 0;
  6879. this.currentKeyframe = 0;
  6880. this.direction = 1;
  6881. this.directionBackwards = false;
  6882. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  6883. };
  6884. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  6885. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  6886. this.startKeyframe = start;
  6887. this.endKeyframe = end;
  6888. this.length = this.endKeyframe - this.startKeyframe + 1;
  6889. };
  6890. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  6891. this.direction = 1;
  6892. this.directionBackwards = false;
  6893. };
  6894. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  6895. this.direction = -1;
  6896. this.directionBackwards = true;
  6897. };
  6898. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  6899. var geometry = this.geometry;
  6900. if ( ! geometry.animations ) geometry.animations = {};
  6901. var firstAnimation, animations = geometry.animations;
  6902. var pattern = /([a-z]+)(\d+)/;
  6903. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  6904. var morph = geometry.morphTargets[ i ];
  6905. var parts = morph.name.match( pattern );
  6906. if ( parts && parts.length > 1 ) {
  6907. var label = parts[ 1 ];
  6908. var num = parts[ 2 ];
  6909. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  6910. var animation = animations[ label ];
  6911. if ( i < animation.start ) animation.start = i;
  6912. if ( i > animation.end ) animation.end = i;
  6913. if ( ! firstAnimation ) firstAnimation = label;
  6914. }
  6915. }
  6916. geometry.firstAnimation = firstAnimation;
  6917. };
  6918. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  6919. if ( ! this.geometry.animations ) this.geometry.animations = {};
  6920. this.geometry.animations[ label ] = { start: start, end: end };
  6921. };
  6922. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  6923. var animation = this.geometry.animations[ label ];
  6924. if ( animation ) {
  6925. this.setFrameRange( animation.start, animation.end );
  6926. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  6927. this.time = 0;
  6928. } else {
  6929. console.warn( "animation[" + label + "] undefined" );
  6930. }
  6931. };
  6932. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  6933. var frameTime = this.duration / this.length;
  6934. this.time += this.direction * delta;
  6935. if ( this.mirroredLoop ) {
  6936. if ( this.time > this.duration || this.time < 0 ) {
  6937. this.direction *= -1;
  6938. if ( this.time > this.duration ) {
  6939. this.time = this.duration;
  6940. this.directionBackwards = true;
  6941. }
  6942. if ( this.time < 0 ) {
  6943. this.time = 0;
  6944. this.directionBackwards = false;
  6945. }
  6946. }
  6947. } else {
  6948. this.time = this.time % this.duration;
  6949. if ( this.time < 0 ) this.time += this.duration;
  6950. }
  6951. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  6952. if ( keyframe !== this.currentKeyframe ) {
  6953. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  6954. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  6955. this.morphTargetInfluences[ keyframe ] = 0;
  6956. this.lastKeyframe = this.currentKeyframe;
  6957. this.currentKeyframe = keyframe;
  6958. }
  6959. var mix = ( this.time % frameTime ) / frameTime;
  6960. if ( this.directionBackwards ) {
  6961. mix = 1 - mix;
  6962. }
  6963. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  6964. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  6965. };
  6966. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  6967. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  6968. object.duration = this.duration;
  6969. object.mirroredLoop = this.mirroredLoop;
  6970. object.time = this.time;
  6971. object.lastKeyframe = this.lastKeyframe;
  6972. object.currentKeyframe = this.currentKeyframe;
  6973. object.direction = this.direction;
  6974. object.directionBackwards = this.directionBackwards;
  6975. THREE.Mesh.prototype.clone.call( this, object );
  6976. return object;
  6977. };
  6978. /**
  6979. * @author alteredq / http://alteredqualia.com/
  6980. */
  6981. THREE.Ribbon = function ( geometry, material ) {
  6982. THREE.Object3D.call( this );
  6983. this.geometry = geometry;
  6984. this.material = material;
  6985. };
  6986. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  6987. THREE.Ribbon.prototype.clone = function ( object ) {
  6988. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  6989. THREE.Object3D.prototype.clone.call( this, object );
  6990. return object;
  6991. };
  6992. /**
  6993. * @author mikael emtinger / http://gomo.se/
  6994. * @author alteredq / http://alteredqualia.com/
  6995. * @author mrdoob / http://mrdoob.com/
  6996. */
  6997. THREE.LOD = function () {
  6998. THREE.Object3D.call( this );
  6999. this.LODs = [];
  7000. };
  7001. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7002. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7003. if ( visibleAtDistance === undefined ) {
  7004. visibleAtDistance = 0;
  7005. }
  7006. visibleAtDistance = Math.abs( visibleAtDistance );
  7007. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7008. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7009. break;
  7010. }
  7011. }
  7012. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7013. this.add( object3D );
  7014. };
  7015. THREE.LOD.prototype.update = function ( camera ) {
  7016. if ( this.LODs.length > 1 ) {
  7017. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7018. var inverse = camera.matrixWorldInverse;
  7019. 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] );
  7020. this.LODs[ 0 ].object3D.visible = true;
  7021. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7022. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7023. this.LODs[ l - 1 ].object3D.visible = false;
  7024. this.LODs[ l ].object3D.visible = true;
  7025. } else {
  7026. break;
  7027. }
  7028. }
  7029. for( ; l < this.LODs.length; l ++ ) {
  7030. this.LODs[ l ].object3D.visible = false;
  7031. }
  7032. }
  7033. };
  7034. THREE.LOD.prototype.clone = function () {
  7035. // TODO
  7036. };
  7037. /**
  7038. * @author mikael emtinger / http://gomo.se/
  7039. */
  7040. THREE.Sprite = function ( parameters ) {
  7041. THREE.Object3D.call( this );
  7042. this.color = ( parameters.color !== undefined ) ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  7043. this.map = ( parameters.map !== undefined ) ? parameters.map : new THREE.Texture();
  7044. this.blending = ( parameters.blending !== undefined ) ? parameters.blending : THREE.NormalBlending;
  7045. this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
  7046. this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
  7047. this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
  7048. this.useScreenCoordinates = ( parameters.useScreenCoordinates !== undefined ) ? parameters.useScreenCoordinates : true;
  7049. this.mergeWith3D = ( parameters.mergeWith3D !== undefined ) ? parameters.mergeWith3D : !this.useScreenCoordinates;
  7050. this.affectedByDistance = ( parameters.affectedByDistance !== undefined ) ? parameters.affectedByDistance : !this.useScreenCoordinates;
  7051. this.scaleByViewport = ( parameters.scaleByViewport !== undefined ) ? parameters.scaleByViewport : !this.affectedByDistance;
  7052. this.alignment = ( parameters.alignment instanceof THREE.Vector2 ) ? parameters.alignment : THREE.SpriteAlignment.center;
  7053. this.rotation3d = this.rotation;
  7054. this.rotation = 0;
  7055. this.opacity = 1;
  7056. this.uvOffset = new THREE.Vector2( 0, 0 );
  7057. this.uvScale = new THREE.Vector2( 1, 1 );
  7058. };
  7059. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7060. /*
  7061. * Custom update matrix
  7062. */
  7063. THREE.Sprite.prototype.updateMatrix = function () {
  7064. this.matrix.setPosition( this.position );
  7065. this.rotation3d.set( 0, 0, this.rotation );
  7066. this.matrix.setRotationFromEuler( this.rotation3d );
  7067. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7068. this.matrix.scale( this.scale );
  7069. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  7070. }
  7071. this.matrixWorldNeedsUpdate = true;
  7072. };
  7073. THREE.Sprite.prototype.clone = function ( object ) {
  7074. if ( object === undefined ) object = new THREE.Sprite( {} );
  7075. object.color.copy( this.color );
  7076. object.map = this.map;
  7077. object.blending = this.blending;
  7078. object.useScreenCoordinates = this.useScreenCoordinates;
  7079. object.mergeWith3D = this.mergeWith3D;
  7080. object.affectedByDistance = this.affectedByDistance;
  7081. object.scaleByViewport = this.scaleByViewport;
  7082. object.alignment = this.alignment;
  7083. object.rotation3d.copy( this.rotation3d );
  7084. object.rotation = this.rotation;
  7085. object.opacity = this.opacity;
  7086. object.uvOffset.copy( this.uvOffset );
  7087. object.uvScale.copy( this.uvScale);
  7088. THREE.Object3D.prototype.clone.call( this, object );
  7089. return object;
  7090. };
  7091. /*
  7092. * Alignment
  7093. */
  7094. THREE.SpriteAlignment = {};
  7095. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7096. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7097. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7098. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7099. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7100. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7101. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7102. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7103. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7104. /**
  7105. * @author mrdoob / http://mrdoob.com/
  7106. */
  7107. THREE.Scene = function () {
  7108. THREE.Object3D.call( this );
  7109. this.fog = null;
  7110. this.overrideMaterial = null;
  7111. this.matrixAutoUpdate = false;
  7112. this.__objects = [];
  7113. this.__lights = [];
  7114. this.__objectsAdded = [];
  7115. this.__objectsRemoved = [];
  7116. };
  7117. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7118. THREE.Scene.prototype.__addObject = function ( object ) {
  7119. if ( object instanceof THREE.Light ) {
  7120. if ( this.__lights.indexOf( object ) === - 1 ) {
  7121. this.__lights.push( object );
  7122. }
  7123. if ( object.target && object.target.parent === undefined ) {
  7124. this.add( object.target );
  7125. }
  7126. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7127. if ( this.__objects.indexOf( object ) === - 1 ) {
  7128. this.__objects.push( object );
  7129. this.__objectsAdded.push( object );
  7130. // check if previously removed
  7131. var i = this.__objectsRemoved.indexOf( object );
  7132. if ( i !== -1 ) {
  7133. this.__objectsRemoved.splice( i, 1 );
  7134. }
  7135. }
  7136. }
  7137. for ( var c = 0; c < object.children.length; c ++ ) {
  7138. this.__addObject( object.children[ c ] );
  7139. }
  7140. };
  7141. THREE.Scene.prototype.__removeObject = function ( object ) {
  7142. if ( object instanceof THREE.Light ) {
  7143. var i = this.__lights.indexOf( object );
  7144. if ( i !== -1 ) {
  7145. this.__lights.splice( i, 1 );
  7146. }
  7147. } else if ( !( object instanceof THREE.Camera ) ) {
  7148. var i = this.__objects.indexOf( object );
  7149. if( i !== -1 ) {
  7150. this.__objects.splice( i, 1 );
  7151. this.__objectsRemoved.push( object );
  7152. // check if previously added
  7153. var ai = this.__objectsAdded.indexOf( object );
  7154. if ( ai !== -1 ) {
  7155. this.__objectsAdded.splice( ai, 1 );
  7156. }
  7157. }
  7158. }
  7159. for ( var c = 0; c < object.children.length; c ++ ) {
  7160. this.__removeObject( object.children[ c ] );
  7161. }
  7162. };
  7163. /**
  7164. * @author mrdoob / http://mrdoob.com/
  7165. * @author alteredq / http://alteredqualia.com/
  7166. */
  7167. THREE.Fog = function ( hex, near, far ) {
  7168. this.color = new THREE.Color( hex );
  7169. this.near = ( near !== undefined ) ? near : 1;
  7170. this.far = ( far !== undefined ) ? far : 1000;
  7171. };
  7172. /**
  7173. * @author mrdoob / http://mrdoob.com/
  7174. * @author alteredq / http://alteredqualia.com/
  7175. */
  7176. THREE.FogExp2 = function ( hex, density ) {
  7177. this.color = new THREE.Color( hex );
  7178. this.density = ( density !== undefined ) ? density : 0.00025;
  7179. };
  7180. /**
  7181. * @author mrdoob / http://mrdoob.com/
  7182. */
  7183. THREE.CanvasRenderer = function ( parameters ) {
  7184. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7185. parameters = parameters || {};
  7186. var _this = this,
  7187. _renderData, _elements, _lights,
  7188. _projector = new THREE.Projector(),
  7189. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  7190. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7191. _context = _canvas.getContext( '2d' ),
  7192. _clearColor = new THREE.Color( 0x000000 ),
  7193. _clearOpacity = 0,
  7194. _contextGlobalAlpha = 1,
  7195. _contextGlobalCompositeOperation = 0,
  7196. _contextStrokeStyle = null,
  7197. _contextFillStyle = null,
  7198. _contextLineWidth = null,
  7199. _contextLineCap = null,
  7200. _contextLineJoin = null,
  7201. _v1, _v2, _v3, _v4,
  7202. _v5 = new THREE.RenderableVertex(),
  7203. _v6 = new THREE.RenderableVertex(),
  7204. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7205. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7206. _color = new THREE.Color(),
  7207. _color1 = new THREE.Color(),
  7208. _color2 = new THREE.Color(),
  7209. _color3 = new THREE.Color(),
  7210. _color4 = new THREE.Color(),
  7211. _diffuseColor = new THREE.Color(),
  7212. _emissiveColor = new THREE.Color(),
  7213. _patterns = {}, _imagedatas = {},
  7214. _near, _far,
  7215. _image, _uvs,
  7216. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7217. _clipRect = new THREE.Rectangle(),
  7218. _clearRect = new THREE.Rectangle(),
  7219. _bboxRect = new THREE.Rectangle(),
  7220. _enableLighting = false,
  7221. _ambientLight = new THREE.Color(),
  7222. _directionalLights = new THREE.Color(),
  7223. _pointLights = new THREE.Color(),
  7224. _pi2 = Math.PI * 2,
  7225. _vector3 = new THREE.Vector3(), // Needed for PointLight
  7226. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  7227. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  7228. _pixelMap = document.createElement( 'canvas' );
  7229. _pixelMap.width = _pixelMap.height = 2;
  7230. _pixelMapContext = _pixelMap.getContext( '2d' );
  7231. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  7232. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  7233. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  7234. _pixelMapData = _pixelMapImage.data;
  7235. _gradientMap = document.createElement( 'canvas' );
  7236. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  7237. _gradientMapContext = _gradientMap.getContext( '2d' );
  7238. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  7239. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  7240. _gradientMapQuality --; // Fix UVs
  7241. this.domElement = _canvas;
  7242. this.autoClear = true;
  7243. this.sortObjects = true;
  7244. this.sortElements = true;
  7245. this.info = {
  7246. render: {
  7247. vertices: 0,
  7248. faces: 0
  7249. }
  7250. }
  7251. this.setSize = function ( width, height ) {
  7252. _canvasWidth = width;
  7253. _canvasHeight = height;
  7254. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  7255. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  7256. _canvas.width = _canvasWidth;
  7257. _canvas.height = _canvasHeight;
  7258. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7259. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7260. _contextGlobalAlpha = 1;
  7261. _contextGlobalCompositeOperation = 0;
  7262. _contextStrokeStyle = null;
  7263. _contextFillStyle = null;
  7264. _contextLineWidth = null;
  7265. _contextLineCap = null;
  7266. _contextLineJoin = null;
  7267. };
  7268. this.setClearColor = function ( color, opacity ) {
  7269. _clearColor.copy( color );
  7270. _clearOpacity = opacity !== undefined ? opacity : 1;
  7271. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7272. };
  7273. this.setClearColorHex = function ( hex, opacity ) {
  7274. _clearColor.setHex( hex );
  7275. _clearOpacity = opacity !== undefined ? opacity : 1;
  7276. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7277. };
  7278. this.getMaxAnisotropy = function () {
  7279. return 0;
  7280. };
  7281. this.clear = function () {
  7282. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7283. if ( _clearRect.isEmpty() === false ) {
  7284. _clearRect.minSelf( _clipRect );
  7285. _clearRect.inflate( 2 );
  7286. if ( _clearOpacity < 1 ) {
  7287. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7288. }
  7289. if ( _clearOpacity > 0 ) {
  7290. setBlending( THREE.NormalBlending );
  7291. setOpacity( 1 );
  7292. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  7293. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7294. }
  7295. _clearRect.empty();
  7296. }
  7297. };
  7298. this.render = function ( scene, camera ) {
  7299. if ( camera instanceof THREE.Camera === false ) {
  7300. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  7301. return;
  7302. }
  7303. var e, el, element, material;
  7304. this.autoClear === true
  7305. ? this.clear()
  7306. : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7307. _this.info.render.vertices = 0;
  7308. _this.info.render.faces = 0;
  7309. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  7310. _elements = _renderData.elements;
  7311. _lights = _renderData.lights;
  7312. /* DEBUG
  7313. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  7314. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  7315. */
  7316. _enableLighting = _lights.length > 0;
  7317. if ( _enableLighting === true ) {
  7318. calculateLights();
  7319. }
  7320. for ( e = 0, el = _elements.length; e < el; e++ ) {
  7321. element = _elements[ e ];
  7322. material = element.material;
  7323. if ( material === undefined || material.visible === false ) continue;
  7324. _bboxRect.empty();
  7325. if ( element instanceof THREE.RenderableParticle ) {
  7326. _v1 = element;
  7327. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  7328. renderParticle( _v1, element, material, scene );
  7329. } else if ( element instanceof THREE.RenderableLine ) {
  7330. _v1 = element.v1; _v2 = element.v2;
  7331. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7332. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7333. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7334. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7335. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7336. renderLine( _v1, _v2, element, material, scene );
  7337. }
  7338. } else if ( element instanceof THREE.RenderableFace3 ) {
  7339. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  7340. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7341. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7342. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7343. if ( material.overdraw === true ) {
  7344. expand( _v1.positionScreen, _v2.positionScreen );
  7345. expand( _v2.positionScreen, _v3.positionScreen );
  7346. expand( _v3.positionScreen, _v1.positionScreen );
  7347. }
  7348. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  7349. _v2.positionScreen.x, _v2.positionScreen.y,
  7350. _v3.positionScreen.x, _v3.positionScreen.y );
  7351. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7352. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  7353. }
  7354. } else if ( element instanceof THREE.RenderableFace4 ) {
  7355. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  7356. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7357. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7358. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7359. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  7360. _v5.positionScreen.copy( _v2.positionScreen );
  7361. _v6.positionScreen.copy( _v4.positionScreen );
  7362. if ( material.overdraw === true ) {
  7363. expand( _v1.positionScreen, _v2.positionScreen );
  7364. expand( _v2.positionScreen, _v4.positionScreen );
  7365. expand( _v4.positionScreen, _v1.positionScreen );
  7366. expand( _v3.positionScreen, _v5.positionScreen );
  7367. expand( _v3.positionScreen, _v6.positionScreen );
  7368. }
  7369. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7370. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7371. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  7372. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  7373. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7374. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  7375. }
  7376. }
  7377. /* DEBUG
  7378. _context.lineWidth = 1;
  7379. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  7380. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  7381. */
  7382. _clearRect.addRectangle( _bboxRect );
  7383. }
  7384. /* DEBUG
  7385. _context.lineWidth = 1;
  7386. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  7387. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  7388. */
  7389. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  7390. //
  7391. function calculateLights() {
  7392. _ambientLight.setRGB( 0, 0, 0 );
  7393. _directionalLights.setRGB( 0, 0, 0 );
  7394. _pointLights.setRGB( 0, 0, 0 );
  7395. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7396. var light = _lights[ l ];
  7397. var lightColor = light.color;
  7398. if ( light instanceof THREE.AmbientLight ) {
  7399. _ambientLight.r += lightColor.r;
  7400. _ambientLight.g += lightColor.g;
  7401. _ambientLight.b += lightColor.b;
  7402. } else if ( light instanceof THREE.DirectionalLight ) {
  7403. // for particles
  7404. _directionalLights.r += lightColor.r;
  7405. _directionalLights.g += lightColor.g;
  7406. _directionalLights.b += lightColor.b;
  7407. } else if ( light instanceof THREE.PointLight ) {
  7408. // for particles
  7409. _pointLights.r += lightColor.r;
  7410. _pointLights.g += lightColor.g;
  7411. _pointLights.b += lightColor.b;
  7412. }
  7413. }
  7414. }
  7415. function calculateLight( position, normal, color ) {
  7416. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7417. var light = _lights[ l ];
  7418. var lightColor = light.color;
  7419. if ( light instanceof THREE.DirectionalLight ) {
  7420. var lightPosition = light.matrixWorld.getPosition().normalize();
  7421. var amount = normal.dot( lightPosition );
  7422. if ( amount <= 0 ) continue;
  7423. amount *= light.intensity;
  7424. color.r += lightColor.r * amount;
  7425. color.g += lightColor.g * amount;
  7426. color.b += lightColor.b * amount;
  7427. } else if ( light instanceof THREE.PointLight ) {
  7428. var lightPosition = light.matrixWorld.getPosition();
  7429. var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  7430. if ( amount <= 0 ) continue;
  7431. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  7432. if ( amount == 0 ) continue;
  7433. amount *= light.intensity;
  7434. color.r += lightColor.r * amount;
  7435. color.g += lightColor.g * amount;
  7436. color.b += lightColor.b * amount;
  7437. }
  7438. }
  7439. }
  7440. function renderParticle( v1, element, material, scene ) {
  7441. setOpacity( material.opacity );
  7442. setBlending( material.blending );
  7443. var width, height, scaleX, scaleY,
  7444. bitmap, bitmapWidth, bitmapHeight;
  7445. if ( material instanceof THREE.ParticleBasicMaterial ) {
  7446. if ( material.map === null ) {
  7447. scaleX = element.object.scale.x;
  7448. scaleY = element.object.scale.y;
  7449. // TODO: Be able to disable this
  7450. scaleX *= element.scale.x * _canvasWidthHalf;
  7451. scaleY *= element.scale.y * _canvasHeightHalf;
  7452. _bboxRect.set( v1.x - scaleX, v1.y - scaleY, v1.x + scaleX, v1.y + scaleY );
  7453. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7454. return;
  7455. }
  7456. setFillStyle( material.color.getContextStyle() );
  7457. _context.save();
  7458. _context.translate( v1.x, v1.y );
  7459. _context.rotate( - element.rotation );
  7460. _context.scale( scaleX, scaleY );
  7461. _context.fillRect( -1, -1, 2, 2 );
  7462. _context.restore();
  7463. } else {
  7464. bitmap = material.map.image;
  7465. bitmapWidth = bitmap.width >> 1;
  7466. bitmapHeight = bitmap.height >> 1;
  7467. scaleX = element.scale.x * _canvasWidthHalf;
  7468. scaleY = element.scale.y * _canvasHeightHalf;
  7469. width = scaleX * bitmapWidth;
  7470. height = scaleY * bitmapHeight;
  7471. // TODO: Rotations break this...
  7472. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7473. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7474. return;
  7475. }
  7476. _context.save();
  7477. _context.translate( v1.x, v1.y );
  7478. _context.rotate( - element.rotation );
  7479. _context.scale( scaleX, - scaleY );
  7480. _context.translate( - bitmapWidth, - bitmapHeight );
  7481. _context.drawImage( bitmap, 0, 0 );
  7482. _context.restore();
  7483. }
  7484. /* DEBUG
  7485. setStrokeStyle( 'rgb(255,255,0)' );
  7486. _context.beginPath();
  7487. _context.moveTo( v1.x - 10, v1.y );
  7488. _context.lineTo( v1.x + 10, v1.y );
  7489. _context.moveTo( v1.x, v1.y - 10 );
  7490. _context.lineTo( v1.x, v1.y + 10 );
  7491. _context.stroke();
  7492. */
  7493. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  7494. width = element.scale.x * _canvasWidthHalf;
  7495. height = element.scale.y * _canvasHeightHalf;
  7496. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7497. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7498. return;
  7499. }
  7500. setStrokeStyle( material.color.getContextStyle() );
  7501. setFillStyle( material.color.getContextStyle() );
  7502. _context.save();
  7503. _context.translate( v1.x, v1.y );
  7504. _context.rotate( - element.rotation );
  7505. _context.scale( width, height );
  7506. material.program( _context );
  7507. _context.restore();
  7508. }
  7509. }
  7510. function renderLine( v1, v2, element, material, scene ) {
  7511. setOpacity( material.opacity );
  7512. setBlending( material.blending );
  7513. _context.beginPath();
  7514. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  7515. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  7516. if ( material instanceof THREE.LineBasicMaterial ) {
  7517. setLineWidth( material.linewidth );
  7518. setLineCap( material.linecap );
  7519. setLineJoin( material.linejoin );
  7520. setStrokeStyle( material.color.getContextStyle() );
  7521. _context.stroke();
  7522. _bboxRect.inflate( material.linewidth * 2 );
  7523. }
  7524. }
  7525. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  7526. _this.info.render.vertices += 3;
  7527. _this.info.render.faces ++;
  7528. setOpacity( material.opacity );
  7529. setBlending( material.blending );
  7530. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7531. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7532. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7533. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  7534. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  7535. _diffuseColor.copy( material.color );
  7536. _emissiveColor.copy( material.emissive );
  7537. if ( material.vertexColors === THREE.FaceColors ) {
  7538. _diffuseColor.r *= element.color.r;
  7539. _diffuseColor.g *= element.color.g;
  7540. _diffuseColor.b *= element.color.b;
  7541. }
  7542. if ( _enableLighting === true ) {
  7543. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  7544. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  7545. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  7546. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  7547. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7548. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7549. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  7550. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7551. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7552. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7553. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7554. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7555. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7556. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7557. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7558. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7559. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7560. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7561. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7562. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7563. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7564. } else {
  7565. _color.r = _ambientLight.r;
  7566. _color.g = _ambientLight.g;
  7567. _color.b = _ambientLight.b;
  7568. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7569. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7570. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7571. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7572. material.wireframe === true
  7573. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7574. : fillPath( _color );
  7575. }
  7576. } else {
  7577. material.wireframe === true
  7578. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7579. : fillPath( material.color );
  7580. }
  7581. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7582. if ( material.map !== null ) {
  7583. if ( material.map.mapping instanceof THREE.UVMapping ) {
  7584. _uvs = element.uvs[ 0 ];
  7585. 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 );
  7586. }
  7587. } else if ( material.envMap !== null ) {
  7588. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  7589. var cameraMatrix = camera.matrixWorldInverse;
  7590. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  7591. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7592. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7593. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  7594. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7595. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7596. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  7597. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7598. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7599. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  7600. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  7601. }*/
  7602. } else {
  7603. _color.copy( material.color );
  7604. if ( material.vertexColors === THREE.FaceColors ) {
  7605. _color.r *= element.color.r;
  7606. _color.g *= element.color.g;
  7607. _color.b *= element.color.b;
  7608. }
  7609. material.wireframe === true
  7610. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7611. : fillPath( _color );
  7612. }
  7613. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7614. _near = camera.near;
  7615. _far = camera.far;
  7616. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7617. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7618. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7619. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7620. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7621. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7622. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7623. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7624. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7625. _color.r = normalToComponent( element.normalWorld.x );
  7626. _color.g = normalToComponent( element.normalWorld.y );
  7627. _color.b = normalToComponent( element.normalWorld.z );
  7628. material.wireframe === true
  7629. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7630. : fillPath( _color );
  7631. }
  7632. }
  7633. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  7634. _this.info.render.vertices += 4;
  7635. _this.info.render.faces ++;
  7636. setOpacity( material.opacity );
  7637. setBlending( material.blending );
  7638. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  7639. // Let renderFace3() handle this
  7640. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  7641. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  7642. return;
  7643. }
  7644. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7645. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7646. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7647. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  7648. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  7649. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  7650. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7651. _diffuseColor.copy( material.color );
  7652. _emissiveColor.copy( material.emissive );
  7653. if ( material.vertexColors === THREE.FaceColors ) {
  7654. _diffuseColor.r *= element.color.r;
  7655. _diffuseColor.g *= element.color.g;
  7656. _diffuseColor.b *= element.color.b;
  7657. }
  7658. if ( _enableLighting === true ) {
  7659. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  7660. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  7661. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  7662. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  7663. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7664. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7665. calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  7666. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  7667. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7668. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7669. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7670. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7671. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7672. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7673. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7674. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7675. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7676. _color4.r = _color4.r * _diffuseColor.r + _emissiveColor.r;
  7677. _color4.g = _color4.g * _diffuseColor.g + _emissiveColor.g;
  7678. _color4.b = _color4.b * _diffuseColor.b + _emissiveColor.b;
  7679. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7680. // TODO: UVs are incorrect, v4->v3?
  7681. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7682. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7683. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7684. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7685. } else {
  7686. _color.r = _ambientLight.r;
  7687. _color.g = _ambientLight.g;
  7688. _color.b = _ambientLight.b;
  7689. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7690. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7691. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7692. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7693. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7694. material.wireframe === true
  7695. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7696. : fillPath( _color );
  7697. }
  7698. } else {
  7699. _color.r = _diffuseColor.r + _emissiveColor.r;
  7700. _color.g = _diffuseColor.g + _emissiveColor.g;
  7701. _color.b = _diffuseColor.b + _emissiveColor.b;
  7702. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7703. material.wireframe === true
  7704. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7705. : fillPath( _color );
  7706. }
  7707. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  7708. _color.copy( material.color );
  7709. if ( material.vertexColors === THREE.FaceColors ) {
  7710. _color.r *= element.color.r;
  7711. _color.g *= element.color.g;
  7712. _color.b *= element.color.b;
  7713. }
  7714. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7715. material.wireframe === true
  7716. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7717. : fillPath( _color );
  7718. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7719. _color.r = normalToComponent( element.normalWorld.x );
  7720. _color.g = normalToComponent( element.normalWorld.y );
  7721. _color.b = normalToComponent( element.normalWorld.z );
  7722. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7723. material.wireframe === true
  7724. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7725. : fillPath( _color );
  7726. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7727. _near = camera.near;
  7728. _far = camera.far;
  7729. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7730. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7731. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  7732. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7733. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7734. // TODO: UVs are incorrect, v4->v3?
  7735. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7736. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7737. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7738. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7739. }
  7740. }
  7741. //
  7742. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  7743. _context.beginPath();
  7744. _context.moveTo( x0, y0 );
  7745. _context.lineTo( x1, y1 );
  7746. _context.lineTo( x2, y2 );
  7747. _context.closePath();
  7748. }
  7749. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  7750. _context.beginPath();
  7751. _context.moveTo( x0, y0 );
  7752. _context.lineTo( x1, y1 );
  7753. _context.lineTo( x2, y2 );
  7754. _context.lineTo( x3, y3 );
  7755. _context.closePath();
  7756. }
  7757. function strokePath( color, linewidth, linecap, linejoin ) {
  7758. setLineWidth( linewidth );
  7759. setLineCap( linecap );
  7760. setLineJoin( linejoin );
  7761. setStrokeStyle( color.getContextStyle() );
  7762. _context.stroke();
  7763. _bboxRect.inflate( linewidth * 2 );
  7764. }
  7765. function fillPath( color ) {
  7766. setFillStyle( color.getContextStyle() );
  7767. _context.fill();
  7768. }
  7769. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  7770. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  7771. if ( texture.needsUpdate === true ) {
  7772. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  7773. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  7774. _patterns[ texture.id ] = _context.createPattern(
  7775. texture.image, repeatX === true && repeatY === true
  7776. ? 'repeat'
  7777. : repeatX === true && repeatY === false
  7778. ? 'repeat-x'
  7779. : repeatX === false && repeatY === true
  7780. ? 'repeat-y'
  7781. : 'no-repeat'
  7782. );
  7783. texture.needsUpdate = false;
  7784. }
  7785. _patterns[ texture.id ] === undefined
  7786. ? setFillStyle( 'rgba(0,0,0,1)' )
  7787. : setFillStyle( _patterns[ texture.id ] );
  7788. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7789. var a, b, c, d, e, f, det, idet,
  7790. offsetX = texture.offset.x / texture.repeat.x,
  7791. offsetY = texture.offset.y / texture.repeat.y,
  7792. width = texture.image.width * texture.repeat.x,
  7793. height = texture.image.height * texture.repeat.y;
  7794. u0 = ( u0 + offsetX ) * width;
  7795. v0 = ( 1.0 - v0 + offsetY ) * height;
  7796. u1 = ( u1 + offsetX ) * width;
  7797. v1 = ( 1.0 - v1 + offsetY ) * height;
  7798. u2 = ( u2 + offsetX ) * width;
  7799. v2 = ( 1.0 - v2 + offsetY ) * height;
  7800. x1 -= x0; y1 -= y0;
  7801. x2 -= x0; y2 -= y0;
  7802. u1 -= u0; v1 -= v0;
  7803. u2 -= u0; v2 -= v0;
  7804. det = u1 * v2 - u2 * v1;
  7805. if ( det === 0 ) {
  7806. if ( _imagedatas[ texture.id ] === undefined ) {
  7807. var canvas = document.createElement( 'canvas' )
  7808. canvas.width = texture.image.width;
  7809. canvas.height = texture.image.height;
  7810. var context = canvas.getContext( '2d' );
  7811. context.drawImage( texture.image, 0, 0 );
  7812. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  7813. }
  7814. var data = _imagedatas[ texture.id ];
  7815. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  7816. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  7817. fillPath( _color );
  7818. return;
  7819. }
  7820. idet = 1 / det;
  7821. a = ( v2 * x1 - v1 * x2 ) * idet;
  7822. b = ( v2 * y1 - v1 * y2 ) * idet;
  7823. c = ( u1 * x2 - u2 * x1 ) * idet;
  7824. d = ( u1 * y2 - u2 * y1 ) * idet;
  7825. e = x0 - a * u0 - c * v0;
  7826. f = y0 - b * u0 - d * v0;
  7827. _context.save();
  7828. _context.transform( a, b, c, d, e, f );
  7829. _context.fill();
  7830. _context.restore();
  7831. }
  7832. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  7833. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7834. var a, b, c, d, e, f, det, idet,
  7835. width = image.width - 1,
  7836. height = image.height - 1;
  7837. u0 *= width; v0 *= height;
  7838. u1 *= width; v1 *= height;
  7839. u2 *= width; v2 *= height;
  7840. x1 -= x0; y1 -= y0;
  7841. x2 -= x0; y2 -= y0;
  7842. u1 -= u0; v1 -= v0;
  7843. u2 -= u0; v2 -= v0;
  7844. det = u1 * v2 - u2 * v1;
  7845. idet = 1 / det;
  7846. a = ( v2 * x1 - v1 * x2 ) * idet;
  7847. b = ( v2 * y1 - v1 * y2 ) * idet;
  7848. c = ( u1 * x2 - u2 * x1 ) * idet;
  7849. d = ( u1 * y2 - u2 * y1 ) * idet;
  7850. e = x0 - a * u0 - c * v0;
  7851. f = y0 - b * u0 - d * v0;
  7852. _context.save();
  7853. _context.transform( a, b, c, d, e, f );
  7854. _context.clip();
  7855. _context.drawImage( image, 0, 0 );
  7856. _context.restore();
  7857. }
  7858. function getGradientTexture( color1, color2, color3, color4 ) {
  7859. // http://mrdoob.com/blog/post/710
  7860. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  7861. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  7862. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  7863. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  7864. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  7865. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  7866. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  7867. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  7868. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  7869. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  7870. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  7871. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  7872. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  7873. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  7874. return _gradientMap;
  7875. }
  7876. function smoothstep( value, min, max ) {
  7877. var x = ( value - min ) / ( max - min );
  7878. return x * x * ( 3 - 2 * x );
  7879. }
  7880. function normalToComponent( normal ) {
  7881. var component = ( normal + 1 ) * 0.5;
  7882. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  7883. }
  7884. // Hide anti-alias gaps
  7885. function expand( v1, v2 ) {
  7886. var x = v2.x - v1.x, y = v2.y - v1.y,
  7887. det = x * x + y * y, idet;
  7888. if ( det === 0 ) return;
  7889. idet = 1 / Math.sqrt( det );
  7890. x *= idet; y *= idet;
  7891. v2.x += x; v2.y += y;
  7892. v1.x -= x; v1.y -= y;
  7893. }
  7894. };
  7895. // Context cached methods.
  7896. function setOpacity( value ) {
  7897. if ( _contextGlobalAlpha !== value ) {
  7898. _context.globalAlpha = value;
  7899. _contextGlobalAlpha = value;
  7900. }
  7901. }
  7902. function setBlending( value ) {
  7903. if ( _contextGlobalCompositeOperation !== value ) {
  7904. if ( value === THREE.NormalBlending ) {
  7905. _context.globalCompositeOperation = 'source-over';
  7906. } else if ( value === THREE.AdditiveBlending ) {
  7907. _context.globalCompositeOperation = 'lighter';
  7908. } else if ( value === THREE.SubtractiveBlending ) {
  7909. _context.globalCompositeOperation = 'darker';
  7910. }
  7911. _contextGlobalCompositeOperation = value;
  7912. }
  7913. }
  7914. function setLineWidth( value ) {
  7915. if ( _contextLineWidth !== value ) {
  7916. _context.lineWidth = value;
  7917. _contextLineWidth = value;
  7918. }
  7919. }
  7920. function setLineCap( value ) {
  7921. // "butt", "round", "square"
  7922. if ( _contextLineCap !== value ) {
  7923. _context.lineCap = value;
  7924. _contextLineCap = value;
  7925. }
  7926. }
  7927. function setLineJoin( value ) {
  7928. // "round", "bevel", "miter"
  7929. if ( _contextLineJoin !== value ) {
  7930. _context.lineJoin = value;
  7931. _contextLineJoin = value;
  7932. }
  7933. }
  7934. function setStrokeStyle( value ) {
  7935. if ( _contextStrokeStyle !== value ) {
  7936. _context.strokeStyle = value;
  7937. _contextStrokeStyle = value;
  7938. }
  7939. }
  7940. function setFillStyle( value ) {
  7941. if ( _contextFillStyle !== value ) {
  7942. _context.fillStyle = value;
  7943. _contextFillStyle = value;
  7944. }
  7945. }
  7946. };
  7947. /**
  7948. * @author alteredq / http://alteredqualia.com/
  7949. * @author mrdoob / http://mrdoob.com/
  7950. * @author mikael emtinger / http://gomo.se/
  7951. */
  7952. THREE.ShaderChunk = {
  7953. // FOG
  7954. fog_pars_fragment: [
  7955. "#ifdef USE_FOG",
  7956. "uniform vec3 fogColor;",
  7957. "#ifdef FOG_EXP2",
  7958. "uniform float fogDensity;",
  7959. "#else",
  7960. "uniform float fogNear;",
  7961. "uniform float fogFar;",
  7962. "#endif",
  7963. "#endif"
  7964. ].join("\n"),
  7965. fog_fragment: [
  7966. "#ifdef USE_FOG",
  7967. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  7968. "#ifdef FOG_EXP2",
  7969. "const float LOG2 = 1.442695;",
  7970. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  7971. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  7972. "#else",
  7973. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  7974. "#endif",
  7975. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  7976. "#endif"
  7977. ].join("\n"),
  7978. // ENVIRONMENT MAP
  7979. envmap_pars_fragment: [
  7980. "#ifdef USE_ENVMAP",
  7981. "uniform float reflectivity;",
  7982. "uniform samplerCube envMap;",
  7983. "uniform float flipEnvMap;",
  7984. "uniform int combine;",
  7985. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  7986. "uniform bool useRefract;",
  7987. "uniform float refractionRatio;",
  7988. "#else",
  7989. "varying vec3 vReflect;",
  7990. "#endif",
  7991. "#endif"
  7992. ].join("\n"),
  7993. envmap_fragment: [
  7994. "#ifdef USE_ENVMAP",
  7995. "vec3 reflectVec;",
  7996. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  7997. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  7998. "if ( useRefract ) {",
  7999. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8000. "} else { ",
  8001. "reflectVec = reflect( cameraToVertex, normal );",
  8002. "}",
  8003. "#else",
  8004. "reflectVec = vReflect;",
  8005. "#endif",
  8006. "#ifdef DOUBLE_SIDED",
  8007. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8008. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8009. "#else",
  8010. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8011. "#endif",
  8012. "#ifdef GAMMA_INPUT",
  8013. "cubeColor.xyz *= cubeColor.xyz;",
  8014. "#endif",
  8015. "if ( combine == 1 ) {",
  8016. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8017. "} else {",
  8018. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8019. "}",
  8020. "#endif"
  8021. ].join("\n"),
  8022. envmap_pars_vertex: [
  8023. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8024. "varying vec3 vReflect;",
  8025. "uniform float refractionRatio;",
  8026. "uniform bool useRefract;",
  8027. "#endif"
  8028. ].join("\n"),
  8029. worldpos_vertex : [
  8030. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8031. "#ifdef USE_SKINNING",
  8032. "vec4 mPosition = modelMatrix * skinned;",
  8033. "#endif",
  8034. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8035. "vec4 mPosition = modelMatrix * vec4( morphed, 1.0 );",
  8036. "#endif",
  8037. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8038. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  8039. "#endif",
  8040. "#endif"
  8041. ].join("\n"),
  8042. envmap_vertex : [
  8043. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8044. "vec3 nWorld = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8045. "if ( useRefract ) {",
  8046. "vReflect = refract( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ), refractionRatio );",
  8047. "} else {",
  8048. "vReflect = reflect( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ) );",
  8049. "}",
  8050. "#endif"
  8051. ].join("\n"),
  8052. // COLOR MAP (particles)
  8053. map_particle_pars_fragment: [
  8054. "#ifdef USE_MAP",
  8055. "uniform sampler2D map;",
  8056. "#endif"
  8057. ].join("\n"),
  8058. map_particle_fragment: [
  8059. "#ifdef USE_MAP",
  8060. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8061. "#endif"
  8062. ].join("\n"),
  8063. // COLOR MAP (triangles)
  8064. map_pars_vertex: [
  8065. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8066. "varying vec2 vUv;",
  8067. "uniform vec4 offsetRepeat;",
  8068. "#endif"
  8069. ].join("\n"),
  8070. map_pars_fragment: [
  8071. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8072. "varying vec2 vUv;",
  8073. "#endif",
  8074. "#ifdef USE_MAP",
  8075. "uniform sampler2D map;",
  8076. "#endif",
  8077. ].join("\n"),
  8078. map_vertex: [
  8079. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8080. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8081. "#endif"
  8082. ].join("\n"),
  8083. map_fragment: [
  8084. "#ifdef USE_MAP",
  8085. "#ifdef GAMMA_INPUT",
  8086. "vec4 texelColor = texture2D( map, vUv );",
  8087. "texelColor.xyz *= texelColor.xyz;",
  8088. "gl_FragColor = gl_FragColor * texelColor;",
  8089. "#else",
  8090. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  8091. "#endif",
  8092. "#endif"
  8093. ].join("\n"),
  8094. // LIGHT MAP
  8095. lightmap_pars_fragment: [
  8096. "#ifdef USE_LIGHTMAP",
  8097. "varying vec2 vUv2;",
  8098. "uniform sampler2D lightMap;",
  8099. "#endif"
  8100. ].join("\n"),
  8101. lightmap_pars_vertex: [
  8102. "#ifdef USE_LIGHTMAP",
  8103. "varying vec2 vUv2;",
  8104. "#endif"
  8105. ].join("\n"),
  8106. lightmap_fragment: [
  8107. "#ifdef USE_LIGHTMAP",
  8108. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8109. "#endif"
  8110. ].join("\n"),
  8111. lightmap_vertex: [
  8112. "#ifdef USE_LIGHTMAP",
  8113. "vUv2 = uv2;",
  8114. "#endif"
  8115. ].join("\n"),
  8116. // BUMP MAP
  8117. bumpmap_pars_fragment: [
  8118. "#ifdef USE_BUMPMAP",
  8119. "uniform sampler2D bumpMap;",
  8120. "uniform float bumpScale;",
  8121. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8122. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8123. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8124. "vec2 dHdxy_fwd() {",
  8125. "vec2 dSTdx = dFdx( vUv );",
  8126. "vec2 dSTdy = dFdy( vUv );",
  8127. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8128. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8129. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8130. "return vec2( dBx, dBy );",
  8131. "}",
  8132. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8133. "vec3 vSigmaX = dFdx( surf_pos );",
  8134. "vec3 vSigmaY = dFdy( surf_pos );",
  8135. "vec3 vN = surf_norm;", // normalized
  8136. "vec3 R1 = cross( vSigmaY, vN );",
  8137. "vec3 R2 = cross( vN, vSigmaX );",
  8138. "float fDet = dot( vSigmaX, R1 );",
  8139. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8140. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8141. "}",
  8142. "#endif"
  8143. ].join("\n"),
  8144. // NORMAL MAP
  8145. normalmap_pars_fragment: [
  8146. "#ifdef USE_NORMALMAP",
  8147. "uniform sampler2D normalMap;",
  8148. "uniform vec2 normalScale;",
  8149. // Per-Pixel Tangent Space Normal Mapping
  8150. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8151. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8152. "vec3 q0 = dFdx( eye_pos.xyz );",
  8153. "vec3 q1 = dFdy( eye_pos.xyz );",
  8154. "vec2 st0 = dFdx( vUv.st );",
  8155. "vec2 st1 = dFdy( vUv.st );",
  8156. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8157. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8158. "vec3 N = normalize( surf_norm );",
  8159. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8160. "mapN.xy = normalScale * mapN.xy;",
  8161. "mat3 tsn = mat3( S, T, N );",
  8162. "return normalize( tsn * mapN );",
  8163. "}",
  8164. "#endif"
  8165. ].join("\n"),
  8166. // SPECULAR MAP
  8167. specularmap_pars_fragment: [
  8168. "#ifdef USE_SPECULARMAP",
  8169. "uniform sampler2D specularMap;",
  8170. "#endif"
  8171. ].join("\n"),
  8172. specularmap_fragment: [
  8173. "float specularStrength;",
  8174. "#ifdef USE_SPECULARMAP",
  8175. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8176. "specularStrength = texelSpecular.r;",
  8177. "#else",
  8178. "specularStrength = 1.0;",
  8179. "#endif"
  8180. ].join("\n"),
  8181. // LIGHTS LAMBERT
  8182. lights_lambert_pars_vertex: [
  8183. "uniform vec3 ambient;",
  8184. "uniform vec3 diffuse;",
  8185. "uniform vec3 emissive;",
  8186. "uniform vec3 ambientLightColor;",
  8187. "#if MAX_DIR_LIGHTS > 0",
  8188. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8189. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8190. "#endif",
  8191. "#if MAX_HEMI_LIGHTS > 0",
  8192. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8193. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8194. "uniform vec3 hemisphereLightPosition[ MAX_HEMI_LIGHTS ];",
  8195. "#endif",
  8196. "#if MAX_POINT_LIGHTS > 0",
  8197. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8198. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8199. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8200. "#endif",
  8201. "#if MAX_SPOT_LIGHTS > 0",
  8202. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8203. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8204. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8205. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8206. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  8207. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8208. "#endif",
  8209. "#ifdef WRAP_AROUND",
  8210. "uniform vec3 wrapRGB;",
  8211. "#endif"
  8212. ].join("\n"),
  8213. lights_lambert_vertex: [
  8214. "vLightFront = vec3( 0.0 );",
  8215. "#ifdef DOUBLE_SIDED",
  8216. "vLightBack = vec3( 0.0 );",
  8217. "#endif",
  8218. "transformedNormal = normalize( transformedNormal );",
  8219. "#if MAX_DIR_LIGHTS > 0",
  8220. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8221. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8222. "vec3 dirVector = normalize( lDirection.xyz );",
  8223. "float dotProduct = dot( transformedNormal, dirVector );",
  8224. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8225. "#ifdef DOUBLE_SIDED",
  8226. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8227. "#ifdef WRAP_AROUND",
  8228. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8229. "#endif",
  8230. "#endif",
  8231. "#ifdef WRAP_AROUND",
  8232. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8233. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  8234. "#ifdef DOUBLE_SIDED",
  8235. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  8236. "#endif",
  8237. "#endif",
  8238. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  8239. "#ifdef DOUBLE_SIDED",
  8240. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  8241. "#endif",
  8242. "}",
  8243. "#endif",
  8244. "#if MAX_POINT_LIGHTS > 0",
  8245. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8246. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8247. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8248. "float lDistance = 1.0;",
  8249. "if ( pointLightDistance[ i ] > 0.0 )",
  8250. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8251. "lVector = normalize( lVector );",
  8252. "float dotProduct = dot( transformedNormal, lVector );",
  8253. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8254. "#ifdef DOUBLE_SIDED",
  8255. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8256. "#ifdef WRAP_AROUND",
  8257. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8258. "#endif",
  8259. "#endif",
  8260. "#ifdef WRAP_AROUND",
  8261. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8262. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  8263. "#ifdef DOUBLE_SIDED",
  8264. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  8265. "#endif",
  8266. "#endif",
  8267. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  8268. "#ifdef DOUBLE_SIDED",
  8269. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  8270. "#endif",
  8271. "}",
  8272. "#endif",
  8273. "#if MAX_SPOT_LIGHTS > 0",
  8274. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8275. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8276. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8277. "lVector = normalize( lVector );",
  8278. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - mPosition.xyz ) );",
  8279. "if ( spotEffect > spotLightAngle[ i ] ) {",
  8280. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  8281. "float lDistance = 1.0;",
  8282. "if ( spotLightDistance[ i ] > 0.0 )",
  8283. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8284. "float dotProduct = dot( transformedNormal, lVector );",
  8285. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8286. "#ifdef DOUBLE_SIDED",
  8287. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8288. "#ifdef WRAP_AROUND",
  8289. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8290. "#endif",
  8291. "#endif",
  8292. "#ifdef WRAP_AROUND",
  8293. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8294. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  8295. "#ifdef DOUBLE_SIDED",
  8296. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  8297. "#endif",
  8298. "#endif",
  8299. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  8300. "#ifdef DOUBLE_SIDED",
  8301. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  8302. "#endif",
  8303. "}",
  8304. "}",
  8305. "#endif",
  8306. "#if MAX_HEMI_LIGHTS > 0",
  8307. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8308. "vec4 lPosition = viewMatrix * vec4( hemisphereLightPosition[ i ], 1.0 );",
  8309. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8310. "lVector = normalize( lVector );",
  8311. "float dotProduct = dot( transformedNormal, lVector );",
  8312. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8313. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  8314. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8315. "#ifdef DOUBLE_SIDED",
  8316. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  8317. "#endif",
  8318. "}",
  8319. "#endif",
  8320. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  8321. "#ifdef DOUBLE_SIDED",
  8322. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  8323. "#endif"
  8324. ].join("\n"),
  8325. // LIGHTS PHONG
  8326. lights_phong_pars_vertex: [
  8327. "#ifndef PHONG_PER_PIXEL",
  8328. "#if MAX_POINT_LIGHTS > 0",
  8329. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8330. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8331. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8332. "#endif",
  8333. "#if MAX_SPOT_LIGHTS > 0",
  8334. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8335. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8336. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8337. "#endif",
  8338. "#endif",
  8339. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8340. "varying vec3 vWorldPosition;",
  8341. "#endif"
  8342. ].join("\n"),
  8343. lights_phong_vertex: [
  8344. "#ifndef PHONG_PER_PIXEL",
  8345. "#if MAX_POINT_LIGHTS > 0",
  8346. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8347. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8348. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8349. "float lDistance = 1.0;",
  8350. "if ( pointLightDistance[ i ] > 0.0 )",
  8351. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8352. "vPointLight[ i ] = vec4( lVector, lDistance );",
  8353. "}",
  8354. "#endif",
  8355. "#if MAX_SPOT_LIGHTS > 0",
  8356. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8357. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8358. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8359. "float lDistance = 1.0;",
  8360. "if ( spotLightDistance[ i ] > 0.0 )",
  8361. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8362. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  8363. "}",
  8364. "#endif",
  8365. "#endif",
  8366. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8367. "vWorldPosition = mPosition.xyz;",
  8368. "#endif"
  8369. ].join("\n"),
  8370. lights_phong_pars_fragment: [
  8371. "uniform vec3 ambientLightColor;",
  8372. "#if MAX_DIR_LIGHTS > 0",
  8373. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8374. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8375. "#endif",
  8376. "#if MAX_HEMI_LIGHTS > 0",
  8377. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8378. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8379. "uniform vec3 hemisphereLightPosition[ MAX_HEMI_LIGHTS ];",
  8380. "#endif",
  8381. "#if MAX_POINT_LIGHTS > 0",
  8382. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8383. "#ifdef PHONG_PER_PIXEL",
  8384. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8385. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8386. "#else",
  8387. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8388. "#endif",
  8389. "#endif",
  8390. "#if MAX_SPOT_LIGHTS > 0",
  8391. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8392. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8393. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8394. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  8395. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8396. "#ifdef PHONG_PER_PIXEL",
  8397. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8398. "#else",
  8399. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8400. "#endif",
  8401. "#endif",
  8402. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8403. "varying vec3 vWorldPosition;",
  8404. "#endif",
  8405. "#ifdef WRAP_AROUND",
  8406. "uniform vec3 wrapRGB;",
  8407. "#endif",
  8408. "varying vec3 vViewPosition;",
  8409. "varying vec3 vNormal;"
  8410. ].join("\n"),
  8411. lights_phong_fragment: [
  8412. "vec3 normal = normalize( vNormal );",
  8413. "vec3 viewPosition = normalize( vViewPosition );",
  8414. "#ifdef DOUBLE_SIDED",
  8415. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8416. "#endif",
  8417. "#ifdef USE_NORMALMAP",
  8418. "normal = perturbNormal2Arb( -viewPosition, normal );",
  8419. "#elif defined( USE_BUMPMAP )",
  8420. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  8421. "#endif",
  8422. "#if MAX_POINT_LIGHTS > 0",
  8423. "vec3 pointDiffuse = vec3( 0.0 );",
  8424. "vec3 pointSpecular = vec3( 0.0 );",
  8425. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8426. "#ifdef PHONG_PER_PIXEL",
  8427. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8428. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8429. "float lDistance = 1.0;",
  8430. "if ( pointLightDistance[ i ] > 0.0 )",
  8431. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8432. "lVector = normalize( lVector );",
  8433. "#else",
  8434. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  8435. "float lDistance = vPointLight[ i ].w;",
  8436. "#endif",
  8437. // diffuse
  8438. "float dotProduct = dot( normal, lVector );",
  8439. "#ifdef WRAP_AROUND",
  8440. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  8441. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8442. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  8443. "#else",
  8444. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  8445. "#endif",
  8446. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  8447. // specular
  8448. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  8449. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  8450. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  8451. "#ifdef PHYSICALLY_BASED_SHADING",
  8452. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8453. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8454. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  8455. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  8456. "#else",
  8457. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  8458. "#endif",
  8459. "}",
  8460. "#endif",
  8461. "#if MAX_SPOT_LIGHTS > 0",
  8462. "vec3 spotDiffuse = vec3( 0.0 );",
  8463. "vec3 spotSpecular = vec3( 0.0 );",
  8464. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8465. "#ifdef PHONG_PER_PIXEL",
  8466. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8467. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8468. "float lDistance = 1.0;",
  8469. "if ( spotLightDistance[ i ] > 0.0 )",
  8470. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8471. "lVector = normalize( lVector );",
  8472. "#else",
  8473. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  8474. "float lDistance = vSpotLight[ i ].w;",
  8475. "#endif",
  8476. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  8477. "if ( spotEffect > spotLightAngle[ i ] ) {",
  8478. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  8479. // diffuse
  8480. "float dotProduct = dot( normal, lVector );",
  8481. "#ifdef WRAP_AROUND",
  8482. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  8483. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8484. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  8485. "#else",
  8486. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  8487. "#endif",
  8488. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  8489. // specular
  8490. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  8491. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  8492. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  8493. "#ifdef PHYSICALLY_BASED_SHADING",
  8494. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8495. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8496. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  8497. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  8498. "#else",
  8499. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  8500. "#endif",
  8501. "}",
  8502. "}",
  8503. "#endif",
  8504. "#if MAX_DIR_LIGHTS > 0",
  8505. "vec3 dirDiffuse = vec3( 0.0 );",
  8506. "vec3 dirSpecular = vec3( 0.0 );" ,
  8507. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8508. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8509. "vec3 dirVector = normalize( lDirection.xyz );",
  8510. // diffuse
  8511. "float dotProduct = dot( normal, dirVector );",
  8512. "#ifdef WRAP_AROUND",
  8513. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  8514. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8515. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  8516. "#else",
  8517. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  8518. "#endif",
  8519. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  8520. // specular
  8521. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  8522. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  8523. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  8524. "#ifdef PHYSICALLY_BASED_SHADING",
  8525. /*
  8526. // fresnel term from skin shader
  8527. "const float F0 = 0.128;",
  8528. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  8529. "float exponential = pow( base, 5.0 );",
  8530. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  8531. */
  8532. /*
  8533. // fresnel term from fresnel shader
  8534. "const float mFresnelBias = 0.08;",
  8535. "const float mFresnelScale = 0.3;",
  8536. "const float mFresnelPower = 5.0;",
  8537. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  8538. */
  8539. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8540. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8541. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  8542. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  8543. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  8544. "#else",
  8545. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  8546. "#endif",
  8547. "}",
  8548. "#endif",
  8549. "#if MAX_HEMI_LIGHTS > 0",
  8550. "vec3 hemiDiffuse = vec3( 0.0 );",
  8551. "vec3 hemiSpecular = vec3( 0.0 );" ,
  8552. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8553. "vec4 lPosition = viewMatrix * vec4( hemisphereLightPosition[ i ], 1.0 );",
  8554. "vec3 lVector = normalize( lPosition.xyz + vViewPosition.xyz );",
  8555. // diffuse
  8556. "float dotProduct = dot( normal, lVector );",
  8557. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8558. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8559. "hemiDiffuse += diffuse * hemiColor;",
  8560. // specular (sky light)
  8561. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  8562. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  8563. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  8564. // specular (ground light)
  8565. "vec3 lVectorGround = normalize( -lPosition.xyz + vViewPosition.xyz );",
  8566. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  8567. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  8568. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  8569. "#ifdef PHYSICALLY_BASED_SHADING",
  8570. "float dotProductGround = dot( normal, lVectorGround );",
  8571. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8572. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8573. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  8574. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  8575. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  8576. "#else",
  8577. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  8578. "#endif",
  8579. "}",
  8580. "#endif",
  8581. "vec3 totalDiffuse = vec3( 0.0 );",
  8582. "vec3 totalSpecular = vec3( 0.0 );",
  8583. "#if MAX_DIR_LIGHTS > 0",
  8584. "totalDiffuse += dirDiffuse;",
  8585. "totalSpecular += dirSpecular;",
  8586. "#endif",
  8587. "#if MAX_HEMI_LIGHTS > 0",
  8588. "totalDiffuse += hemiDiffuse;",
  8589. "totalSpecular += hemiSpecular;",
  8590. "#endif",
  8591. "#if MAX_POINT_LIGHTS > 0",
  8592. "totalDiffuse += pointDiffuse;",
  8593. "totalSpecular += pointSpecular;",
  8594. "#endif",
  8595. "#if MAX_SPOT_LIGHTS > 0",
  8596. "totalDiffuse += spotDiffuse;",
  8597. "totalSpecular += spotSpecular;",
  8598. "#endif",
  8599. "#ifdef METAL",
  8600. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  8601. "#else",
  8602. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  8603. "#endif"
  8604. ].join("\n"),
  8605. // VERTEX COLORS
  8606. color_pars_fragment: [
  8607. "#ifdef USE_COLOR",
  8608. "varying vec3 vColor;",
  8609. "#endif"
  8610. ].join("\n"),
  8611. color_fragment: [
  8612. "#ifdef USE_COLOR",
  8613. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  8614. "#endif"
  8615. ].join("\n"),
  8616. color_pars_vertex: [
  8617. "#ifdef USE_COLOR",
  8618. "varying vec3 vColor;",
  8619. "#endif"
  8620. ].join("\n"),
  8621. color_vertex: [
  8622. "#ifdef USE_COLOR",
  8623. "#ifdef GAMMA_INPUT",
  8624. "vColor = color * color;",
  8625. "#else",
  8626. "vColor = color;",
  8627. "#endif",
  8628. "#endif"
  8629. ].join("\n"),
  8630. // SKINNING
  8631. skinning_pars_vertex: [
  8632. "#ifdef USE_SKINNING",
  8633. "#ifdef BONE_TEXTURE",
  8634. "uniform sampler2D boneTexture;",
  8635. "mat4 getBoneMatrix( const in float i ) {",
  8636. "float j = i * 4.0;",
  8637. "float x = mod( j, N_BONE_PIXEL_X );",
  8638. "float y = floor( j / N_BONE_PIXEL_X );",
  8639. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  8640. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  8641. "y = dy * ( y + 0.5 );",
  8642. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  8643. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  8644. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  8645. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  8646. "mat4 bone = mat4( v1, v2, v3, v4 );",
  8647. "return bone;",
  8648. "}",
  8649. "#else",
  8650. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  8651. "mat4 getBoneMatrix( const in float i ) {",
  8652. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  8653. "return bone;",
  8654. "}",
  8655. "#endif",
  8656. "#endif"
  8657. ].join("\n"),
  8658. skinbase_vertex: [
  8659. "#ifdef USE_SKINNING",
  8660. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  8661. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  8662. "#endif"
  8663. ].join("\n"),
  8664. skinning_vertex: [
  8665. "#ifdef USE_SKINNING",
  8666. "#ifdef USE_MORPHTARGETS",
  8667. "vec4 skinVertex = vec4( morphed, 1.0 );",
  8668. "#else",
  8669. "vec4 skinVertex = vec4( position, 1.0 );",
  8670. "#endif",
  8671. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  8672. "skinned += boneMatY * skinVertex * skinWeight.y;",
  8673. "#endif"
  8674. ].join("\n"),
  8675. // MORPHING
  8676. morphtarget_pars_vertex: [
  8677. "#ifdef USE_MORPHTARGETS",
  8678. "#ifndef USE_MORPHNORMALS",
  8679. "uniform float morphTargetInfluences[ 8 ];",
  8680. "#else",
  8681. "uniform float morphTargetInfluences[ 4 ];",
  8682. "#endif",
  8683. "#endif"
  8684. ].join("\n"),
  8685. morphtarget_vertex: [
  8686. "#ifdef USE_MORPHTARGETS",
  8687. "vec3 morphed = vec3( 0.0 );",
  8688. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  8689. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  8690. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  8691. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  8692. "#ifndef USE_MORPHNORMALS",
  8693. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  8694. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  8695. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  8696. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  8697. "#endif",
  8698. "morphed += position;",
  8699. "#endif"
  8700. ].join("\n"),
  8701. default_vertex : [
  8702. "vec4 mvPosition;",
  8703. "#ifdef USE_SKINNING",
  8704. "mvPosition = modelViewMatrix * skinned;",
  8705. "#endif",
  8706. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  8707. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  8708. "#endif",
  8709. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  8710. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8711. "#endif",
  8712. "gl_Position = projectionMatrix * mvPosition;",
  8713. ].join("\n"),
  8714. morphnormal_vertex: [
  8715. "#ifdef USE_MORPHNORMALS",
  8716. "vec3 morphedNormal = vec3( 0.0 );",
  8717. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  8718. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  8719. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  8720. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  8721. "morphedNormal += normal;",
  8722. "#endif"
  8723. ].join("\n"),
  8724. skinnormal_vertex: [
  8725. "#ifdef USE_SKINNING",
  8726. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  8727. "skinMatrix += skinWeight.y * boneMatY;",
  8728. "#ifdef USE_MORPHNORMALS",
  8729. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  8730. "#else",
  8731. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  8732. "#endif",
  8733. "#endif"
  8734. ].join("\n"),
  8735. defaultnormal_vertex: [
  8736. "vec3 objectNormal;",
  8737. "#ifdef USE_SKINNING",
  8738. "objectNormal = skinnedNormal.xyz;",
  8739. "#endif",
  8740. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  8741. "objectNormal = morphedNormal;",
  8742. "#endif",
  8743. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  8744. "objectNormal = normal;",
  8745. "#endif",
  8746. "#ifdef FLIP_SIDED",
  8747. "objectNormal = -objectNormal;",
  8748. "#endif",
  8749. "vec3 transformedNormal = normalMatrix * objectNormal;",
  8750. ].join("\n"),
  8751. // SHADOW MAP
  8752. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  8753. // http://spidergl.org/example.php?id=6
  8754. // http://fabiensanglard.net/shadowmapping
  8755. shadowmap_pars_fragment: [
  8756. "#ifdef USE_SHADOWMAP",
  8757. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  8758. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  8759. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  8760. "uniform float shadowBias[ MAX_SHADOWS ];",
  8761. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8762. "float unpackDepth( const in vec4 rgba_depth ) {",
  8763. "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 );",
  8764. "float depth = dot( rgba_depth, bit_shift );",
  8765. "return depth;",
  8766. "}",
  8767. "#endif"
  8768. ].join("\n"),
  8769. shadowmap_fragment: [
  8770. "#ifdef USE_SHADOWMAP",
  8771. "#ifdef SHADOWMAP_DEBUG",
  8772. "vec3 frustumColors[3];",
  8773. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  8774. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  8775. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  8776. "#endif",
  8777. "#ifdef SHADOWMAP_CASCADE",
  8778. "int inFrustumCount = 0;",
  8779. "#endif",
  8780. "float fDepth;",
  8781. "vec3 shadowColor = vec3( 1.0 );",
  8782. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8783. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  8784. // "if ( something && something )" breaks ATI OpenGL shader compiler
  8785. // "if ( all( something, something ) )" using this instead
  8786. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  8787. "bool inFrustum = all( inFrustumVec );",
  8788. // don't shadow pixels outside of light frustum
  8789. // use just first frustum (for cascades)
  8790. // don't shadow pixels behind far plane of light frustum
  8791. "#ifdef SHADOWMAP_CASCADE",
  8792. "inFrustumCount += int( inFrustum );",
  8793. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  8794. "#else",
  8795. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  8796. "#endif",
  8797. "bool frustumTest = all( frustumTestVec );",
  8798. "if ( frustumTest ) {",
  8799. "shadowCoord.z += shadowBias[ i ];",
  8800. "#ifdef SHADOWMAP_SOFT",
  8801. // Percentage-close filtering
  8802. // (9 pixel kernel)
  8803. // http://fabiensanglard.net/shadowmappingPCF/
  8804. "float shadow = 0.0;",
  8805. /*
  8806. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  8807. // must enroll loop manually
  8808. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  8809. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  8810. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  8811. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  8812. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  8813. "float fDepth = unpackDepth( rgbaDepth );",
  8814. "if ( fDepth < shadowCoord.z )",
  8815. "shadow += 1.0;",
  8816. "}",
  8817. "shadow /= 9.0;",
  8818. */
  8819. "const float shadowDelta = 1.0 / 9.0;",
  8820. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  8821. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  8822. "float dx0 = -1.25 * xPixelOffset;",
  8823. "float dy0 = -1.25 * yPixelOffset;",
  8824. "float dx1 = 1.25 * xPixelOffset;",
  8825. "float dy1 = 1.25 * yPixelOffset;",
  8826. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  8827. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8828. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  8829. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8830. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  8831. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8832. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  8833. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8834. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  8835. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8836. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  8837. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8838. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  8839. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8840. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  8841. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8842. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  8843. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8844. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  8845. "#else",
  8846. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  8847. "float fDepth = unpackDepth( rgbaDepth );",
  8848. "if ( fDepth < shadowCoord.z )",
  8849. // spot with multiple shadows is darker
  8850. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  8851. // spot with multiple shadows has the same color as single shadow spot
  8852. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  8853. "#endif",
  8854. "}",
  8855. "#ifdef SHADOWMAP_DEBUG",
  8856. "#ifdef SHADOWMAP_CASCADE",
  8857. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  8858. "#else",
  8859. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  8860. "#endif",
  8861. "#endif",
  8862. "}",
  8863. "#ifdef GAMMA_OUTPUT",
  8864. "shadowColor *= shadowColor;",
  8865. "#endif",
  8866. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  8867. "#endif"
  8868. ].join("\n"),
  8869. shadowmap_pars_vertex: [
  8870. "#ifdef USE_SHADOWMAP",
  8871. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8872. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  8873. "#endif"
  8874. ].join("\n"),
  8875. shadowmap_vertex: [
  8876. "#ifdef USE_SHADOWMAP",
  8877. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8878. "vShadowCoord[ i ] = shadowMatrix[ i ] * mPosition;",
  8879. "}",
  8880. "#endif"
  8881. ].join("\n"),
  8882. // ALPHATEST
  8883. alphatest_fragment: [
  8884. "#ifdef ALPHATEST",
  8885. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  8886. "#endif"
  8887. ].join("\n"),
  8888. // LINEAR SPACE
  8889. linear_to_gamma_fragment: [
  8890. "#ifdef GAMMA_OUTPUT",
  8891. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  8892. "#endif"
  8893. ].join("\n"),
  8894. };
  8895. THREE.UniformsUtils = {
  8896. merge: function ( uniforms ) {
  8897. var u, p, tmp, merged = {};
  8898. for ( u = 0; u < uniforms.length; u ++ ) {
  8899. tmp = this.clone( uniforms[ u ] );
  8900. for ( p in tmp ) {
  8901. merged[ p ] = tmp[ p ];
  8902. }
  8903. }
  8904. return merged;
  8905. },
  8906. clone: function ( uniforms_src ) {
  8907. var u, p, parameter, parameter_src, uniforms_dst = {};
  8908. for ( u in uniforms_src ) {
  8909. uniforms_dst[ u ] = {};
  8910. for ( p in uniforms_src[ u ] ) {
  8911. parameter_src = uniforms_src[ u ][ p ];
  8912. if ( parameter_src instanceof THREE.Color ||
  8913. parameter_src instanceof THREE.Vector2 ||
  8914. parameter_src instanceof THREE.Vector3 ||
  8915. parameter_src instanceof THREE.Vector4 ||
  8916. parameter_src instanceof THREE.Matrix4 ||
  8917. parameter_src instanceof THREE.Texture ) {
  8918. uniforms_dst[ u ][ p ] = parameter_src.clone();
  8919. } else if ( parameter_src instanceof Array ) {
  8920. uniforms_dst[ u ][ p ] = parameter_src.slice();
  8921. } else {
  8922. uniforms_dst[ u ][ p ] = parameter_src;
  8923. }
  8924. }
  8925. }
  8926. return uniforms_dst;
  8927. }
  8928. };
  8929. THREE.UniformsLib = {
  8930. common: {
  8931. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  8932. "opacity" : { type: "f", value: 1.0 },
  8933. "map" : { type: "t", value: null },
  8934. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  8935. "lightMap" : { type: "t", value: null },
  8936. "specularMap" : { type: "t", value: null },
  8937. "envMap" : { type: "t", value: null },
  8938. "flipEnvMap" : { type: "f", value: -1 },
  8939. "useRefract" : { type: "i", value: 0 },
  8940. "reflectivity" : { type: "f", value: 1.0 },
  8941. "refractionRatio" : { type: "f", value: 0.98 },
  8942. "combine" : { type: "i", value: 0 },
  8943. "morphTargetInfluences" : { type: "f", value: 0 }
  8944. },
  8945. bump: {
  8946. "bumpMap" : { type: "t", value: null },
  8947. "bumpScale" : { type: "f", value: 1 }
  8948. },
  8949. normalmap: {
  8950. "normalMap" : { type: "t", value: null },
  8951. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  8952. },
  8953. fog : {
  8954. "fogDensity" : { type: "f", value: 0.00025 },
  8955. "fogNear" : { type: "f", value: 1 },
  8956. "fogFar" : { type: "f", value: 2000 },
  8957. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  8958. },
  8959. lights: {
  8960. "ambientLightColor" : { type: "fv", value: [] },
  8961. "directionalLightDirection" : { type: "fv", value: [] },
  8962. "directionalLightColor" : { type: "fv", value: [] },
  8963. "hemisphereLightPosition" : { type: "fv", value: [] },
  8964. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  8965. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  8966. "pointLightColor" : { type: "fv", value: [] },
  8967. "pointLightPosition" : { type: "fv", value: [] },
  8968. "pointLightDistance" : { type: "fv1", value: [] },
  8969. "spotLightColor" : { type: "fv", value: [] },
  8970. "spotLightPosition" : { type: "fv", value: [] },
  8971. "spotLightDirection" : { type: "fv", value: [] },
  8972. "spotLightDistance" : { type: "fv1", value: [] },
  8973. "spotLightAngle" : { type: "fv1", value: [] },
  8974. "spotLightExponent" : { type: "fv1", value: [] }
  8975. },
  8976. particle: {
  8977. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  8978. "opacity" : { type: "f", value: 1.0 },
  8979. "size" : { type: "f", value: 1.0 },
  8980. "scale" : { type: "f", value: 1.0 },
  8981. "map" : { type: "t", value: null },
  8982. "fogDensity" : { type: "f", value: 0.00025 },
  8983. "fogNear" : { type: "f", value: 1 },
  8984. "fogFar" : { type: "f", value: 2000 },
  8985. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  8986. },
  8987. shadowmap: {
  8988. "shadowMap": { type: "tv", value: [] },
  8989. "shadowMapSize": { type: "v2v", value: [] },
  8990. "shadowBias" : { type: "fv1", value: [] },
  8991. "shadowDarkness": { type: "fv1", value: [] },
  8992. "shadowMatrix" : { type: "m4v", value: [] },
  8993. }
  8994. };
  8995. THREE.ShaderLib = {
  8996. 'depth': {
  8997. uniforms: {
  8998. "mNear": { type: "f", value: 1.0 },
  8999. "mFar" : { type: "f", value: 2000.0 },
  9000. "opacity" : { type: "f", value: 1.0 }
  9001. },
  9002. vertexShader: [
  9003. "void main() {",
  9004. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  9005. "}"
  9006. ].join("\n"),
  9007. fragmentShader: [
  9008. "uniform float mNear;",
  9009. "uniform float mFar;",
  9010. "uniform float opacity;",
  9011. "void main() {",
  9012. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9013. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  9014. "gl_FragColor = vec4( vec3( color ), opacity );",
  9015. "}"
  9016. ].join("\n")
  9017. },
  9018. 'normal': {
  9019. uniforms: {
  9020. "opacity" : { type: "f", value: 1.0 }
  9021. },
  9022. vertexShader: [
  9023. "varying vec3 vNormal;",
  9024. "void main() {",
  9025. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9026. "vNormal = normalMatrix * normal;",
  9027. "gl_Position = projectionMatrix * mvPosition;",
  9028. "}"
  9029. ].join("\n"),
  9030. fragmentShader: [
  9031. "uniform float opacity;",
  9032. "varying vec3 vNormal;",
  9033. "void main() {",
  9034. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  9035. "}"
  9036. ].join("\n")
  9037. },
  9038. 'basic': {
  9039. uniforms: THREE.UniformsUtils.merge( [
  9040. THREE.UniformsLib[ "common" ],
  9041. THREE.UniformsLib[ "fog" ],
  9042. THREE.UniformsLib[ "shadowmap" ]
  9043. ] ),
  9044. vertexShader: [
  9045. THREE.ShaderChunk[ "map_pars_vertex" ],
  9046. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9047. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9048. THREE.ShaderChunk[ "color_pars_vertex" ],
  9049. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9050. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9051. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9052. "void main() {",
  9053. THREE.ShaderChunk[ "map_vertex" ],
  9054. THREE.ShaderChunk[ "lightmap_vertex" ],
  9055. THREE.ShaderChunk[ "color_vertex" ],
  9056. "#ifdef USE_ENVMAP",
  9057. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9058. THREE.ShaderChunk[ "skinbase_vertex" ],
  9059. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9060. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9061. "#endif",
  9062. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9063. THREE.ShaderChunk[ "skinning_vertex" ],
  9064. THREE.ShaderChunk[ "default_vertex" ],
  9065. THREE.ShaderChunk[ "worldpos_vertex" ],
  9066. THREE.ShaderChunk[ "envmap_vertex" ],
  9067. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9068. "}"
  9069. ].join("\n"),
  9070. fragmentShader: [
  9071. "uniform vec3 diffuse;",
  9072. "uniform float opacity;",
  9073. THREE.ShaderChunk[ "color_pars_fragment" ],
  9074. THREE.ShaderChunk[ "map_pars_fragment" ],
  9075. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9076. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9077. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9078. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9079. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9080. "void main() {",
  9081. "gl_FragColor = vec4( diffuse, opacity );",
  9082. THREE.ShaderChunk[ "map_fragment" ],
  9083. THREE.ShaderChunk[ "alphatest_fragment" ],
  9084. THREE.ShaderChunk[ "specularmap_fragment" ],
  9085. THREE.ShaderChunk[ "lightmap_fragment" ],
  9086. THREE.ShaderChunk[ "color_fragment" ],
  9087. THREE.ShaderChunk[ "envmap_fragment" ],
  9088. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9089. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9090. THREE.ShaderChunk[ "fog_fragment" ],
  9091. "}"
  9092. ].join("\n")
  9093. },
  9094. 'lambert': {
  9095. uniforms: THREE.UniformsUtils.merge( [
  9096. THREE.UniformsLib[ "common" ],
  9097. THREE.UniformsLib[ "fog" ],
  9098. THREE.UniformsLib[ "lights" ],
  9099. THREE.UniformsLib[ "shadowmap" ],
  9100. {
  9101. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9102. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9103. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9104. }
  9105. ] ),
  9106. vertexShader: [
  9107. "#define LAMBERT",
  9108. "varying vec3 vLightFront;",
  9109. "#ifdef DOUBLE_SIDED",
  9110. "varying vec3 vLightBack;",
  9111. "#endif",
  9112. THREE.ShaderChunk[ "map_pars_vertex" ],
  9113. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9114. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9115. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9116. THREE.ShaderChunk[ "color_pars_vertex" ],
  9117. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9118. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9119. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9120. "void main() {",
  9121. THREE.ShaderChunk[ "map_vertex" ],
  9122. THREE.ShaderChunk[ "lightmap_vertex" ],
  9123. THREE.ShaderChunk[ "color_vertex" ],
  9124. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9125. THREE.ShaderChunk[ "skinbase_vertex" ],
  9126. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9127. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9128. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9129. THREE.ShaderChunk[ "skinning_vertex" ],
  9130. THREE.ShaderChunk[ "default_vertex" ],
  9131. THREE.ShaderChunk[ "worldpos_vertex" ],
  9132. THREE.ShaderChunk[ "envmap_vertex" ],
  9133. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9134. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9135. "}"
  9136. ].join("\n"),
  9137. fragmentShader: [
  9138. "uniform float opacity;",
  9139. "varying vec3 vLightFront;",
  9140. "#ifdef DOUBLE_SIDED",
  9141. "varying vec3 vLightBack;",
  9142. "#endif",
  9143. THREE.ShaderChunk[ "color_pars_fragment" ],
  9144. THREE.ShaderChunk[ "map_pars_fragment" ],
  9145. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9146. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9147. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9148. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9149. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9150. "void main() {",
  9151. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9152. THREE.ShaderChunk[ "map_fragment" ],
  9153. THREE.ShaderChunk[ "alphatest_fragment" ],
  9154. THREE.ShaderChunk[ "specularmap_fragment" ],
  9155. "#ifdef DOUBLE_SIDED",
  9156. //"float isFront = float( gl_FrontFacing );",
  9157. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9158. "if ( gl_FrontFacing )",
  9159. "gl_FragColor.xyz *= vLightFront;",
  9160. "else",
  9161. "gl_FragColor.xyz *= vLightBack;",
  9162. "#else",
  9163. "gl_FragColor.xyz *= vLightFront;",
  9164. "#endif",
  9165. THREE.ShaderChunk[ "lightmap_fragment" ],
  9166. THREE.ShaderChunk[ "color_fragment" ],
  9167. THREE.ShaderChunk[ "envmap_fragment" ],
  9168. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9169. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9170. THREE.ShaderChunk[ "fog_fragment" ],
  9171. "}"
  9172. ].join("\n")
  9173. },
  9174. 'phong': {
  9175. uniforms: THREE.UniformsUtils.merge( [
  9176. THREE.UniformsLib[ "common" ],
  9177. THREE.UniformsLib[ "bump" ],
  9178. THREE.UniformsLib[ "normalmap" ],
  9179. THREE.UniformsLib[ "fog" ],
  9180. THREE.UniformsLib[ "lights" ],
  9181. THREE.UniformsLib[ "shadowmap" ],
  9182. {
  9183. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9184. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9185. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  9186. "shininess": { type: "f", value: 30 },
  9187. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9188. }
  9189. ] ),
  9190. vertexShader: [
  9191. "#define PHONG",
  9192. "varying vec3 vViewPosition;",
  9193. "varying vec3 vNormal;",
  9194. THREE.ShaderChunk[ "map_pars_vertex" ],
  9195. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9196. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9197. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  9198. THREE.ShaderChunk[ "color_pars_vertex" ],
  9199. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9200. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9201. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9202. "void main() {",
  9203. THREE.ShaderChunk[ "map_vertex" ],
  9204. THREE.ShaderChunk[ "lightmap_vertex" ],
  9205. THREE.ShaderChunk[ "color_vertex" ],
  9206. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9207. THREE.ShaderChunk[ "skinbase_vertex" ],
  9208. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9209. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9210. "vNormal = transformedNormal;",
  9211. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9212. THREE.ShaderChunk[ "skinning_vertex" ],
  9213. THREE.ShaderChunk[ "default_vertex" ],
  9214. "vViewPosition = -mvPosition.xyz;",
  9215. THREE.ShaderChunk[ "worldpos_vertex" ],
  9216. THREE.ShaderChunk[ "envmap_vertex" ],
  9217. THREE.ShaderChunk[ "lights_phong_vertex" ],
  9218. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9219. "}"
  9220. ].join("\n"),
  9221. fragmentShader: [
  9222. "uniform vec3 diffuse;",
  9223. "uniform float opacity;",
  9224. "uniform vec3 ambient;",
  9225. "uniform vec3 emissive;",
  9226. "uniform vec3 specular;",
  9227. "uniform float shininess;",
  9228. THREE.ShaderChunk[ "color_pars_fragment" ],
  9229. THREE.ShaderChunk[ "map_pars_fragment" ],
  9230. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9231. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9232. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9233. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  9234. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9235. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  9236. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  9237. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9238. "void main() {",
  9239. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9240. THREE.ShaderChunk[ "map_fragment" ],
  9241. THREE.ShaderChunk[ "alphatest_fragment" ],
  9242. THREE.ShaderChunk[ "specularmap_fragment" ],
  9243. THREE.ShaderChunk[ "lights_phong_fragment" ],
  9244. THREE.ShaderChunk[ "lightmap_fragment" ],
  9245. THREE.ShaderChunk[ "color_fragment" ],
  9246. THREE.ShaderChunk[ "envmap_fragment" ],
  9247. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9248. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9249. THREE.ShaderChunk[ "fog_fragment" ],
  9250. "}"
  9251. ].join("\n")
  9252. },
  9253. 'particle_basic': {
  9254. uniforms: THREE.UniformsUtils.merge( [
  9255. THREE.UniformsLib[ "particle" ],
  9256. THREE.UniformsLib[ "shadowmap" ]
  9257. ] ),
  9258. vertexShader: [
  9259. "uniform float size;",
  9260. "uniform float scale;",
  9261. THREE.ShaderChunk[ "color_pars_vertex" ],
  9262. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9263. "void main() {",
  9264. THREE.ShaderChunk[ "color_vertex" ],
  9265. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9266. "#ifdef USE_SIZEATTENUATION",
  9267. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  9268. "#else",
  9269. "gl_PointSize = size;",
  9270. "#endif",
  9271. "gl_Position = projectionMatrix * mvPosition;",
  9272. THREE.ShaderChunk[ "worldpos_vertex" ],
  9273. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9274. "}"
  9275. ].join("\n"),
  9276. fragmentShader: [
  9277. "uniform vec3 psColor;",
  9278. "uniform float opacity;",
  9279. THREE.ShaderChunk[ "color_pars_fragment" ],
  9280. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  9281. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9282. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9283. "void main() {",
  9284. "gl_FragColor = vec4( psColor, opacity );",
  9285. THREE.ShaderChunk[ "map_particle_fragment" ],
  9286. THREE.ShaderChunk[ "alphatest_fragment" ],
  9287. THREE.ShaderChunk[ "color_fragment" ],
  9288. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9289. THREE.ShaderChunk[ "fog_fragment" ],
  9290. "}"
  9291. ].join("\n")
  9292. },
  9293. // Depth encoding into RGBA texture
  9294. // based on SpiderGL shadow map example
  9295. // http://spidergl.org/example.php?id=6
  9296. // originally from
  9297. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  9298. // see also here:
  9299. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  9300. 'depthRGBA': {
  9301. uniforms: {},
  9302. vertexShader: [
  9303. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9304. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9305. "void main() {",
  9306. THREE.ShaderChunk[ "skinbase_vertex" ],
  9307. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9308. THREE.ShaderChunk[ "skinning_vertex" ],
  9309. THREE.ShaderChunk[ "default_vertex" ],
  9310. "}"
  9311. ].join("\n"),
  9312. fragmentShader: [
  9313. "vec4 pack_depth( const in float depth ) {",
  9314. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  9315. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  9316. "vec4 res = fract( depth * bit_shift );",
  9317. "res -= res.xxyz * bit_mask;",
  9318. "return res;",
  9319. "}",
  9320. "void main() {",
  9321. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  9322. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  9323. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  9324. //"gl_FragData[ 0 ] = pack_depth( z );",
  9325. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  9326. "}"
  9327. ].join("\n")
  9328. }
  9329. };
  9330. /**
  9331. * @author supereggbert / http://www.paulbrunt.co.uk/
  9332. * @author mrdoob / http://mrdoob.com/
  9333. * @author alteredq / http://alteredqualia.com/
  9334. * @author szimek / https://github.com/szimek/
  9335. */
  9336. THREE.WebGLRenderer = function ( parameters ) {
  9337. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  9338. parameters = parameters || {};
  9339. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  9340. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  9341. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  9342. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  9343. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  9344. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  9345. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  9346. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  9347. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0,
  9348. _maxLights = parameters.maxLights !== undefined ? parameters.maxLights : 4;
  9349. // public properties
  9350. this.domElement = _canvas;
  9351. this.context = null;
  9352. // clearing
  9353. this.autoClear = true;
  9354. this.autoClearColor = true;
  9355. this.autoClearDepth = true;
  9356. this.autoClearStencil = true;
  9357. // scene graph
  9358. this.sortObjects = true;
  9359. this.autoUpdateObjects = true;
  9360. this.autoUpdateScene = true;
  9361. // physically based shading
  9362. this.gammaInput = false;
  9363. this.gammaOutput = false;
  9364. this.physicallyBasedShading = false;
  9365. // shadow map
  9366. this.shadowMapEnabled = false;
  9367. this.shadowMapAutoUpdate = true;
  9368. this.shadowMapSoft = true;
  9369. this.shadowMapCullFrontFaces = true;
  9370. this.shadowMapDebug = false;
  9371. this.shadowMapCascade = false;
  9372. // morphs
  9373. this.maxMorphTargets = 8;
  9374. this.maxMorphNormals = 4;
  9375. // flags
  9376. this.autoScaleCubemaps = true;
  9377. // custom render plugins
  9378. this.renderPluginsPre = [];
  9379. this.renderPluginsPost = [];
  9380. // info
  9381. this.info = {
  9382. memory: {
  9383. programs: 0,
  9384. geometries: 0,
  9385. textures: 0
  9386. },
  9387. render: {
  9388. calls: 0,
  9389. vertices: 0,
  9390. faces: 0,
  9391. points: 0
  9392. }
  9393. };
  9394. // internal properties
  9395. var _this = this,
  9396. _programs = [],
  9397. _programs_counter = 0,
  9398. // internal state cache
  9399. _currentProgram = null,
  9400. _currentFramebuffer = null,
  9401. _currentMaterialId = -1,
  9402. _currentGeometryGroupHash = null,
  9403. _currentCamera = null,
  9404. _geometryGroupCounter = 0,
  9405. _usedTextureUnits = 0,
  9406. // GL state cache
  9407. _oldDoubleSided = -1,
  9408. _oldFlipSided = -1,
  9409. _oldBlending = -1,
  9410. _oldBlendEquation = -1,
  9411. _oldBlendSrc = -1,
  9412. _oldBlendDst = -1,
  9413. _oldDepthTest = -1,
  9414. _oldDepthWrite = -1,
  9415. _oldPolygonOffset = null,
  9416. _oldPolygonOffsetFactor = null,
  9417. _oldPolygonOffsetUnits = null,
  9418. _oldLineWidth = null,
  9419. _viewportX = 0,
  9420. _viewportY = 0,
  9421. _viewportWidth = 0,
  9422. _viewportHeight = 0,
  9423. _currentWidth = 0,
  9424. _currentHeight = 0,
  9425. // frustum
  9426. _frustum = new THREE.Frustum(),
  9427. // camera matrices cache
  9428. _projScreenMatrix = new THREE.Matrix4(),
  9429. _projScreenMatrixPS = new THREE.Matrix4(),
  9430. _vector3 = new THREE.Vector4(),
  9431. // light arrays cache
  9432. _direction = new THREE.Vector3(),
  9433. _lightsNeedUpdate = true,
  9434. _lights = {
  9435. ambient: [ 0, 0, 0 ],
  9436. directional: { length: 0, colors: new Array(), positions: new Array() },
  9437. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  9438. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), angles: new Array(), exponents: new Array() },
  9439. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  9440. };
  9441. // initialize
  9442. var _gl;
  9443. var _glExtensionTextureFloat;
  9444. var _glExtensionStandardDerivatives;
  9445. var _glExtensionTextureFilterAnisotropic;
  9446. var _glExtensionCompressedTextureS3TC;
  9447. initGL();
  9448. setDefaultGLState();
  9449. this.context = _gl;
  9450. // GPU capabilities
  9451. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  9452. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9453. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  9454. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9455. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  9456. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  9457. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  9458. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  9459. // API
  9460. this.getContext = function () {
  9461. return _gl;
  9462. };
  9463. this.supportsVertexTextures = function () {
  9464. return _supportsVertexTextures;
  9465. };
  9466. this.getMaxAnisotropy = function () {
  9467. return _maxAnisotropy;
  9468. };
  9469. this.setSize = function ( width, height ) {
  9470. _canvas.width = width;
  9471. _canvas.height = height;
  9472. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  9473. };
  9474. this.setViewport = function ( x, y, width, height ) {
  9475. _viewportX = x !== undefined ? x : 0;
  9476. _viewportY = y !== undefined ? y : 0;
  9477. _viewportWidth = width !== undefined ? width : _canvas.width;
  9478. _viewportHeight = height !== undefined ? height : _canvas.height;
  9479. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  9480. };
  9481. this.setScissor = function ( x, y, width, height ) {
  9482. _gl.scissor( x, y, width, height );
  9483. };
  9484. this.enableScissorTest = function ( enable ) {
  9485. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  9486. };
  9487. // Clearing
  9488. this.setClearColorHex = function ( hex, alpha ) {
  9489. _clearColor.setHex( hex );
  9490. _clearAlpha = alpha;
  9491. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9492. };
  9493. this.setClearColor = function ( color, alpha ) {
  9494. _clearColor.copy( color );
  9495. _clearAlpha = alpha;
  9496. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9497. };
  9498. this.getClearColor = function () {
  9499. return _clearColor;
  9500. };
  9501. this.getClearAlpha = function () {
  9502. return _clearAlpha;
  9503. };
  9504. this.clear = function ( color, depth, stencil ) {
  9505. var bits = 0;
  9506. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  9507. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  9508. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  9509. _gl.clear( bits );
  9510. };
  9511. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  9512. this.setRenderTarget( renderTarget );
  9513. this.clear( color, depth, stencil );
  9514. };
  9515. // Plugins
  9516. this.addPostPlugin = function ( plugin ) {
  9517. plugin.init( this );
  9518. this.renderPluginsPost.push( plugin );
  9519. };
  9520. this.addPrePlugin = function ( plugin ) {
  9521. plugin.init( this );
  9522. this.renderPluginsPre.push( plugin );
  9523. };
  9524. // Deallocation
  9525. this.deallocateObject = function ( object ) {
  9526. if ( ! object.__webglInit ) return;
  9527. object.__webglInit = false;
  9528. delete object._modelViewMatrix;
  9529. delete object._normalMatrix;
  9530. delete object._normalMatrixArray;
  9531. delete object._modelViewMatrixArray;
  9532. delete object._modelMatrixArray;
  9533. if ( object instanceof THREE.Mesh ) {
  9534. for ( var g in object.geometry.geometryGroups ) {
  9535. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  9536. }
  9537. } else if ( object instanceof THREE.Ribbon ) {
  9538. deleteRibbonBuffers( object.geometry );
  9539. } else if ( object instanceof THREE.Line ) {
  9540. deleteLineBuffers( object.geometry );
  9541. } else if ( object instanceof THREE.ParticleSystem ) {
  9542. deleteParticleBuffers( object.geometry );
  9543. }
  9544. };
  9545. this.deallocateTexture = function ( texture ) {
  9546. if ( ! texture.__webglInit ) return;
  9547. texture.__webglInit = false;
  9548. _gl.deleteTexture( texture.__webglTexture );
  9549. _this.info.memory.textures --;
  9550. };
  9551. this.deallocateRenderTarget = function ( renderTarget ) {
  9552. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  9553. _gl.deleteTexture( renderTarget.__webglTexture );
  9554. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9555. for ( var i = 0; i < 6; i ++ ) {
  9556. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  9557. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  9558. }
  9559. } else {
  9560. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  9561. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  9562. }
  9563. };
  9564. this.deallocateMaterial = function ( material ) {
  9565. var program = material.program;
  9566. if ( ! program ) return;
  9567. material.program = undefined;
  9568. // only deallocate GL program if this was the last use of shared program
  9569. // assumed there is only single copy of any program in the _programs list
  9570. // (that's how it's constructed)
  9571. var i, il, programInfo;
  9572. var deleteProgram = false;
  9573. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9574. programInfo = _programs[ i ];
  9575. if ( programInfo.program === program ) {
  9576. programInfo.usedTimes --;
  9577. if ( programInfo.usedTimes === 0 ) {
  9578. deleteProgram = true;
  9579. }
  9580. break;
  9581. }
  9582. }
  9583. if ( deleteProgram ) {
  9584. // avoid using array.splice, this is costlier than creating new array from scratch
  9585. var newPrograms = [];
  9586. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9587. programInfo = _programs[ i ];
  9588. if ( programInfo.program !== program ) {
  9589. newPrograms.push( programInfo );
  9590. }
  9591. }
  9592. _programs = newPrograms;
  9593. _gl.deleteProgram( program );
  9594. _this.info.memory.programs --;
  9595. }
  9596. };
  9597. // Rendering
  9598. this.updateShadowMap = function ( scene, camera ) {
  9599. _currentProgram = null;
  9600. _oldBlending = -1;
  9601. _oldDepthTest = -1;
  9602. _oldDepthWrite = -1;
  9603. _currentGeometryGroupHash = -1;
  9604. _currentMaterialId = -1;
  9605. _lightsNeedUpdate = true;
  9606. _oldDoubleSided = -1;
  9607. _oldFlipSided = -1;
  9608. this.shadowMapPlugin.update( scene, camera );
  9609. };
  9610. // Internal functions
  9611. // Buffer allocation
  9612. function createParticleBuffers ( geometry ) {
  9613. geometry.__webglVertexBuffer = _gl.createBuffer();
  9614. geometry.__webglColorBuffer = _gl.createBuffer();
  9615. _this.info.memory.geometries ++;
  9616. };
  9617. function createLineBuffers ( geometry ) {
  9618. geometry.__webglVertexBuffer = _gl.createBuffer();
  9619. geometry.__webglColorBuffer = _gl.createBuffer();
  9620. _this.info.memory.geometries ++;
  9621. };
  9622. function createRibbonBuffers ( geometry ) {
  9623. geometry.__webglVertexBuffer = _gl.createBuffer();
  9624. geometry.__webglColorBuffer = _gl.createBuffer();
  9625. _this.info.memory.geometries ++;
  9626. };
  9627. function createMeshBuffers ( geometryGroup ) {
  9628. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  9629. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  9630. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  9631. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  9632. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  9633. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  9634. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  9635. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  9636. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  9637. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  9638. var m, ml;
  9639. if ( geometryGroup.numMorphTargets ) {
  9640. geometryGroup.__webglMorphTargetsBuffers = [];
  9641. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9642. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  9643. }
  9644. }
  9645. if ( geometryGroup.numMorphNormals ) {
  9646. geometryGroup.__webglMorphNormalsBuffers = [];
  9647. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9648. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  9649. }
  9650. }
  9651. _this.info.memory.geometries ++;
  9652. };
  9653. // Buffer deallocation
  9654. function deleteParticleBuffers ( geometry ) {
  9655. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9656. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9657. _this.info.memory.geometries --;
  9658. };
  9659. function deleteLineBuffers ( geometry ) {
  9660. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9661. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9662. _this.info.memory.geometries --;
  9663. };
  9664. function deleteRibbonBuffers ( geometry ) {
  9665. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9666. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9667. _this.info.memory.geometries --;
  9668. };
  9669. function deleteMeshBuffers ( geometryGroup ) {
  9670. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  9671. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  9672. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  9673. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  9674. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  9675. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  9676. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  9677. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  9678. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  9679. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  9680. var m, ml;
  9681. if ( geometryGroup.numMorphTargets ) {
  9682. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9683. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  9684. }
  9685. }
  9686. if ( geometryGroup.numMorphNormals ) {
  9687. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9688. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  9689. }
  9690. }
  9691. if ( geometryGroup.__webglCustomAttributesList ) {
  9692. for ( var id in geometryGroup.__webglCustomAttributesList ) {
  9693. _gl.deleteBuffer( geometryGroup.__webglCustomAttributesList[ id ].buffer );
  9694. }
  9695. }
  9696. _this.info.memory.geometries --;
  9697. };
  9698. // Buffer initialization
  9699. function initCustomAttributes ( geometry, object ) {
  9700. var nvertices = geometry.vertices.length;
  9701. var material = object.material;
  9702. if ( material.attributes ) {
  9703. if ( geometry.__webglCustomAttributesList === undefined ) {
  9704. geometry.__webglCustomAttributesList = [];
  9705. }
  9706. for ( var a in material.attributes ) {
  9707. var attribute = material.attributes[ a ];
  9708. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9709. attribute.__webglInitialized = true;
  9710. var size = 1; // "f" and "i"
  9711. if ( attribute.type === "v2" ) size = 2;
  9712. else if ( attribute.type === "v3" ) size = 3;
  9713. else if ( attribute.type === "v4" ) size = 4;
  9714. else if ( attribute.type === "c" ) size = 3;
  9715. attribute.size = size;
  9716. attribute.array = new Float32Array( nvertices * size );
  9717. attribute.buffer = _gl.createBuffer();
  9718. attribute.buffer.belongsToAttribute = a;
  9719. attribute.needsUpdate = true;
  9720. }
  9721. geometry.__webglCustomAttributesList.push( attribute );
  9722. }
  9723. }
  9724. };
  9725. function initParticleBuffers ( geometry, object ) {
  9726. var nvertices = geometry.vertices.length;
  9727. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9728. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9729. geometry.__sortArray = [];
  9730. geometry.__webglParticleCount = nvertices;
  9731. initCustomAttributes ( geometry, object );
  9732. };
  9733. function initLineBuffers ( geometry, object ) {
  9734. var nvertices = geometry.vertices.length;
  9735. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9736. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9737. geometry.__webglLineCount = nvertices;
  9738. initCustomAttributes ( geometry, object );
  9739. };
  9740. function initRibbonBuffers ( geometry ) {
  9741. var nvertices = geometry.vertices.length;
  9742. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9743. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9744. geometry.__webglVertexCount = nvertices;
  9745. };
  9746. function initMeshBuffers ( geometryGroup, object ) {
  9747. var geometry = object.geometry,
  9748. faces3 = geometryGroup.faces3,
  9749. faces4 = geometryGroup.faces4,
  9750. nvertices = faces3.length * 3 + faces4.length * 4,
  9751. ntris = faces3.length * 1 + faces4.length * 2,
  9752. nlines = faces3.length * 3 + faces4.length * 4,
  9753. material = getBufferMaterial( object, geometryGroup ),
  9754. uvType = bufferGuessUVType( material ),
  9755. normalType = bufferGuessNormalType( material ),
  9756. vertexColorType = bufferGuessVertexColorType( material );
  9757. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  9758. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  9759. if ( normalType ) {
  9760. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  9761. }
  9762. if ( geometry.hasTangents ) {
  9763. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  9764. }
  9765. if ( vertexColorType ) {
  9766. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  9767. }
  9768. if ( uvType ) {
  9769. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  9770. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  9771. }
  9772. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  9773. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  9774. }
  9775. }
  9776. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  9777. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  9778. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  9779. }
  9780. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  9781. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  9782. var m, ml;
  9783. if ( geometryGroup.numMorphTargets ) {
  9784. geometryGroup.__morphTargetsArrays = [];
  9785. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9786. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  9787. }
  9788. }
  9789. if ( geometryGroup.numMorphNormals ) {
  9790. geometryGroup.__morphNormalsArrays = [];
  9791. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9792. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  9793. }
  9794. }
  9795. geometryGroup.__webglFaceCount = ntris * 3;
  9796. geometryGroup.__webglLineCount = nlines * 2;
  9797. // custom attributes
  9798. if ( material.attributes ) {
  9799. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  9800. geometryGroup.__webglCustomAttributesList = [];
  9801. }
  9802. for ( var a in material.attributes ) {
  9803. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  9804. // attribute buffers which are correctly indexed in the setMeshBuffers function
  9805. var originalAttribute = material.attributes[ a ];
  9806. var attribute = {};
  9807. for ( var property in originalAttribute ) {
  9808. attribute[ property ] = originalAttribute[ property ];
  9809. }
  9810. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9811. attribute.__webglInitialized = true;
  9812. var size = 1; // "f" and "i"
  9813. if( attribute.type === "v2" ) size = 2;
  9814. else if( attribute.type === "v3" ) size = 3;
  9815. else if( attribute.type === "v4" ) size = 4;
  9816. else if( attribute.type === "c" ) size = 3;
  9817. attribute.size = size;
  9818. attribute.array = new Float32Array( nvertices * size );
  9819. attribute.buffer = _gl.createBuffer();
  9820. attribute.buffer.belongsToAttribute = a;
  9821. originalAttribute.needsUpdate = true;
  9822. attribute.__original = originalAttribute;
  9823. }
  9824. geometryGroup.__webglCustomAttributesList.push( attribute );
  9825. }
  9826. }
  9827. geometryGroup.__inittedArrays = true;
  9828. };
  9829. function getBufferMaterial( object, geometryGroup ) {
  9830. if ( object.material && ! ( object.material instanceof THREE.MeshFaceMaterial ) ) {
  9831. return object.material;
  9832. } else if ( geometryGroup.materialIndex >= 0 ) {
  9833. return object.geometry.materials[ geometryGroup.materialIndex ];
  9834. }
  9835. };
  9836. function materialNeedsSmoothNormals ( material ) {
  9837. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  9838. };
  9839. function bufferGuessNormalType ( material ) {
  9840. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  9841. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  9842. return false;
  9843. }
  9844. if ( materialNeedsSmoothNormals( material ) ) {
  9845. return THREE.SmoothShading;
  9846. } else {
  9847. return THREE.FlatShading;
  9848. }
  9849. };
  9850. function bufferGuessVertexColorType ( material ) {
  9851. if ( material.vertexColors ) {
  9852. return material.vertexColors;
  9853. }
  9854. return false;
  9855. };
  9856. function bufferGuessUVType ( material ) {
  9857. // material must use some texture to require uvs
  9858. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  9859. return true;
  9860. }
  9861. return false;
  9862. };
  9863. //
  9864. function initDirectBuffers( geometry ) {
  9865. var a, attribute, type;
  9866. for ( a in geometry.attributes ) {
  9867. if ( a === "index" ) {
  9868. type = _gl.ELEMENT_ARRAY_BUFFER;
  9869. } else {
  9870. type = _gl.ARRAY_BUFFER;
  9871. }
  9872. attribute = geometry.attributes[ a ];
  9873. attribute.buffer = _gl.createBuffer();
  9874. _gl.bindBuffer( type, attribute.buffer );
  9875. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  9876. }
  9877. };
  9878. // Buffer setting
  9879. function setParticleBuffers ( geometry, hint, object ) {
  9880. var v, c, vertex, offset, index, color,
  9881. vertices = geometry.vertices,
  9882. vl = vertices.length,
  9883. colors = geometry.colors,
  9884. cl = colors.length,
  9885. vertexArray = geometry.__vertexArray,
  9886. colorArray = geometry.__colorArray,
  9887. sortArray = geometry.__sortArray,
  9888. dirtyVertices = geometry.verticesNeedUpdate,
  9889. dirtyElements = geometry.elementsNeedUpdate,
  9890. dirtyColors = geometry.colorsNeedUpdate,
  9891. customAttributes = geometry.__webglCustomAttributesList,
  9892. i, il,
  9893. a, ca, cal, value,
  9894. customAttribute;
  9895. if ( object.sortParticles ) {
  9896. _projScreenMatrixPS.copy( _projScreenMatrix );
  9897. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  9898. for ( v = 0; v < vl; v ++ ) {
  9899. vertex = vertices[ v ];
  9900. _vector3.copy( vertex );
  9901. _projScreenMatrixPS.multiplyVector3( _vector3 );
  9902. sortArray[ v ] = [ _vector3.z, v ];
  9903. }
  9904. sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
  9905. for ( v = 0; v < vl; v ++ ) {
  9906. vertex = vertices[ sortArray[v][1] ];
  9907. offset = v * 3;
  9908. vertexArray[ offset ] = vertex.x;
  9909. vertexArray[ offset + 1 ] = vertex.y;
  9910. vertexArray[ offset + 2 ] = vertex.z;
  9911. }
  9912. for ( c = 0; c < cl; c ++ ) {
  9913. offset = c * 3;
  9914. color = colors[ sortArray[c][1] ];
  9915. colorArray[ offset ] = color.r;
  9916. colorArray[ offset + 1 ] = color.g;
  9917. colorArray[ offset + 2 ] = color.b;
  9918. }
  9919. if ( customAttributes ) {
  9920. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9921. customAttribute = customAttributes[ i ];
  9922. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  9923. offset = 0;
  9924. cal = customAttribute.value.length;
  9925. if ( customAttribute.size === 1 ) {
  9926. for ( ca = 0; ca < cal; ca ++ ) {
  9927. index = sortArray[ ca ][ 1 ];
  9928. customAttribute.array[ ca ] = customAttribute.value[ index ];
  9929. }
  9930. } else if ( customAttribute.size === 2 ) {
  9931. for ( ca = 0; ca < cal; ca ++ ) {
  9932. index = sortArray[ ca ][ 1 ];
  9933. value = customAttribute.value[ index ];
  9934. customAttribute.array[ offset ] = value.x;
  9935. customAttribute.array[ offset + 1 ] = value.y;
  9936. offset += 2;
  9937. }
  9938. } else if ( customAttribute.size === 3 ) {
  9939. if ( customAttribute.type === "c" ) {
  9940. for ( ca = 0; ca < cal; ca ++ ) {
  9941. index = sortArray[ ca ][ 1 ];
  9942. value = customAttribute.value[ index ];
  9943. customAttribute.array[ offset ] = value.r;
  9944. customAttribute.array[ offset + 1 ] = value.g;
  9945. customAttribute.array[ offset + 2 ] = value.b;
  9946. offset += 3;
  9947. }
  9948. } else {
  9949. for ( ca = 0; ca < cal; ca ++ ) {
  9950. index = sortArray[ ca ][ 1 ];
  9951. value = customAttribute.value[ index ];
  9952. customAttribute.array[ offset ] = value.x;
  9953. customAttribute.array[ offset + 1 ] = value.y;
  9954. customAttribute.array[ offset + 2 ] = value.z;
  9955. offset += 3;
  9956. }
  9957. }
  9958. } else if ( customAttribute.size === 4 ) {
  9959. for ( ca = 0; ca < cal; ca ++ ) {
  9960. index = sortArray[ ca ][ 1 ];
  9961. value = customAttribute.value[ index ];
  9962. customAttribute.array[ offset ] = value.x;
  9963. customAttribute.array[ offset + 1 ] = value.y;
  9964. customAttribute.array[ offset + 2 ] = value.z;
  9965. customAttribute.array[ offset + 3 ] = value.w;
  9966. offset += 4;
  9967. }
  9968. }
  9969. }
  9970. }
  9971. } else {
  9972. if ( dirtyVertices ) {
  9973. for ( v = 0; v < vl; v ++ ) {
  9974. vertex = vertices[ v ];
  9975. offset = v * 3;
  9976. vertexArray[ offset ] = vertex.x;
  9977. vertexArray[ offset + 1 ] = vertex.y;
  9978. vertexArray[ offset + 2 ] = vertex.z;
  9979. }
  9980. }
  9981. if ( dirtyColors ) {
  9982. for ( c = 0; c < cl; c ++ ) {
  9983. color = colors[ c ];
  9984. offset = c * 3;
  9985. colorArray[ offset ] = color.r;
  9986. colorArray[ offset + 1 ] = color.g;
  9987. colorArray[ offset + 2 ] = color.b;
  9988. }
  9989. }
  9990. if ( customAttributes ) {
  9991. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9992. customAttribute = customAttributes[ i ];
  9993. if ( customAttribute.needsUpdate &&
  9994. ( customAttribute.boundTo === undefined ||
  9995. customAttribute.boundTo === "vertices") ) {
  9996. cal = customAttribute.value.length;
  9997. offset = 0;
  9998. if ( customAttribute.size === 1 ) {
  9999. for ( ca = 0; ca < cal; ca ++ ) {
  10000. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10001. }
  10002. } else if ( customAttribute.size === 2 ) {
  10003. for ( ca = 0; ca < cal; ca ++ ) {
  10004. value = customAttribute.value[ ca ];
  10005. customAttribute.array[ offset ] = value.x;
  10006. customAttribute.array[ offset + 1 ] = value.y;
  10007. offset += 2;
  10008. }
  10009. } else if ( customAttribute.size === 3 ) {
  10010. if ( customAttribute.type === "c" ) {
  10011. for ( ca = 0; ca < cal; ca ++ ) {
  10012. value = customAttribute.value[ ca ];
  10013. customAttribute.array[ offset ] = value.r;
  10014. customAttribute.array[ offset + 1 ] = value.g;
  10015. customAttribute.array[ offset + 2 ] = value.b;
  10016. offset += 3;
  10017. }
  10018. } else {
  10019. for ( ca = 0; ca < cal; ca ++ ) {
  10020. value = customAttribute.value[ ca ];
  10021. customAttribute.array[ offset ] = value.x;
  10022. customAttribute.array[ offset + 1 ] = value.y;
  10023. customAttribute.array[ offset + 2 ] = value.z;
  10024. offset += 3;
  10025. }
  10026. }
  10027. } else if ( customAttribute.size === 4 ) {
  10028. for ( ca = 0; ca < cal; ca ++ ) {
  10029. value = customAttribute.value[ ca ];
  10030. customAttribute.array[ offset ] = value.x;
  10031. customAttribute.array[ offset + 1 ] = value.y;
  10032. customAttribute.array[ offset + 2 ] = value.z;
  10033. customAttribute.array[ offset + 3 ] = value.w;
  10034. offset += 4;
  10035. }
  10036. }
  10037. }
  10038. }
  10039. }
  10040. }
  10041. if ( dirtyVertices || object.sortParticles ) {
  10042. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10043. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10044. }
  10045. if ( dirtyColors || object.sortParticles ) {
  10046. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10047. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10048. }
  10049. if ( customAttributes ) {
  10050. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10051. customAttribute = customAttributes[ i ];
  10052. if ( customAttribute.needsUpdate || object.sortParticles ) {
  10053. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10054. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10055. }
  10056. }
  10057. }
  10058. };
  10059. function setLineBuffers ( geometry, hint ) {
  10060. var v, c, vertex, offset, color,
  10061. vertices = geometry.vertices,
  10062. colors = geometry.colors,
  10063. vl = vertices.length,
  10064. cl = colors.length,
  10065. vertexArray = geometry.__vertexArray,
  10066. colorArray = geometry.__colorArray,
  10067. dirtyVertices = geometry.verticesNeedUpdate,
  10068. dirtyColors = geometry.colorsNeedUpdate,
  10069. customAttributes = geometry.__webglCustomAttributesList,
  10070. i, il,
  10071. a, ca, cal, value,
  10072. customAttribute;
  10073. if ( dirtyVertices ) {
  10074. for ( v = 0; v < vl; v ++ ) {
  10075. vertex = vertices[ v ];
  10076. offset = v * 3;
  10077. vertexArray[ offset ] = vertex.x;
  10078. vertexArray[ offset + 1 ] = vertex.y;
  10079. vertexArray[ offset + 2 ] = vertex.z;
  10080. }
  10081. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10082. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10083. }
  10084. if ( dirtyColors ) {
  10085. for ( c = 0; c < cl; c ++ ) {
  10086. color = colors[ c ];
  10087. offset = c * 3;
  10088. colorArray[ offset ] = color.r;
  10089. colorArray[ offset + 1 ] = color.g;
  10090. colorArray[ offset + 2 ] = color.b;
  10091. }
  10092. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10093. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10094. }
  10095. if ( customAttributes ) {
  10096. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10097. customAttribute = customAttributes[ i ];
  10098. if ( customAttribute.needsUpdate &&
  10099. ( customAttribute.boundTo === undefined ||
  10100. customAttribute.boundTo === "vertices" ) ) {
  10101. offset = 0;
  10102. cal = customAttribute.value.length;
  10103. if ( customAttribute.size === 1 ) {
  10104. for ( ca = 0; ca < cal; ca ++ ) {
  10105. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10106. }
  10107. } else if ( customAttribute.size === 2 ) {
  10108. for ( ca = 0; ca < cal; ca ++ ) {
  10109. value = customAttribute.value[ ca ];
  10110. customAttribute.array[ offset ] = value.x;
  10111. customAttribute.array[ offset + 1 ] = value.y;
  10112. offset += 2;
  10113. }
  10114. } else if ( customAttribute.size === 3 ) {
  10115. if ( customAttribute.type === "c" ) {
  10116. for ( ca = 0; ca < cal; ca ++ ) {
  10117. value = customAttribute.value[ ca ];
  10118. customAttribute.array[ offset ] = value.r;
  10119. customAttribute.array[ offset + 1 ] = value.g;
  10120. customAttribute.array[ offset + 2 ] = value.b;
  10121. offset += 3;
  10122. }
  10123. } else {
  10124. for ( ca = 0; ca < cal; ca ++ ) {
  10125. value = customAttribute.value[ ca ];
  10126. customAttribute.array[ offset ] = value.x;
  10127. customAttribute.array[ offset + 1 ] = value.y;
  10128. customAttribute.array[ offset + 2 ] = value.z;
  10129. offset += 3;
  10130. }
  10131. }
  10132. } else if ( customAttribute.size === 4 ) {
  10133. for ( ca = 0; ca < cal; ca ++ ) {
  10134. value = customAttribute.value[ ca ];
  10135. customAttribute.array[ offset ] = value.x;
  10136. customAttribute.array[ offset + 1 ] = value.y;
  10137. customAttribute.array[ offset + 2 ] = value.z;
  10138. customAttribute.array[ offset + 3 ] = value.w;
  10139. offset += 4;
  10140. }
  10141. }
  10142. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10143. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10144. }
  10145. }
  10146. }
  10147. };
  10148. function setRibbonBuffers ( geometry, hint ) {
  10149. var v, c, vertex, offset, color,
  10150. vertices = geometry.vertices,
  10151. colors = geometry.colors,
  10152. vl = vertices.length,
  10153. cl = colors.length,
  10154. vertexArray = geometry.__vertexArray,
  10155. colorArray = geometry.__colorArray,
  10156. dirtyVertices = geometry.verticesNeedUpdate,
  10157. dirtyColors = geometry.colorsNeedUpdate;
  10158. if ( dirtyVertices ) {
  10159. for ( v = 0; v < vl; v ++ ) {
  10160. vertex = vertices[ v ];
  10161. offset = v * 3;
  10162. vertexArray[ offset ] = vertex.x;
  10163. vertexArray[ offset + 1 ] = vertex.y;
  10164. vertexArray[ offset + 2 ] = vertex.z;
  10165. }
  10166. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10167. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10168. }
  10169. if ( dirtyColors ) {
  10170. for ( c = 0; c < cl; c ++ ) {
  10171. color = colors[ c ];
  10172. offset = c * 3;
  10173. colorArray[ offset ] = color.r;
  10174. colorArray[ offset + 1 ] = color.g;
  10175. colorArray[ offset + 2 ] = color.b;
  10176. }
  10177. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10178. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10179. }
  10180. };
  10181. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  10182. if ( ! geometryGroup.__inittedArrays ) {
  10183. // console.log( object );
  10184. return;
  10185. }
  10186. var normalType = bufferGuessNormalType( material ),
  10187. vertexColorType = bufferGuessVertexColorType( material ),
  10188. uvType = bufferGuessUVType( material ),
  10189. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  10190. var f, fl, fi, face,
  10191. vertexNormals, faceNormal, normal,
  10192. vertexColors, faceColor,
  10193. vertexTangents,
  10194. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  10195. c1, c2, c3, c4,
  10196. sw1, sw2, sw3, sw4,
  10197. si1, si2, si3, si4,
  10198. sa1, sa2, sa3, sa4,
  10199. sb1, sb2, sb3, sb4,
  10200. m, ml, i, il,
  10201. vn, uvi, uv2i,
  10202. vk, vkl, vka,
  10203. nka, chf, faceVertexNormals,
  10204. a,
  10205. vertexIndex = 0,
  10206. offset = 0,
  10207. offset_uv = 0,
  10208. offset_uv2 = 0,
  10209. offset_face = 0,
  10210. offset_normal = 0,
  10211. offset_tangent = 0,
  10212. offset_line = 0,
  10213. offset_color = 0,
  10214. offset_skin = 0,
  10215. offset_morphTarget = 0,
  10216. offset_custom = 0,
  10217. offset_customSrc = 0,
  10218. value,
  10219. vertexArray = geometryGroup.__vertexArray,
  10220. uvArray = geometryGroup.__uvArray,
  10221. uv2Array = geometryGroup.__uv2Array,
  10222. normalArray = geometryGroup.__normalArray,
  10223. tangentArray = geometryGroup.__tangentArray,
  10224. colorArray = geometryGroup.__colorArray,
  10225. skinIndexArray = geometryGroup.__skinIndexArray,
  10226. skinWeightArray = geometryGroup.__skinWeightArray,
  10227. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  10228. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  10229. customAttributes = geometryGroup.__webglCustomAttributesList,
  10230. customAttribute,
  10231. faceArray = geometryGroup.__faceArray,
  10232. lineArray = geometryGroup.__lineArray,
  10233. geometry = object.geometry, // this is shared for all chunks
  10234. dirtyVertices = geometry.verticesNeedUpdate,
  10235. dirtyElements = geometry.elementsNeedUpdate,
  10236. dirtyUvs = geometry.uvsNeedUpdate,
  10237. dirtyNormals = geometry.normalsNeedUpdate,
  10238. dirtyTangents = geometry.tangentsNeedUpdate,
  10239. dirtyColors = geometry.colorsNeedUpdate,
  10240. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  10241. vertices = geometry.vertices,
  10242. chunk_faces3 = geometryGroup.faces3,
  10243. chunk_faces4 = geometryGroup.faces4,
  10244. obj_faces = geometry.faces,
  10245. obj_uvs = geometry.faceVertexUvs[ 0 ],
  10246. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  10247. obj_colors = geometry.colors,
  10248. obj_skinIndices = geometry.skinIndices,
  10249. obj_skinWeights = geometry.skinWeights,
  10250. morphTargets = geometry.morphTargets,
  10251. morphNormals = geometry.morphNormals;
  10252. if ( dirtyVertices ) {
  10253. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10254. face = obj_faces[ chunk_faces3[ f ] ];
  10255. v1 = vertices[ face.a ];
  10256. v2 = vertices[ face.b ];
  10257. v3 = vertices[ face.c ];
  10258. vertexArray[ offset ] = v1.x;
  10259. vertexArray[ offset + 1 ] = v1.y;
  10260. vertexArray[ offset + 2 ] = v1.z;
  10261. vertexArray[ offset + 3 ] = v2.x;
  10262. vertexArray[ offset + 4 ] = v2.y;
  10263. vertexArray[ offset + 5 ] = v2.z;
  10264. vertexArray[ offset + 6 ] = v3.x;
  10265. vertexArray[ offset + 7 ] = v3.y;
  10266. vertexArray[ offset + 8 ] = v3.z;
  10267. offset += 9;
  10268. }
  10269. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10270. face = obj_faces[ chunk_faces4[ f ] ];
  10271. v1 = vertices[ face.a ];
  10272. v2 = vertices[ face.b ];
  10273. v3 = vertices[ face.c ];
  10274. v4 = vertices[ face.d ];
  10275. vertexArray[ offset ] = v1.x;
  10276. vertexArray[ offset + 1 ] = v1.y;
  10277. vertexArray[ offset + 2 ] = v1.z;
  10278. vertexArray[ offset + 3 ] = v2.x;
  10279. vertexArray[ offset + 4 ] = v2.y;
  10280. vertexArray[ offset + 5 ] = v2.z;
  10281. vertexArray[ offset + 6 ] = v3.x;
  10282. vertexArray[ offset + 7 ] = v3.y;
  10283. vertexArray[ offset + 8 ] = v3.z;
  10284. vertexArray[ offset + 9 ] = v4.x;
  10285. vertexArray[ offset + 10 ] = v4.y;
  10286. vertexArray[ offset + 11 ] = v4.z;
  10287. offset += 12;
  10288. }
  10289. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  10290. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10291. }
  10292. if ( dirtyMorphTargets ) {
  10293. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  10294. offset_morphTarget = 0;
  10295. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10296. chf = chunk_faces3[ f ];
  10297. face = obj_faces[ chf ];
  10298. // morph positions
  10299. v1 = morphTargets[ vk ].vertices[ face.a ];
  10300. v2 = morphTargets[ vk ].vertices[ face.b ];
  10301. v3 = morphTargets[ vk ].vertices[ face.c ];
  10302. vka = morphTargetsArrays[ vk ];
  10303. vka[ offset_morphTarget ] = v1.x;
  10304. vka[ offset_morphTarget + 1 ] = v1.y;
  10305. vka[ offset_morphTarget + 2 ] = v1.z;
  10306. vka[ offset_morphTarget + 3 ] = v2.x;
  10307. vka[ offset_morphTarget + 4 ] = v2.y;
  10308. vka[ offset_morphTarget + 5 ] = v2.z;
  10309. vka[ offset_morphTarget + 6 ] = v3.x;
  10310. vka[ offset_morphTarget + 7 ] = v3.y;
  10311. vka[ offset_morphTarget + 8 ] = v3.z;
  10312. // morph normals
  10313. if ( material.morphNormals ) {
  10314. if ( needsSmoothNormals ) {
  10315. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10316. n1 = faceVertexNormals.a;
  10317. n2 = faceVertexNormals.b;
  10318. n3 = faceVertexNormals.c;
  10319. } else {
  10320. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10321. n2 = n1;
  10322. n3 = n1;
  10323. }
  10324. nka = morphNormalsArrays[ vk ];
  10325. nka[ offset_morphTarget ] = n1.x;
  10326. nka[ offset_morphTarget + 1 ] = n1.y;
  10327. nka[ offset_morphTarget + 2 ] = n1.z;
  10328. nka[ offset_morphTarget + 3 ] = n2.x;
  10329. nka[ offset_morphTarget + 4 ] = n2.y;
  10330. nka[ offset_morphTarget + 5 ] = n2.z;
  10331. nka[ offset_morphTarget + 6 ] = n3.x;
  10332. nka[ offset_morphTarget + 7 ] = n3.y;
  10333. nka[ offset_morphTarget + 8 ] = n3.z;
  10334. }
  10335. //
  10336. offset_morphTarget += 9;
  10337. }
  10338. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10339. chf = chunk_faces4[ f ];
  10340. face = obj_faces[ chf ];
  10341. // morph positions
  10342. v1 = morphTargets[ vk ].vertices[ face.a ];
  10343. v2 = morphTargets[ vk ].vertices[ face.b ];
  10344. v3 = morphTargets[ vk ].vertices[ face.c ];
  10345. v4 = morphTargets[ vk ].vertices[ face.d ];
  10346. vka = morphTargetsArrays[ vk ];
  10347. vka[ offset_morphTarget ] = v1.x;
  10348. vka[ offset_morphTarget + 1 ] = v1.y;
  10349. vka[ offset_morphTarget + 2 ] = v1.z;
  10350. vka[ offset_morphTarget + 3 ] = v2.x;
  10351. vka[ offset_morphTarget + 4 ] = v2.y;
  10352. vka[ offset_morphTarget + 5 ] = v2.z;
  10353. vka[ offset_morphTarget + 6 ] = v3.x;
  10354. vka[ offset_morphTarget + 7 ] = v3.y;
  10355. vka[ offset_morphTarget + 8 ] = v3.z;
  10356. vka[ offset_morphTarget + 9 ] = v4.x;
  10357. vka[ offset_morphTarget + 10 ] = v4.y;
  10358. vka[ offset_morphTarget + 11 ] = v4.z;
  10359. // morph normals
  10360. if ( material.morphNormals ) {
  10361. if ( needsSmoothNormals ) {
  10362. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10363. n1 = faceVertexNormals.a;
  10364. n2 = faceVertexNormals.b;
  10365. n3 = faceVertexNormals.c;
  10366. n4 = faceVertexNormals.d;
  10367. } else {
  10368. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10369. n2 = n1;
  10370. n3 = n1;
  10371. n4 = n1;
  10372. }
  10373. nka = morphNormalsArrays[ vk ];
  10374. nka[ offset_morphTarget ] = n1.x;
  10375. nka[ offset_morphTarget + 1 ] = n1.y;
  10376. nka[ offset_morphTarget + 2 ] = n1.z;
  10377. nka[ offset_morphTarget + 3 ] = n2.x;
  10378. nka[ offset_morphTarget + 4 ] = n2.y;
  10379. nka[ offset_morphTarget + 5 ] = n2.z;
  10380. nka[ offset_morphTarget + 6 ] = n3.x;
  10381. nka[ offset_morphTarget + 7 ] = n3.y;
  10382. nka[ offset_morphTarget + 8 ] = n3.z;
  10383. nka[ offset_morphTarget + 9 ] = n4.x;
  10384. nka[ offset_morphTarget + 10 ] = n4.y;
  10385. nka[ offset_morphTarget + 11 ] = n4.z;
  10386. }
  10387. //
  10388. offset_morphTarget += 12;
  10389. }
  10390. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  10391. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  10392. if ( material.morphNormals ) {
  10393. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  10394. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  10395. }
  10396. }
  10397. }
  10398. if ( obj_skinWeights.length ) {
  10399. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10400. face = obj_faces[ chunk_faces3[ f ] ];
  10401. // weights
  10402. sw1 = obj_skinWeights[ face.a ];
  10403. sw2 = obj_skinWeights[ face.b ];
  10404. sw3 = obj_skinWeights[ face.c ];
  10405. skinWeightArray[ offset_skin ] = sw1.x;
  10406. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10407. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10408. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10409. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10410. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10411. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10412. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10413. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10414. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10415. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10416. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10417. // indices
  10418. si1 = obj_skinIndices[ face.a ];
  10419. si2 = obj_skinIndices[ face.b ];
  10420. si3 = obj_skinIndices[ face.c ];
  10421. skinIndexArray[ offset_skin ] = si1.x;
  10422. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10423. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10424. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10425. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10426. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10427. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10428. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10429. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10430. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10431. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10432. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10433. offset_skin += 12;
  10434. }
  10435. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10436. face = obj_faces[ chunk_faces4[ f ] ];
  10437. // weights
  10438. sw1 = obj_skinWeights[ face.a ];
  10439. sw2 = obj_skinWeights[ face.b ];
  10440. sw3 = obj_skinWeights[ face.c ];
  10441. sw4 = obj_skinWeights[ face.d ];
  10442. skinWeightArray[ offset_skin ] = sw1.x;
  10443. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10444. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10445. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10446. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10447. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10448. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10449. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10450. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10451. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10452. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10453. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10454. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  10455. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  10456. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  10457. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  10458. // indices
  10459. si1 = obj_skinIndices[ face.a ];
  10460. si2 = obj_skinIndices[ face.b ];
  10461. si3 = obj_skinIndices[ face.c ];
  10462. si4 = obj_skinIndices[ face.d ];
  10463. skinIndexArray[ offset_skin ] = si1.x;
  10464. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10465. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10466. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10467. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10468. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10469. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10470. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10471. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10472. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10473. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10474. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10475. skinIndexArray[ offset_skin + 12 ] = si4.x;
  10476. skinIndexArray[ offset_skin + 13 ] = si4.y;
  10477. skinIndexArray[ offset_skin + 14 ] = si4.z;
  10478. skinIndexArray[ offset_skin + 15 ] = si4.w;
  10479. offset_skin += 16;
  10480. }
  10481. if ( offset_skin > 0 ) {
  10482. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10483. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  10484. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10485. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  10486. }
  10487. }
  10488. if ( dirtyColors && vertexColorType ) {
  10489. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10490. face = obj_faces[ chunk_faces3[ f ] ];
  10491. vertexColors = face.vertexColors;
  10492. faceColor = face.color;
  10493. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  10494. c1 = vertexColors[ 0 ];
  10495. c2 = vertexColors[ 1 ];
  10496. c3 = vertexColors[ 2 ];
  10497. } else {
  10498. c1 = faceColor;
  10499. c2 = faceColor;
  10500. c3 = faceColor;
  10501. }
  10502. colorArray[ offset_color ] = c1.r;
  10503. colorArray[ offset_color + 1 ] = c1.g;
  10504. colorArray[ offset_color + 2 ] = c1.b;
  10505. colorArray[ offset_color + 3 ] = c2.r;
  10506. colorArray[ offset_color + 4 ] = c2.g;
  10507. colorArray[ offset_color + 5 ] = c2.b;
  10508. colorArray[ offset_color + 6 ] = c3.r;
  10509. colorArray[ offset_color + 7 ] = c3.g;
  10510. colorArray[ offset_color + 8 ] = c3.b;
  10511. offset_color += 9;
  10512. }
  10513. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10514. face = obj_faces[ chunk_faces4[ f ] ];
  10515. vertexColors = face.vertexColors;
  10516. faceColor = face.color;
  10517. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  10518. c1 = vertexColors[ 0 ];
  10519. c2 = vertexColors[ 1 ];
  10520. c3 = vertexColors[ 2 ];
  10521. c4 = vertexColors[ 3 ];
  10522. } else {
  10523. c1 = faceColor;
  10524. c2 = faceColor;
  10525. c3 = faceColor;
  10526. c4 = faceColor;
  10527. }
  10528. colorArray[ offset_color ] = c1.r;
  10529. colorArray[ offset_color + 1 ] = c1.g;
  10530. colorArray[ offset_color + 2 ] = c1.b;
  10531. colorArray[ offset_color + 3 ] = c2.r;
  10532. colorArray[ offset_color + 4 ] = c2.g;
  10533. colorArray[ offset_color + 5 ] = c2.b;
  10534. colorArray[ offset_color + 6 ] = c3.r;
  10535. colorArray[ offset_color + 7 ] = c3.g;
  10536. colorArray[ offset_color + 8 ] = c3.b;
  10537. colorArray[ offset_color + 9 ] = c4.r;
  10538. colorArray[ offset_color + 10 ] = c4.g;
  10539. colorArray[ offset_color + 11 ] = c4.b;
  10540. offset_color += 12;
  10541. }
  10542. if ( offset_color > 0 ) {
  10543. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  10544. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10545. }
  10546. }
  10547. if ( dirtyTangents && geometry.hasTangents ) {
  10548. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10549. face = obj_faces[ chunk_faces3[ f ] ];
  10550. vertexTangents = face.vertexTangents;
  10551. t1 = vertexTangents[ 0 ];
  10552. t2 = vertexTangents[ 1 ];
  10553. t3 = vertexTangents[ 2 ];
  10554. tangentArray[ offset_tangent ] = t1.x;
  10555. tangentArray[ offset_tangent + 1 ] = t1.y;
  10556. tangentArray[ offset_tangent + 2 ] = t1.z;
  10557. tangentArray[ offset_tangent + 3 ] = t1.w;
  10558. tangentArray[ offset_tangent + 4 ] = t2.x;
  10559. tangentArray[ offset_tangent + 5 ] = t2.y;
  10560. tangentArray[ offset_tangent + 6 ] = t2.z;
  10561. tangentArray[ offset_tangent + 7 ] = t2.w;
  10562. tangentArray[ offset_tangent + 8 ] = t3.x;
  10563. tangentArray[ offset_tangent + 9 ] = t3.y;
  10564. tangentArray[ offset_tangent + 10 ] = t3.z;
  10565. tangentArray[ offset_tangent + 11 ] = t3.w;
  10566. offset_tangent += 12;
  10567. }
  10568. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10569. face = obj_faces[ chunk_faces4[ f ] ];
  10570. vertexTangents = face.vertexTangents;
  10571. t1 = vertexTangents[ 0 ];
  10572. t2 = vertexTangents[ 1 ];
  10573. t3 = vertexTangents[ 2 ];
  10574. t4 = vertexTangents[ 3 ];
  10575. tangentArray[ offset_tangent ] = t1.x;
  10576. tangentArray[ offset_tangent + 1 ] = t1.y;
  10577. tangentArray[ offset_tangent + 2 ] = t1.z;
  10578. tangentArray[ offset_tangent + 3 ] = t1.w;
  10579. tangentArray[ offset_tangent + 4 ] = t2.x;
  10580. tangentArray[ offset_tangent + 5 ] = t2.y;
  10581. tangentArray[ offset_tangent + 6 ] = t2.z;
  10582. tangentArray[ offset_tangent + 7 ] = t2.w;
  10583. tangentArray[ offset_tangent + 8 ] = t3.x;
  10584. tangentArray[ offset_tangent + 9 ] = t3.y;
  10585. tangentArray[ offset_tangent + 10 ] = t3.z;
  10586. tangentArray[ offset_tangent + 11 ] = t3.w;
  10587. tangentArray[ offset_tangent + 12 ] = t4.x;
  10588. tangentArray[ offset_tangent + 13 ] = t4.y;
  10589. tangentArray[ offset_tangent + 14 ] = t4.z;
  10590. tangentArray[ offset_tangent + 15 ] = t4.w;
  10591. offset_tangent += 16;
  10592. }
  10593. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  10594. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  10595. }
  10596. if ( dirtyNormals && normalType ) {
  10597. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10598. face = obj_faces[ chunk_faces3[ f ] ];
  10599. vertexNormals = face.vertexNormals;
  10600. faceNormal = face.normal;
  10601. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  10602. for ( i = 0; i < 3; i ++ ) {
  10603. vn = vertexNormals[ i ];
  10604. normalArray[ offset_normal ] = vn.x;
  10605. normalArray[ offset_normal + 1 ] = vn.y;
  10606. normalArray[ offset_normal + 2 ] = vn.z;
  10607. offset_normal += 3;
  10608. }
  10609. } else {
  10610. for ( i = 0; i < 3; i ++ ) {
  10611. normalArray[ offset_normal ] = faceNormal.x;
  10612. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10613. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10614. offset_normal += 3;
  10615. }
  10616. }
  10617. }
  10618. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10619. face = obj_faces[ chunk_faces4[ f ] ];
  10620. vertexNormals = face.vertexNormals;
  10621. faceNormal = face.normal;
  10622. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  10623. for ( i = 0; i < 4; i ++ ) {
  10624. vn = vertexNormals[ i ];
  10625. normalArray[ offset_normal ] = vn.x;
  10626. normalArray[ offset_normal + 1 ] = vn.y;
  10627. normalArray[ offset_normal + 2 ] = vn.z;
  10628. offset_normal += 3;
  10629. }
  10630. } else {
  10631. for ( i = 0; i < 4; i ++ ) {
  10632. normalArray[ offset_normal ] = faceNormal.x;
  10633. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10634. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10635. offset_normal += 3;
  10636. }
  10637. }
  10638. }
  10639. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  10640. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10641. }
  10642. if ( dirtyUvs && obj_uvs && uvType ) {
  10643. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10644. fi = chunk_faces3[ f ];
  10645. uv = obj_uvs[ fi ];
  10646. if ( uv === undefined ) continue;
  10647. for ( i = 0; i < 3; i ++ ) {
  10648. uvi = uv[ i ];
  10649. uvArray[ offset_uv ] = uvi.u;
  10650. uvArray[ offset_uv + 1 ] = uvi.v;
  10651. offset_uv += 2;
  10652. }
  10653. }
  10654. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10655. fi = chunk_faces4[ f ];
  10656. uv = obj_uvs[ fi ];
  10657. if ( uv === undefined ) continue;
  10658. for ( i = 0; i < 4; i ++ ) {
  10659. uvi = uv[ i ];
  10660. uvArray[ offset_uv ] = uvi.u;
  10661. uvArray[ offset_uv + 1 ] = uvi.v;
  10662. offset_uv += 2;
  10663. }
  10664. }
  10665. if ( offset_uv > 0 ) {
  10666. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  10667. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  10668. }
  10669. }
  10670. if ( dirtyUvs && obj_uvs2 && uvType ) {
  10671. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10672. fi = chunk_faces3[ f ];
  10673. uv2 = obj_uvs2[ fi ];
  10674. if ( uv2 === undefined ) continue;
  10675. for ( i = 0; i < 3; i ++ ) {
  10676. uv2i = uv2[ i ];
  10677. uv2Array[ offset_uv2 ] = uv2i.u;
  10678. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10679. offset_uv2 += 2;
  10680. }
  10681. }
  10682. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10683. fi = chunk_faces4[ f ];
  10684. uv2 = obj_uvs2[ fi ];
  10685. if ( uv2 === undefined ) continue;
  10686. for ( i = 0; i < 4; i ++ ) {
  10687. uv2i = uv2[ i ];
  10688. uv2Array[ offset_uv2 ] = uv2i.u;
  10689. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10690. offset_uv2 += 2;
  10691. }
  10692. }
  10693. if ( offset_uv2 > 0 ) {
  10694. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  10695. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  10696. }
  10697. }
  10698. if ( dirtyElements ) {
  10699. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10700. faceArray[ offset_face ] = vertexIndex;
  10701. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10702. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  10703. offset_face += 3;
  10704. lineArray[ offset_line ] = vertexIndex;
  10705. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10706. lineArray[ offset_line + 2 ] = vertexIndex;
  10707. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  10708. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10709. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10710. offset_line += 6;
  10711. vertexIndex += 3;
  10712. }
  10713. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10714. faceArray[ offset_face ] = vertexIndex;
  10715. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10716. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  10717. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  10718. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  10719. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  10720. offset_face += 6;
  10721. lineArray[ offset_line ] = vertexIndex;
  10722. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10723. lineArray[ offset_line + 2 ] = vertexIndex;
  10724. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  10725. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10726. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10727. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  10728. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  10729. offset_line += 8;
  10730. vertexIndex += 4;
  10731. }
  10732. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  10733. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  10734. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  10735. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  10736. }
  10737. if ( customAttributes ) {
  10738. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10739. customAttribute = customAttributes[ i ];
  10740. if ( ! customAttribute.__original.needsUpdate ) continue;
  10741. offset_custom = 0;
  10742. offset_customSrc = 0;
  10743. if ( customAttribute.size === 1 ) {
  10744. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10745. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10746. face = obj_faces[ chunk_faces3[ f ] ];
  10747. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10748. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10749. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10750. offset_custom += 3;
  10751. }
  10752. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10753. face = obj_faces[ chunk_faces4[ f ] ];
  10754. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10755. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10756. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10757. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  10758. offset_custom += 4;
  10759. }
  10760. } else if ( customAttribute.boundTo === "faces" ) {
  10761. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10762. value = customAttribute.value[ chunk_faces3[ f ] ];
  10763. customAttribute.array[ offset_custom ] = value;
  10764. customAttribute.array[ offset_custom + 1 ] = value;
  10765. customAttribute.array[ offset_custom + 2 ] = value;
  10766. offset_custom += 3;
  10767. }
  10768. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10769. value = customAttribute.value[ chunk_faces4[ f ] ];
  10770. customAttribute.array[ offset_custom ] = value;
  10771. customAttribute.array[ offset_custom + 1 ] = value;
  10772. customAttribute.array[ offset_custom + 2 ] = value;
  10773. customAttribute.array[ offset_custom + 3 ] = value;
  10774. offset_custom += 4;
  10775. }
  10776. }
  10777. } else if ( customAttribute.size === 2 ) {
  10778. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10779. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10780. face = obj_faces[ chunk_faces3[ f ] ];
  10781. v1 = customAttribute.value[ face.a ];
  10782. v2 = customAttribute.value[ face.b ];
  10783. v3 = customAttribute.value[ face.c ];
  10784. customAttribute.array[ offset_custom ] = v1.x;
  10785. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10786. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10787. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10788. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10789. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10790. offset_custom += 6;
  10791. }
  10792. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10793. face = obj_faces[ chunk_faces4[ f ] ];
  10794. v1 = customAttribute.value[ face.a ];
  10795. v2 = customAttribute.value[ face.b ];
  10796. v3 = customAttribute.value[ face.c ];
  10797. v4 = customAttribute.value[ face.d ];
  10798. customAttribute.array[ offset_custom ] = v1.x;
  10799. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10800. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10801. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10802. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10803. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10804. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10805. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10806. offset_custom += 8;
  10807. }
  10808. } else if ( customAttribute.boundTo === "faces" ) {
  10809. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10810. value = customAttribute.value[ chunk_faces3[ f ] ];
  10811. v1 = value;
  10812. v2 = value;
  10813. v3 = value;
  10814. customAttribute.array[ offset_custom ] = v1.x;
  10815. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10816. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10817. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10818. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10819. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10820. offset_custom += 6;
  10821. }
  10822. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10823. value = customAttribute.value[ chunk_faces4[ f ] ];
  10824. v1 = value;
  10825. v2 = value;
  10826. v3 = value;
  10827. v4 = value;
  10828. customAttribute.array[ offset_custom ] = v1.x;
  10829. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10830. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10831. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10832. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10833. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10834. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10835. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10836. offset_custom += 8;
  10837. }
  10838. }
  10839. } else if ( customAttribute.size === 3 ) {
  10840. var pp;
  10841. if ( customAttribute.type === "c" ) {
  10842. pp = [ "r", "g", "b" ];
  10843. } else {
  10844. pp = [ "x", "y", "z" ];
  10845. }
  10846. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10847. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10848. face = obj_faces[ chunk_faces3[ f ] ];
  10849. v1 = customAttribute.value[ face.a ];
  10850. v2 = customAttribute.value[ face.b ];
  10851. v3 = customAttribute.value[ face.c ];
  10852. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10853. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10854. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10855. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10856. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10857. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10858. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10859. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10860. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10861. offset_custom += 9;
  10862. }
  10863. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10864. face = obj_faces[ chunk_faces4[ f ] ];
  10865. v1 = customAttribute.value[ face.a ];
  10866. v2 = customAttribute.value[ face.b ];
  10867. v3 = customAttribute.value[ face.c ];
  10868. v4 = customAttribute.value[ face.d ];
  10869. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10870. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10871. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10872. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10873. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10874. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10875. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10876. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10877. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10878. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10879. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10880. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10881. offset_custom += 12;
  10882. }
  10883. } else if ( customAttribute.boundTo === "faces" ) {
  10884. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10885. value = customAttribute.value[ chunk_faces3[ f ] ];
  10886. v1 = value;
  10887. v2 = value;
  10888. v3 = value;
  10889. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10890. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10891. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10892. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10893. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10894. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10895. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10896. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10897. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10898. offset_custom += 9;
  10899. }
  10900. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10901. value = customAttribute.value[ chunk_faces4[ f ] ];
  10902. v1 = value;
  10903. v2 = value;
  10904. v3 = value;
  10905. v4 = value;
  10906. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10907. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10908. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10909. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10910. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10911. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10912. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10913. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10914. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10915. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10916. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10917. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10918. offset_custom += 12;
  10919. }
  10920. } else if ( customAttribute.boundTo === "faceVertices" ) {
  10921. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10922. value = customAttribute.value[ chunk_faces3[ f ] ];
  10923. v1 = value[ 0 ];
  10924. v2 = value[ 1 ];
  10925. v3 = value[ 2 ];
  10926. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10927. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10928. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10929. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10930. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10931. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10932. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10933. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10934. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10935. offset_custom += 9;
  10936. }
  10937. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10938. value = customAttribute.value[ chunk_faces4[ f ] ];
  10939. v1 = value[ 0 ];
  10940. v2 = value[ 1 ];
  10941. v3 = value[ 2 ];
  10942. v4 = value[ 3 ];
  10943. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10944. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10945. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10946. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10947. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10948. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10949. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10950. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10951. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10952. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10953. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10954. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10955. offset_custom += 12;
  10956. }
  10957. }
  10958. } else if ( customAttribute.size === 4 ) {
  10959. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10960. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10961. face = obj_faces[ chunk_faces3[ f ] ];
  10962. v1 = customAttribute.value[ face.a ];
  10963. v2 = customAttribute.value[ face.b ];
  10964. v3 = customAttribute.value[ face.c ];
  10965. customAttribute.array[ offset_custom ] = v1.x;
  10966. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10967. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10968. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10969. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10970. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10971. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10972. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10973. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10974. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10975. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10976. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10977. offset_custom += 12;
  10978. }
  10979. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10980. face = obj_faces[ chunk_faces4[ f ] ];
  10981. v1 = customAttribute.value[ face.a ];
  10982. v2 = customAttribute.value[ face.b ];
  10983. v3 = customAttribute.value[ face.c ];
  10984. v4 = customAttribute.value[ face.d ];
  10985. customAttribute.array[ offset_custom ] = v1.x;
  10986. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10987. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10988. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10989. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10990. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10991. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10992. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10993. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10994. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10995. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10996. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10997. customAttribute.array[ offset_custom + 12 ] = v4.x;
  10998. customAttribute.array[ offset_custom + 13 ] = v4.y;
  10999. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11000. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11001. offset_custom += 16;
  11002. }
  11003. } else if ( customAttribute.boundTo === "faces" ) {
  11004. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11005. value = customAttribute.value[ chunk_faces3[ f ] ];
  11006. v1 = value;
  11007. v2 = value;
  11008. v3 = value;
  11009. customAttribute.array[ offset_custom ] = v1.x;
  11010. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11011. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11012. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11013. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11014. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11015. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11016. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11017. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11018. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11019. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11020. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11021. offset_custom += 12;
  11022. }
  11023. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11024. value = customAttribute.value[ chunk_faces4[ f ] ];
  11025. v1 = value;
  11026. v2 = value;
  11027. v3 = value;
  11028. v4 = value;
  11029. customAttribute.array[ offset_custom ] = v1.x;
  11030. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11031. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11032. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11033. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11034. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11035. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11036. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11037. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11038. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11039. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11040. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11041. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11042. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11043. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11044. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11045. offset_custom += 16;
  11046. }
  11047. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11048. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11049. value = customAttribute.value[ chunk_faces3[ f ] ];
  11050. v1 = value[ 0 ];
  11051. v2 = value[ 1 ];
  11052. v3 = value[ 2 ];
  11053. customAttribute.array[ offset_custom ] = v1.x;
  11054. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11055. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11056. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11057. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11058. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11059. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11060. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11061. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11062. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11063. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11064. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11065. offset_custom += 12;
  11066. }
  11067. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11068. value = customAttribute.value[ chunk_faces4[ f ] ];
  11069. v1 = value[ 0 ];
  11070. v2 = value[ 1 ];
  11071. v3 = value[ 2 ];
  11072. v4 = value[ 3 ];
  11073. customAttribute.array[ offset_custom ] = v1.x;
  11074. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11075. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11076. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11077. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11078. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11079. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11080. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11081. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11082. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11083. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11084. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11085. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11086. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11087. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11088. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11089. offset_custom += 16;
  11090. }
  11091. }
  11092. }
  11093. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11094. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11095. }
  11096. }
  11097. if ( dispose ) {
  11098. delete geometryGroup.__inittedArrays;
  11099. delete geometryGroup.__colorArray;
  11100. delete geometryGroup.__normalArray;
  11101. delete geometryGroup.__tangentArray;
  11102. delete geometryGroup.__uvArray;
  11103. delete geometryGroup.__uv2Array;
  11104. delete geometryGroup.__faceArray;
  11105. delete geometryGroup.__vertexArray;
  11106. delete geometryGroup.__lineArray;
  11107. delete geometryGroup.__skinIndexArray;
  11108. delete geometryGroup.__skinWeightArray;
  11109. }
  11110. };
  11111. function setDirectBuffers ( geometry, hint, dispose ) {
  11112. var attributes = geometry.attributes;
  11113. var index = attributes[ "index" ];
  11114. var position = attributes[ "position" ];
  11115. var normal = attributes[ "normal" ];
  11116. var uv = attributes[ "uv" ];
  11117. var color = attributes[ "color" ];
  11118. var tangent = attributes[ "tangent" ];
  11119. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  11120. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11121. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  11122. }
  11123. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  11124. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11125. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  11126. }
  11127. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  11128. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11129. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  11130. }
  11131. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  11132. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11133. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  11134. }
  11135. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  11136. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11137. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  11138. }
  11139. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  11140. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11141. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  11142. }
  11143. if ( dispose ) {
  11144. for ( var i in geometry.attributes ) {
  11145. delete geometry.attributes[ i ].array;
  11146. }
  11147. }
  11148. };
  11149. // Buffer rendering
  11150. this.renderBufferImmediate = function ( object, program, material ) {
  11151. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  11152. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  11153. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  11154. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  11155. if ( object.hasPositions ) {
  11156. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  11157. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11158. _gl.enableVertexAttribArray( program.attributes.position );
  11159. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11160. }
  11161. if ( object.hasNormals ) {
  11162. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  11163. if ( material.shading === THREE.FlatShading ) {
  11164. var nx, ny, nz,
  11165. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  11166. normalArray,
  11167. i, il = object.count * 3;
  11168. for( i = 0; i < il; i += 9 ) {
  11169. normalArray = object.normalArray;
  11170. nax = normalArray[ i ];
  11171. nay = normalArray[ i + 1 ];
  11172. naz = normalArray[ i + 2 ];
  11173. nbx = normalArray[ i + 3 ];
  11174. nby = normalArray[ i + 4 ];
  11175. nbz = normalArray[ i + 5 ];
  11176. ncx = normalArray[ i + 6 ];
  11177. ncy = normalArray[ i + 7 ];
  11178. ncz = normalArray[ i + 8 ];
  11179. nx = ( nax + nbx + ncx ) / 3;
  11180. ny = ( nay + nby + ncy ) / 3;
  11181. nz = ( naz + nbz + ncz ) / 3;
  11182. normalArray[ i ] = nx;
  11183. normalArray[ i + 1 ] = ny;
  11184. normalArray[ i + 2 ] = nz;
  11185. normalArray[ i + 3 ] = nx;
  11186. normalArray[ i + 4 ] = ny;
  11187. normalArray[ i + 5 ] = nz;
  11188. normalArray[ i + 6 ] = nx;
  11189. normalArray[ i + 7 ] = ny;
  11190. normalArray[ i + 8 ] = nz;
  11191. }
  11192. }
  11193. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11194. _gl.enableVertexAttribArray( program.attributes.normal );
  11195. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11196. }
  11197. if ( object.hasUvs && material.map ) {
  11198. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  11199. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11200. _gl.enableVertexAttribArray( program.attributes.uv );
  11201. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11202. }
  11203. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  11204. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  11205. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11206. _gl.enableVertexAttribArray( program.attributes.color );
  11207. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11208. }
  11209. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11210. object.count = 0;
  11211. };
  11212. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  11213. if ( material.visible === false ) return;
  11214. var program, attributes, linewidth, primitives, a, attribute;
  11215. program = setProgram( camera, lights, fog, material, object );
  11216. attributes = program.attributes;
  11217. var updateBuffers = false,
  11218. wireframeBit = material.wireframe ? 1 : 0,
  11219. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11220. if ( geometryHash !== _currentGeometryGroupHash ) {
  11221. _currentGeometryGroupHash = geometryHash;
  11222. updateBuffers = true;
  11223. }
  11224. // render mesh
  11225. if ( object instanceof THREE.Mesh ) {
  11226. var offsets = geometry.offsets;
  11227. // if there is more than 1 chunk
  11228. // must set attribute pointers to use new offsets for each chunk
  11229. // even if geometry and materials didn't change
  11230. if ( offsets.length > 1 ) updateBuffers = true;
  11231. for ( var i = 0, il = offsets.length; i < il; ++ i ) {
  11232. var startIndex = offsets[ i ].index;
  11233. if ( updateBuffers ) {
  11234. // vertices
  11235. var position = geometry.attributes[ "position" ];
  11236. var positionSize = position.itemSize;
  11237. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11238. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  11239. // normals
  11240. var normal = geometry.attributes[ "normal" ];
  11241. if ( attributes.normal >= 0 && normal ) {
  11242. var normalSize = normal.itemSize;
  11243. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11244. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  11245. }
  11246. // uvs
  11247. var uv = geometry.attributes[ "uv" ];
  11248. if ( attributes.uv >= 0 && uv ) {
  11249. if ( uv.buffer ) {
  11250. var uvSize = uv.itemSize;
  11251. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11252. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  11253. _gl.enableVertexAttribArray( attributes.uv );
  11254. } else {
  11255. _gl.disableVertexAttribArray( attributes.uv );
  11256. }
  11257. }
  11258. // colors
  11259. var color = geometry.attributes[ "color" ];
  11260. if ( attributes.color >= 0 && color ) {
  11261. var colorSize = color.itemSize;
  11262. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11263. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  11264. }
  11265. // tangents
  11266. var tangent = geometry.attributes[ "tangent" ];
  11267. if ( attributes.tangent >= 0 && tangent ) {
  11268. var tangentSize = tangent.itemSize;
  11269. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11270. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  11271. }
  11272. // indices
  11273. var index = geometry.attributes[ "index" ];
  11274. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11275. }
  11276. // render indexed triangles
  11277. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  11278. _this.info.render.calls ++;
  11279. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  11280. _this.info.render.faces += offsets[ i ].count / 3;
  11281. }
  11282. // render particles
  11283. } else if ( object instanceof THREE.ParticleSystem ) {
  11284. if ( updateBuffers ) {
  11285. // vertices
  11286. var position = geometry.attributes[ "position" ];
  11287. var positionSize = position.itemSize;
  11288. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11289. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  11290. // colors
  11291. var color = geometry.attributes[ "color" ];
  11292. if ( attributes.color >= 0 && color ) {
  11293. var colorSize = color.itemSize;
  11294. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11295. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  11296. }
  11297. // render particles
  11298. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  11299. _this.info.render.calls ++;
  11300. _this.info.render.points += position.numItems / 3;
  11301. }
  11302. }
  11303. };
  11304. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  11305. if ( material.visible === false ) return;
  11306. var program, attributes, linewidth, primitives, a, attribute, i, il;
  11307. program = setProgram( camera, lights, fog, material, object );
  11308. attributes = program.attributes;
  11309. var updateBuffers = false,
  11310. wireframeBit = material.wireframe ? 1 : 0,
  11311. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11312. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  11313. _currentGeometryGroupHash = geometryGroupHash;
  11314. updateBuffers = true;
  11315. }
  11316. // vertices
  11317. if ( !material.morphTargets && attributes.position >= 0 ) {
  11318. if ( updateBuffers ) {
  11319. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11320. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11321. }
  11322. } else {
  11323. if ( object.morphTargetBase ) {
  11324. setupMorphTargets( material, geometryGroup, object );
  11325. }
  11326. }
  11327. if ( updateBuffers ) {
  11328. // custom attributes
  11329. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  11330. if ( geometryGroup.__webglCustomAttributesList ) {
  11331. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  11332. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  11333. if( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  11334. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  11335. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  11336. }
  11337. }
  11338. }
  11339. // colors
  11340. if ( attributes.color >= 0 ) {
  11341. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11342. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11343. }
  11344. // normals
  11345. if ( attributes.normal >= 0 ) {
  11346. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11347. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11348. }
  11349. // tangents
  11350. if ( attributes.tangent >= 0 ) {
  11351. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11352. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  11353. }
  11354. // uvs
  11355. if ( attributes.uv >= 0 ) {
  11356. if ( geometryGroup.__webglUVBuffer ) {
  11357. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11358. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11359. _gl.enableVertexAttribArray( attributes.uv );
  11360. } else {
  11361. _gl.disableVertexAttribArray( attributes.uv );
  11362. }
  11363. }
  11364. if ( attributes.uv2 >= 0 ) {
  11365. if ( geometryGroup.__webglUV2Buffer ) {
  11366. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11367. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  11368. _gl.enableVertexAttribArray( attributes.uv2 );
  11369. } else {
  11370. _gl.disableVertexAttribArray( attributes.uv2 );
  11371. }
  11372. }
  11373. if ( material.skinning &&
  11374. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  11375. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11376. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  11377. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11378. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  11379. }
  11380. }
  11381. // render mesh
  11382. if ( object instanceof THREE.Mesh ) {
  11383. // wireframe
  11384. if ( material.wireframe ) {
  11385. setLineWidth( material.wireframeLinewidth );
  11386. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11387. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  11388. // triangles
  11389. } else {
  11390. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11391. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  11392. }
  11393. _this.info.render.calls ++;
  11394. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  11395. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  11396. // render lines
  11397. } else if ( object instanceof THREE.Line ) {
  11398. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  11399. setLineWidth( material.linewidth );
  11400. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  11401. _this.info.render.calls ++;
  11402. // render particles
  11403. } else if ( object instanceof THREE.ParticleSystem ) {
  11404. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  11405. _this.info.render.calls ++;
  11406. _this.info.render.points += geometryGroup.__webglParticleCount;
  11407. // render ribbon
  11408. } else if ( object instanceof THREE.Ribbon ) {
  11409. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  11410. _this.info.render.calls ++;
  11411. }
  11412. };
  11413. function setupMorphTargets ( material, geometryGroup, object ) {
  11414. // set base
  11415. var attributes = material.program.attributes;
  11416. if ( object.morphTargetBase !== -1 ) {
  11417. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  11418. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11419. } else if ( attributes.position >= 0 ) {
  11420. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11421. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11422. }
  11423. if ( object.morphTargetForcedOrder.length ) {
  11424. // set forced order
  11425. var m = 0;
  11426. var order = object.morphTargetForcedOrder;
  11427. var influences = object.morphTargetInfluences;
  11428. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  11429. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  11430. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11431. if ( material.morphNormals ) {
  11432. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  11433. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11434. }
  11435. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  11436. m ++;
  11437. }
  11438. } else {
  11439. // find the most influencing
  11440. var influence, activeInfluenceIndices = [];
  11441. var influences = object.morphTargetInfluences;
  11442. var i, il = influences.length;
  11443. for ( i = 0; i < il; i ++ ) {
  11444. influence = influences[ i ];
  11445. if ( influence > 0 ) {
  11446. activeInfluenceIndices.push( [ i, influence ] );
  11447. }
  11448. }
  11449. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  11450. activeInfluenceIndices.sort( numericalSort );
  11451. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  11452. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  11453. activeInfluenceIndices.sort( numericalSort );
  11454. } else if ( activeInfluenceIndices.length === 0 ) {
  11455. activeInfluenceIndices.push( [ 0, 0 ] );
  11456. };
  11457. var influenceIndex, m = 0;
  11458. while ( m < material.numSupportedMorphTargets ) {
  11459. if ( activeInfluenceIndices[ m ] ) {
  11460. influenceIndex = activeInfluenceIndices[ m ][ 0 ];
  11461. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  11462. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11463. if ( material.morphNormals ) {
  11464. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  11465. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11466. }
  11467. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  11468. } else {
  11469. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11470. if ( material.morphNormals ) {
  11471. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11472. }
  11473. object.__webglMorphTargetInfluences[ m ] = 0;
  11474. }
  11475. m ++;
  11476. }
  11477. }
  11478. // load updated influences uniform
  11479. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  11480. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  11481. }
  11482. };
  11483. // Sorting
  11484. function painterSort ( a, b ) {
  11485. return b.z - a.z;
  11486. };
  11487. function numericalSort ( a, b ) {
  11488. return b[ 1 ] - a[ 1 ];
  11489. };
  11490. // Rendering
  11491. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11492. if ( camera instanceof THREE.Camera === false ) {
  11493. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  11494. return;
  11495. }
  11496. var i, il,
  11497. webglObject, object,
  11498. renderList,
  11499. lights = scene.__lights,
  11500. fog = scene.fog;
  11501. // reset caching for this frame
  11502. _currentMaterialId = -1;
  11503. _lightsNeedUpdate = true;
  11504. // update scene graph
  11505. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  11506. // update camera matrices and frustum
  11507. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  11508. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  11509. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  11510. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11511. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  11512. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  11513. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  11514. _frustum.setFromMatrix( _projScreenMatrix );
  11515. // update WebGL objects
  11516. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  11517. // custom render plugins (pre pass)
  11518. renderPlugins( this.renderPluginsPre, scene, camera );
  11519. //
  11520. _this.info.render.calls = 0;
  11521. _this.info.render.vertices = 0;
  11522. _this.info.render.faces = 0;
  11523. _this.info.render.points = 0;
  11524. this.setRenderTarget( renderTarget );
  11525. if ( this.autoClear || forceClear ) {
  11526. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  11527. }
  11528. // set matrices for regular objects (frustum culled)
  11529. renderList = scene.__webglObjects;
  11530. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11531. webglObject = renderList[ i ];
  11532. object = webglObject.object;
  11533. webglObject.render = false;
  11534. if ( object.visible ) {
  11535. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  11536. //object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11537. setupMatrices( object, camera );
  11538. unrollBufferMaterial( webglObject );
  11539. webglObject.render = true;
  11540. if ( this.sortObjects === true ) {
  11541. if ( object.renderDepth !== null ) {
  11542. webglObject.z = object.renderDepth;
  11543. } else {
  11544. _vector3.copy( object.matrixWorld.getPosition() );
  11545. _projScreenMatrix.multiplyVector3( _vector3 );
  11546. webglObject.z = _vector3.z;
  11547. }
  11548. }
  11549. }
  11550. }
  11551. }
  11552. if ( this.sortObjects ) {
  11553. renderList.sort( painterSort );
  11554. }
  11555. // set matrices for immediate objects
  11556. renderList = scene.__webglObjectsImmediate;
  11557. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11558. webglObject = renderList[ i ];
  11559. object = webglObject.object;
  11560. if ( object.visible ) {
  11561. /*
  11562. if ( object.matrixAutoUpdate ) {
  11563. object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11564. }
  11565. */
  11566. setupMatrices( object, camera );
  11567. unrollImmediateBufferMaterial( webglObject );
  11568. }
  11569. }
  11570. if ( scene.overrideMaterial ) {
  11571. var material = scene.overrideMaterial;
  11572. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11573. this.setDepthTest( material.depthTest );
  11574. this.setDepthWrite( material.depthWrite );
  11575. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11576. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  11577. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  11578. } else {
  11579. // opaque pass (front-to-back order)
  11580. this.setBlending( THREE.NormalBlending );
  11581. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false );
  11582. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false );
  11583. // transparent pass (back-to-front order)
  11584. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true );
  11585. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true );
  11586. }
  11587. // custom render plugins (post pass)
  11588. renderPlugins( this.renderPluginsPost, scene, camera );
  11589. // Generate mipmap if we're using any kind of mipmap filtering
  11590. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  11591. updateRenderTargetMipmap( renderTarget );
  11592. }
  11593. // Ensure depth buffer writing is enabled so it can be cleared on next render
  11594. this.setDepthTest( true );
  11595. this.setDepthWrite( true );
  11596. // _gl.finish();
  11597. };
  11598. function renderPlugins( plugins, scene, camera ) {
  11599. if ( ! plugins.length ) return;
  11600. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  11601. // reset state for plugin (to start from clean slate)
  11602. _currentProgram = null;
  11603. _currentCamera = null;
  11604. _oldBlending = -1;
  11605. _oldDepthTest = -1;
  11606. _oldDepthWrite = -1;
  11607. _oldDoubleSided = -1;
  11608. _oldFlipSided = -1;
  11609. _currentGeometryGroupHash = -1;
  11610. _currentMaterialId = -1;
  11611. _lightsNeedUpdate = true;
  11612. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  11613. // reset state after plugin (anything could have changed)
  11614. _currentProgram = null;
  11615. _currentCamera = null;
  11616. _oldBlending = -1;
  11617. _oldDepthTest = -1;
  11618. _oldDepthWrite = -1;
  11619. _oldDoubleSided = -1;
  11620. _oldFlipSided = -1;
  11621. _currentGeometryGroupHash = -1;
  11622. _currentMaterialId = -1;
  11623. _lightsNeedUpdate = true;
  11624. }
  11625. };
  11626. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11627. var webglObject, object, buffer, material, start, end, delta;
  11628. if ( reverse ) {
  11629. start = renderList.length - 1;
  11630. end = -1;
  11631. delta = -1;
  11632. } else {
  11633. start = 0;
  11634. end = renderList.length;
  11635. delta = 1;
  11636. }
  11637. for ( var i = start; i !== end; i += delta ) {
  11638. webglObject = renderList[ i ];
  11639. if ( webglObject.render ) {
  11640. object = webglObject.object;
  11641. buffer = webglObject.buffer;
  11642. if ( overrideMaterial ) {
  11643. material = overrideMaterial;
  11644. } else {
  11645. material = webglObject[ materialType ];
  11646. if ( ! material ) continue;
  11647. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11648. _this.setDepthTest( material.depthTest );
  11649. _this.setDepthWrite( material.depthWrite );
  11650. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11651. }
  11652. _this.setMaterialFaces( material );
  11653. if ( buffer instanceof THREE.BufferGeometry ) {
  11654. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  11655. } else {
  11656. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  11657. }
  11658. }
  11659. }
  11660. };
  11661. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11662. var webglObject, object, material, program;
  11663. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  11664. webglObject = renderList[ i ];
  11665. object = webglObject.object;
  11666. if ( object.visible ) {
  11667. if ( overrideMaterial ) {
  11668. material = overrideMaterial;
  11669. } else {
  11670. material = webglObject[ materialType ];
  11671. if ( ! material ) continue;
  11672. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11673. _this.setDepthTest( material.depthTest );
  11674. _this.setDepthWrite( material.depthWrite );
  11675. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11676. }
  11677. _this.renderImmediateObject( camera, lights, fog, material, object );
  11678. }
  11679. }
  11680. };
  11681. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  11682. var program = setProgram( camera, lights, fog, material, object );
  11683. _currentGeometryGroupHash = -1;
  11684. _this.setMaterialFaces( material );
  11685. if ( object.immediateRenderCallback ) {
  11686. object.immediateRenderCallback( program, _gl, _frustum );
  11687. } else {
  11688. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  11689. }
  11690. };
  11691. function unrollImmediateBufferMaterial ( globject ) {
  11692. var object = globject.object,
  11693. material = object.material;
  11694. if ( material.transparent ) {
  11695. globject.transparent = material;
  11696. globject.opaque = null;
  11697. } else {
  11698. globject.opaque = material;
  11699. globject.transparent = null;
  11700. }
  11701. };
  11702. function unrollBufferMaterial ( globject ) {
  11703. var object = globject.object,
  11704. buffer = globject.buffer,
  11705. material, materialIndex, meshMaterial;
  11706. meshMaterial = object.material;
  11707. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  11708. materialIndex = buffer.materialIndex;
  11709. if ( materialIndex >= 0 ) {
  11710. material = object.geometry.materials[ materialIndex ];
  11711. if ( material.transparent ) {
  11712. globject.transparent = material;
  11713. globject.opaque = null;
  11714. } else {
  11715. globject.opaque = material;
  11716. globject.transparent = null;
  11717. }
  11718. }
  11719. } else {
  11720. material = meshMaterial;
  11721. if ( material ) {
  11722. if ( material.transparent ) {
  11723. globject.transparent = material;
  11724. globject.opaque = null;
  11725. } else {
  11726. globject.opaque = material;
  11727. globject.transparent = null;
  11728. }
  11729. }
  11730. }
  11731. };
  11732. // Geometry splitting
  11733. function sortFacesByMaterial ( geometry ) {
  11734. var f, fl, face, materialIndex, vertices,
  11735. materialHash, groupHash,
  11736. hash_map = {};
  11737. var numMorphTargets = geometry.morphTargets.length;
  11738. var numMorphNormals = geometry.morphNormals.length;
  11739. geometry.geometryGroups = {};
  11740. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  11741. face = geometry.faces[ f ];
  11742. materialIndex = face.materialIndex;
  11743. materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;
  11744. if ( hash_map[ materialHash ] === undefined ) {
  11745. hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };
  11746. }
  11747. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11748. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11749. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11750. }
  11751. vertices = face instanceof THREE.Face3 ? 3 : 4;
  11752. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  11753. hash_map[ materialHash ].counter += 1;
  11754. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11755. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11756. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11757. }
  11758. }
  11759. if ( face instanceof THREE.Face3 ) {
  11760. geometry.geometryGroups[ groupHash ].faces3.push( f );
  11761. } else {
  11762. geometry.geometryGroups[ groupHash ].faces4.push( f );
  11763. }
  11764. geometry.geometryGroups[ groupHash ].vertices += vertices;
  11765. }
  11766. geometry.geometryGroupsList = [];
  11767. for ( var g in geometry.geometryGroups ) {
  11768. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  11769. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  11770. }
  11771. };
  11772. // Objects refresh
  11773. this.initWebGLObjects = function ( scene ) {
  11774. if ( !scene.__webglObjects ) {
  11775. scene.__webglObjects = [];
  11776. scene.__webglObjectsImmediate = [];
  11777. scene.__webglSprites = [];
  11778. scene.__webglFlares = [];
  11779. }
  11780. while ( scene.__objectsAdded.length ) {
  11781. addObject( scene.__objectsAdded[ 0 ], scene );
  11782. scene.__objectsAdded.splice( 0, 1 );
  11783. }
  11784. while ( scene.__objectsRemoved.length ) {
  11785. removeObject( scene.__objectsRemoved[ 0 ], scene );
  11786. scene.__objectsRemoved.splice( 0, 1 );
  11787. }
  11788. // update must be called after objects adding / removal
  11789. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  11790. updateObject( scene.__webglObjects[ o ].object );
  11791. }
  11792. };
  11793. // Objects adding
  11794. function addObject ( object, scene ) {
  11795. var g, geometry, geometryGroup;
  11796. if ( ! object.__webglInit ) {
  11797. object.__webglInit = true;
  11798. object._modelViewMatrix = new THREE.Matrix4();
  11799. object._normalMatrix = new THREE.Matrix3();
  11800. if ( object instanceof THREE.Mesh ) {
  11801. geometry = object.geometry;
  11802. if ( geometry instanceof THREE.Geometry ) {
  11803. if ( geometry.geometryGroups === undefined ) {
  11804. sortFacesByMaterial( geometry );
  11805. }
  11806. // create separate VBOs per geometry chunk
  11807. for ( g in geometry.geometryGroups ) {
  11808. geometryGroup = geometry.geometryGroups[ g ];
  11809. // initialise VBO on the first access
  11810. if ( ! geometryGroup.__webglVertexBuffer ) {
  11811. createMeshBuffers( geometryGroup );
  11812. initMeshBuffers( geometryGroup, object );
  11813. geometry.verticesNeedUpdate = true;
  11814. geometry.morphTargetsNeedUpdate = true;
  11815. geometry.elementsNeedUpdate = true;
  11816. geometry.uvsNeedUpdate = true;
  11817. geometry.normalsNeedUpdate = true;
  11818. geometry.tangentsNeedUpdate = true;
  11819. geometry.colorsNeedUpdate = true;
  11820. }
  11821. }
  11822. } else if ( geometry instanceof THREE.BufferGeometry ) {
  11823. initDirectBuffers( geometry );
  11824. }
  11825. } else if ( object instanceof THREE.Ribbon ) {
  11826. geometry = object.geometry;
  11827. if( ! geometry.__webglVertexBuffer ) {
  11828. createRibbonBuffers( geometry );
  11829. initRibbonBuffers( geometry );
  11830. geometry.verticesNeedUpdate = true;
  11831. geometry.colorsNeedUpdate = true;
  11832. }
  11833. } else if ( object instanceof THREE.Line ) {
  11834. geometry = object.geometry;
  11835. if( ! geometry.__webglVertexBuffer ) {
  11836. createLineBuffers( geometry );
  11837. initLineBuffers( geometry, object );
  11838. geometry.verticesNeedUpdate = true;
  11839. geometry.colorsNeedUpdate = true;
  11840. }
  11841. } else if ( object instanceof THREE.ParticleSystem ) {
  11842. geometry = object.geometry;
  11843. if ( ! geometry.__webglVertexBuffer ) {
  11844. if ( geometry instanceof THREE.Geometry ) {
  11845. createParticleBuffers( geometry );
  11846. initParticleBuffers( geometry, object );
  11847. geometry.verticesNeedUpdate = true;
  11848. geometry.colorsNeedUpdate = true;
  11849. } else if ( geometry instanceof THREE.BufferGeometry ) {
  11850. initDirectBuffers( geometry );
  11851. }
  11852. }
  11853. }
  11854. }
  11855. if ( ! object.__webglActive ) {
  11856. if ( object instanceof THREE.Mesh ) {
  11857. geometry = object.geometry;
  11858. if ( geometry instanceof THREE.BufferGeometry ) {
  11859. addBuffer( scene.__webglObjects, geometry, object );
  11860. } else {
  11861. for ( g in geometry.geometryGroups ) {
  11862. geometryGroup = geometry.geometryGroups[ g ];
  11863. addBuffer( scene.__webglObjects, geometryGroup, object );
  11864. }
  11865. }
  11866. } else if ( object instanceof THREE.Ribbon ||
  11867. object instanceof THREE.Line ||
  11868. object instanceof THREE.ParticleSystem ) {
  11869. geometry = object.geometry;
  11870. addBuffer( scene.__webglObjects, geometry, object );
  11871. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  11872. addBufferImmediate( scene.__webglObjectsImmediate, object );
  11873. } else if ( object instanceof THREE.Sprite ) {
  11874. scene.__webglSprites.push( object );
  11875. } else if ( object instanceof THREE.LensFlare ) {
  11876. scene.__webglFlares.push( object );
  11877. }
  11878. object.__webglActive = true;
  11879. }
  11880. };
  11881. function addBuffer ( objlist, buffer, object ) {
  11882. objlist.push(
  11883. {
  11884. buffer: buffer,
  11885. object: object,
  11886. opaque: null,
  11887. transparent: null
  11888. }
  11889. );
  11890. };
  11891. function addBufferImmediate ( objlist, object ) {
  11892. objlist.push(
  11893. {
  11894. object: object,
  11895. opaque: null,
  11896. transparent: null
  11897. }
  11898. );
  11899. };
  11900. // Objects updates
  11901. function updateObject ( object ) {
  11902. var geometry = object.geometry,
  11903. geometryGroup, customAttributesDirty, material;
  11904. if ( object instanceof THREE.Mesh ) {
  11905. if ( geometry instanceof THREE.BufferGeometry ) {
  11906. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  11907. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  11908. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  11909. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  11910. }
  11911. geometry.verticesNeedUpdate = false;
  11912. geometry.elementsNeedUpdate = false;
  11913. geometry.uvsNeedUpdate = false;
  11914. geometry.normalsNeedUpdate = false;
  11915. geometry.colorsNeedUpdate = false;
  11916. geometry.tangentsNeedUpdate = false;
  11917. } else {
  11918. // check all geometry groups
  11919. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  11920. geometryGroup = geometry.geometryGroupsList[ i ];
  11921. material = getBufferMaterial( object, geometryGroup );
  11922. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11923. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  11924. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  11925. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  11926. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  11927. }
  11928. }
  11929. geometry.verticesNeedUpdate = false;
  11930. geometry.morphTargetsNeedUpdate = false;
  11931. geometry.elementsNeedUpdate = false;
  11932. geometry.uvsNeedUpdate = false;
  11933. geometry.normalsNeedUpdate = false;
  11934. geometry.colorsNeedUpdate = false;
  11935. geometry.tangentsNeedUpdate = false;
  11936. material.attributes && clearCustomAttributes( material );
  11937. }
  11938. } else if ( object instanceof THREE.Ribbon ) {
  11939. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  11940. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  11941. }
  11942. geometry.verticesNeedUpdate = false;
  11943. geometry.colorsNeedUpdate = false;
  11944. } else if ( object instanceof THREE.Line ) {
  11945. material = getBufferMaterial( object, geometryGroup );
  11946. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11947. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || customAttributesDirty ) {
  11948. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  11949. }
  11950. geometry.verticesNeedUpdate = false;
  11951. geometry.colorsNeedUpdate = false;
  11952. material.attributes && clearCustomAttributes( material );
  11953. } else if ( object instanceof THREE.ParticleSystem ) {
  11954. if ( geometry instanceof THREE.BufferGeometry ) {
  11955. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  11956. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  11957. }
  11958. geometry.verticesNeedUpdate = false;
  11959. geometry.colorsNeedUpdate = false;
  11960. } else {
  11961. material = getBufferMaterial( object, geometryGroup );
  11962. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11963. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  11964. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  11965. }
  11966. geometry.verticesNeedUpdate = false;
  11967. geometry.colorsNeedUpdate = false;
  11968. material.attributes && clearCustomAttributes( material );
  11969. }
  11970. }
  11971. };
  11972. // Objects updates - custom attributes check
  11973. function areCustomAttributesDirty ( material ) {
  11974. for ( var a in material.attributes ) {
  11975. if ( material.attributes[ a ].needsUpdate ) return true;
  11976. }
  11977. return false;
  11978. };
  11979. function clearCustomAttributes ( material ) {
  11980. for ( var a in material.attributes ) {
  11981. material.attributes[ a ].needsUpdate = false;
  11982. }
  11983. };
  11984. // Objects removal
  11985. function removeObject ( object, scene ) {
  11986. if ( object instanceof THREE.Mesh ||
  11987. object instanceof THREE.ParticleSystem ||
  11988. object instanceof THREE.Ribbon ||
  11989. object instanceof THREE.Line ) {
  11990. removeInstances( scene.__webglObjects, object );
  11991. } else if ( object instanceof THREE.Sprite ) {
  11992. removeInstancesDirect( scene.__webglSprites, object );
  11993. } else if ( object instanceof THREE.LensFlare ) {
  11994. removeInstancesDirect( scene.__webglFlares, object );
  11995. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  11996. removeInstances( scene.__webglObjectsImmediate, object );
  11997. }
  11998. object.__webglActive = false;
  11999. };
  12000. function removeInstances ( objlist, object ) {
  12001. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12002. if ( objlist[ o ].object === object ) {
  12003. objlist.splice( o, 1 );
  12004. }
  12005. }
  12006. };
  12007. function removeInstancesDirect ( objlist, object ) {
  12008. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12009. if ( objlist[ o ] === object ) {
  12010. objlist.splice( o, 1 );
  12011. }
  12012. }
  12013. };
  12014. // Materials
  12015. this.initMaterial = function ( material, lights, fog, object ) {
  12016. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  12017. if ( material instanceof THREE.MeshDepthMaterial ) {
  12018. shaderID = 'depth';
  12019. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12020. shaderID = 'normal';
  12021. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  12022. shaderID = 'basic';
  12023. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12024. shaderID = 'lambert';
  12025. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12026. shaderID = 'phong';
  12027. } else if ( material instanceof THREE.LineBasicMaterial ) {
  12028. shaderID = 'basic';
  12029. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12030. shaderID = 'particle_basic';
  12031. }
  12032. if ( shaderID ) {
  12033. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  12034. }
  12035. // heuristics to create shader parameters according to lights in the scene
  12036. // (not to blow over maxLights budget)
  12037. maxLightCount = allocateLights( lights );
  12038. maxShadows = allocateShadows( lights );
  12039. maxBones = allocateBones( object );
  12040. parameters = {
  12041. map: !!material.map,
  12042. envMap: !!material.envMap,
  12043. lightMap: !!material.lightMap,
  12044. bumpMap: !!material.bumpMap,
  12045. normalMap: !!material.normalMap,
  12046. specularMap: !!material.specularMap,
  12047. vertexColors: material.vertexColors,
  12048. fog: fog,
  12049. useFog: material.fog,
  12050. sizeAttenuation: material.sizeAttenuation,
  12051. skinning: material.skinning,
  12052. maxBones: maxBones,
  12053. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  12054. boneTextureWidth: object && object.boneTextureWidth,
  12055. boneTextureHeight: object && object.boneTextureHeight,
  12056. morphTargets: material.morphTargets,
  12057. morphNormals: material.morphNormals,
  12058. maxMorphTargets: this.maxMorphTargets,
  12059. maxMorphNormals: this.maxMorphNormals,
  12060. maxDirLights: maxLightCount.directional,
  12061. maxPointLights: maxLightCount.point,
  12062. maxSpotLights: maxLightCount.spot,
  12063. maxHemiLights: maxLightCount.hemi,
  12064. maxShadows: maxShadows,
  12065. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  12066. shadowMapSoft: this.shadowMapSoft,
  12067. shadowMapDebug: this.shadowMapDebug,
  12068. shadowMapCascade: this.shadowMapCascade,
  12069. alphaTest: material.alphaTest,
  12070. metal: material.metal,
  12071. perPixel: material.perPixel,
  12072. wrapAround: material.wrapAround,
  12073. doubleSided: material.side === THREE.DoubleSide,
  12074. flipSided: material.side === THREE.BackSide
  12075. };
  12076. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  12077. var attributes = material.program.attributes;
  12078. if ( attributes.position >= 0 ) _gl.enableVertexAttribArray( attributes.position );
  12079. if ( attributes.color >= 0 ) _gl.enableVertexAttribArray( attributes.color );
  12080. if ( attributes.normal >= 0 ) _gl.enableVertexAttribArray( attributes.normal );
  12081. if ( attributes.tangent >= 0 ) _gl.enableVertexAttribArray( attributes.tangent );
  12082. if ( material.skinning &&
  12083. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12084. _gl.enableVertexAttribArray( attributes.skinIndex );
  12085. _gl.enableVertexAttribArray( attributes.skinWeight );
  12086. }
  12087. if ( material.attributes ) {
  12088. for ( a in material.attributes ) {
  12089. if( attributes[ a ] !== undefined && attributes[ a ] >= 0 ) _gl.enableVertexAttribArray( attributes[ a ] );
  12090. }
  12091. }
  12092. if ( material.morphTargets ) {
  12093. material.numSupportedMorphTargets = 0;
  12094. var id, base = "morphTarget";
  12095. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  12096. id = base + i;
  12097. if ( attributes[ id ] >= 0 ) {
  12098. _gl.enableVertexAttribArray( attributes[ id ] );
  12099. material.numSupportedMorphTargets ++;
  12100. }
  12101. }
  12102. }
  12103. if ( material.morphNormals ) {
  12104. material.numSupportedMorphNormals = 0;
  12105. var id, base = "morphNormal";
  12106. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  12107. id = base + i;
  12108. if ( attributes[ id ] >= 0 ) {
  12109. _gl.enableVertexAttribArray( attributes[ id ] );
  12110. material.numSupportedMorphNormals ++;
  12111. }
  12112. }
  12113. }
  12114. material.uniformsList = [];
  12115. for ( u in material.uniforms ) {
  12116. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  12117. }
  12118. };
  12119. function setMaterialShaders( material, shaders ) {
  12120. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  12121. material.vertexShader = shaders.vertexShader;
  12122. material.fragmentShader = shaders.fragmentShader;
  12123. };
  12124. function setProgram( camera, lights, fog, material, object ) {
  12125. _usedTextureUnits = 0;
  12126. if ( material.needsUpdate ) {
  12127. if ( material.program ) _this.deallocateMaterial( material );
  12128. _this.initMaterial( material, lights, fog, object );
  12129. material.needsUpdate = false;
  12130. }
  12131. if ( material.morphTargets ) {
  12132. if ( ! object.__webglMorphTargetInfluences ) {
  12133. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  12134. }
  12135. }
  12136. var refreshMaterial = false;
  12137. var program = material.program,
  12138. p_uniforms = program.uniforms,
  12139. m_uniforms = material.uniforms;
  12140. if ( program !== _currentProgram ) {
  12141. _gl.useProgram( program );
  12142. _currentProgram = program;
  12143. refreshMaterial = true;
  12144. }
  12145. if ( material.id !== _currentMaterialId ) {
  12146. _currentMaterialId = material.id;
  12147. refreshMaterial = true;
  12148. }
  12149. if ( refreshMaterial || camera !== _currentCamera ) {
  12150. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  12151. if ( camera !== _currentCamera ) _currentCamera = camera;
  12152. }
  12153. // skinning uniforms must be set even if material didn't change
  12154. // auto-setting of texture unit for bone texture must go before other textures
  12155. // not sure why, but otherwise weird things happen
  12156. if ( material.skinning ) {
  12157. if ( _supportsBoneTextures && object.useVertexTexture ) {
  12158. if ( p_uniforms.boneTexture !== null ) {
  12159. var textureUnit = getTextureUnit();
  12160. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  12161. _this.setTexture( object.boneTexture, textureUnit );
  12162. }
  12163. } else {
  12164. if ( p_uniforms.boneGlobalMatrices !== null ) {
  12165. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  12166. }
  12167. }
  12168. }
  12169. if ( refreshMaterial ) {
  12170. // refresh uniforms common to several materials
  12171. if ( fog && material.fog ) {
  12172. refreshUniformsFog( m_uniforms, fog );
  12173. }
  12174. if ( material instanceof THREE.MeshPhongMaterial ||
  12175. material instanceof THREE.MeshLambertMaterial ||
  12176. material.lights ) {
  12177. if ( _lightsNeedUpdate ) {
  12178. setupLights( program, lights );
  12179. _lightsNeedUpdate = false;
  12180. }
  12181. refreshUniformsLights( m_uniforms, _lights );
  12182. }
  12183. if ( material instanceof THREE.MeshBasicMaterial ||
  12184. material instanceof THREE.MeshLambertMaterial ||
  12185. material instanceof THREE.MeshPhongMaterial ) {
  12186. refreshUniformsCommon( m_uniforms, material );
  12187. }
  12188. // refresh single material specific uniforms
  12189. if ( material instanceof THREE.LineBasicMaterial ) {
  12190. refreshUniformsLine( m_uniforms, material );
  12191. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12192. refreshUniformsParticle( m_uniforms, material );
  12193. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12194. refreshUniformsPhong( m_uniforms, material );
  12195. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12196. refreshUniformsLambert( m_uniforms, material );
  12197. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  12198. m_uniforms.mNear.value = camera.near;
  12199. m_uniforms.mFar.value = camera.far;
  12200. m_uniforms.opacity.value = material.opacity;
  12201. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12202. m_uniforms.opacity.value = material.opacity;
  12203. }
  12204. if ( object.receiveShadow && ! material._shadowPass ) {
  12205. refreshUniformsShadow( m_uniforms, lights );
  12206. }
  12207. // load common uniforms
  12208. loadUniformsGeneric( program, material.uniformsList );
  12209. // load material specific uniforms
  12210. // (shader material also gets them for the sake of genericity)
  12211. if ( material instanceof THREE.ShaderMaterial ||
  12212. material instanceof THREE.MeshPhongMaterial ||
  12213. material.envMap ) {
  12214. if ( p_uniforms.cameraPosition !== null ) {
  12215. var position = camera.matrixWorld.getPosition();
  12216. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  12217. }
  12218. }
  12219. if ( material instanceof THREE.MeshPhongMaterial ||
  12220. material instanceof THREE.MeshLambertMaterial ||
  12221. material instanceof THREE.ShaderMaterial ||
  12222. material.skinning ) {
  12223. if ( p_uniforms.viewMatrix !== null ) {
  12224. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray );
  12225. }
  12226. }
  12227. }
  12228. loadUniformsMatrices( p_uniforms, object );
  12229. if ( p_uniforms.modelMatrix !== null ) {
  12230. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  12231. }
  12232. return program;
  12233. };
  12234. // Uniforms (refresh uniforms objects)
  12235. function refreshUniformsCommon ( uniforms, material ) {
  12236. uniforms.opacity.value = material.opacity;
  12237. if ( _this.gammaInput ) {
  12238. uniforms.diffuse.value.copyGammaToLinear( material.color );
  12239. } else {
  12240. uniforms.diffuse.value = material.color;
  12241. }
  12242. uniforms.map.value = material.map;
  12243. uniforms.lightMap.value = material.lightMap;
  12244. uniforms.specularMap.value = material.specularMap;
  12245. if ( material.bumpMap ) {
  12246. uniforms.bumpMap.value = material.bumpMap;
  12247. uniforms.bumpScale.value = material.bumpScale;
  12248. }
  12249. if ( material.normalMap ) {
  12250. uniforms.normalMap.value = material.normalMap;
  12251. uniforms.normalScale.value.copy( material.normalScale );
  12252. }
  12253. // uv repeat and offset setting priorities
  12254. // 1. color map
  12255. // 2. specular map
  12256. // 3. normal map
  12257. // 4. bump map
  12258. var uvScaleMap;
  12259. if ( material.map ) {
  12260. uvScaleMap = material.map;
  12261. } else if ( material.specularMap ) {
  12262. uvScaleMap = material.specularMap;
  12263. } else if ( material.normalMap ) {
  12264. uvScaleMap = material.normalMap;
  12265. } else if ( material.bumpMap ) {
  12266. uvScaleMap = material.bumpMap;
  12267. }
  12268. if ( uvScaleMap !== undefined ) {
  12269. var offset = uvScaleMap.offset;
  12270. var repeat = uvScaleMap.repeat;
  12271. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12272. }
  12273. uniforms.envMap.value = material.envMap;
  12274. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  12275. if ( _this.gammaInput ) {
  12276. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  12277. uniforms.reflectivity.value = material.reflectivity;
  12278. } else {
  12279. uniforms.reflectivity.value = material.reflectivity;
  12280. }
  12281. uniforms.refractionRatio.value = material.refractionRatio;
  12282. uniforms.combine.value = material.combine;
  12283. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  12284. };
  12285. function refreshUniformsLine ( uniforms, material ) {
  12286. uniforms.diffuse.value = material.color;
  12287. uniforms.opacity.value = material.opacity;
  12288. };
  12289. function refreshUniformsParticle ( uniforms, material ) {
  12290. uniforms.psColor.value = material.color;
  12291. uniforms.opacity.value = material.opacity;
  12292. uniforms.size.value = material.size;
  12293. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  12294. uniforms.map.value = material.map;
  12295. };
  12296. function refreshUniformsFog ( uniforms, fog ) {
  12297. uniforms.fogColor.value = fog.color;
  12298. if ( fog instanceof THREE.Fog ) {
  12299. uniforms.fogNear.value = fog.near;
  12300. uniforms.fogFar.value = fog.far;
  12301. } else if ( fog instanceof THREE.FogExp2 ) {
  12302. uniforms.fogDensity.value = fog.density;
  12303. }
  12304. };
  12305. function refreshUniformsPhong ( uniforms, material ) {
  12306. uniforms.shininess.value = material.shininess;
  12307. if ( _this.gammaInput ) {
  12308. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12309. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12310. uniforms.specular.value.copyGammaToLinear( material.specular );
  12311. } else {
  12312. uniforms.ambient.value = material.ambient;
  12313. uniforms.emissive.value = material.emissive;
  12314. uniforms.specular.value = material.specular;
  12315. }
  12316. if ( material.wrapAround ) {
  12317. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12318. }
  12319. };
  12320. function refreshUniformsLambert ( uniforms, material ) {
  12321. if ( _this.gammaInput ) {
  12322. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12323. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12324. } else {
  12325. uniforms.ambient.value = material.ambient;
  12326. uniforms.emissive.value = material.emissive;
  12327. }
  12328. if ( material.wrapAround ) {
  12329. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12330. }
  12331. };
  12332. function refreshUniformsLights ( uniforms, lights ) {
  12333. uniforms.ambientLightColor.value = lights.ambient;
  12334. uniforms.directionalLightColor.value = lights.directional.colors;
  12335. uniforms.directionalLightDirection.value = lights.directional.positions;
  12336. uniforms.pointLightColor.value = lights.point.colors;
  12337. uniforms.pointLightPosition.value = lights.point.positions;
  12338. uniforms.pointLightDistance.value = lights.point.distances;
  12339. uniforms.spotLightColor.value = lights.spot.colors;
  12340. uniforms.spotLightPosition.value = lights.spot.positions;
  12341. uniforms.spotLightDistance.value = lights.spot.distances;
  12342. uniforms.spotLightDirection.value = lights.spot.directions;
  12343. uniforms.spotLightAngle.value = lights.spot.angles;
  12344. uniforms.spotLightExponent.value = lights.spot.exponents;
  12345. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  12346. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  12347. uniforms.hemisphereLightPosition.value = lights.hemi.positions;
  12348. };
  12349. function refreshUniformsShadow ( uniforms, lights ) {
  12350. if ( uniforms.shadowMatrix ) {
  12351. var j = 0;
  12352. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  12353. var light = lights[ i ];
  12354. if ( ! light.castShadow ) continue;
  12355. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  12356. uniforms.shadowMap.value[ j ] = light.shadowMap;
  12357. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  12358. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  12359. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  12360. uniforms.shadowBias.value[ j ] = light.shadowBias;
  12361. j ++;
  12362. }
  12363. }
  12364. }
  12365. };
  12366. // Uniforms (load to GPU)
  12367. function loadUniformsMatrices ( uniforms, object ) {
  12368. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  12369. if ( uniforms.normalMatrix ) {
  12370. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  12371. }
  12372. };
  12373. function getTextureUnit() {
  12374. var textureUnit = _usedTextureUnits;
  12375. if ( textureUnit >= _maxTextures ) {
  12376. console.warn( "Trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  12377. }
  12378. _usedTextureUnits += 1;
  12379. return textureUnit;
  12380. };
  12381. function loadUniformsGeneric ( program, uniforms ) {
  12382. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  12383. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  12384. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  12385. if ( !location ) continue;
  12386. uniform = uniforms[ j ][ 0 ];
  12387. type = uniform.type;
  12388. value = uniform.value;
  12389. if ( type === "i" ) { // single integer
  12390. _gl.uniform1i( location, value );
  12391. } else if ( type === "f" ) { // single float
  12392. _gl.uniform1f( location, value );
  12393. } else if ( type === "v2" ) { // single THREE.Vector2
  12394. _gl.uniform2f( location, value.x, value.y );
  12395. } else if ( type === "v3" ) { // single THREE.Vector3
  12396. _gl.uniform3f( location, value.x, value.y, value.z );
  12397. } else if ( type === "v4" ) { // single THREE.Vector4
  12398. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  12399. } else if ( type === "c" ) { // single THREE.Color
  12400. _gl.uniform3f( location, value.r, value.g, value.b );
  12401. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  12402. _gl.uniform1iv( location, value );
  12403. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  12404. _gl.uniform3iv( location, value );
  12405. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  12406. _gl.uniform1fv( location, value );
  12407. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  12408. _gl.uniform3fv( location, value );
  12409. } else if ( type === "v2v" ) { // array of THREE.Vector2
  12410. if ( uniform._array === undefined ) {
  12411. uniform._array = new Float32Array( 2 * value.length );
  12412. }
  12413. for ( i = 0, il = value.length; i < il; i ++ ) {
  12414. offset = i * 2;
  12415. uniform._array[ offset ] = value[ i ].x;
  12416. uniform._array[ offset + 1 ] = value[ i ].y;
  12417. }
  12418. _gl.uniform2fv( location, uniform._array );
  12419. } else if ( type === "v3v" ) { // array of THREE.Vector3
  12420. if ( uniform._array === undefined ) {
  12421. uniform._array = new Float32Array( 3 * value.length );
  12422. }
  12423. for ( i = 0, il = value.length; i < il; i ++ ) {
  12424. offset = i * 3;
  12425. uniform._array[ offset ] = value[ i ].x;
  12426. uniform._array[ offset + 1 ] = value[ i ].y;
  12427. uniform._array[ offset + 2 ] = value[ i ].z;
  12428. }
  12429. _gl.uniform3fv( location, uniform._array );
  12430. } else if ( type === "v4v" ) { // array of THREE.Vector4
  12431. if ( uniform._array === undefined ) {
  12432. uniform._array = new Float32Array( 4 * value.length );
  12433. }
  12434. for ( i = 0, il = value.length; i < il; i ++ ) {
  12435. offset = i * 4;
  12436. uniform._array[ offset ] = value[ i ].x;
  12437. uniform._array[ offset + 1 ] = value[ i ].y;
  12438. uniform._array[ offset + 2 ] = value[ i ].z;
  12439. uniform._array[ offset + 3 ] = value[ i ].w;
  12440. }
  12441. _gl.uniform4fv( location, uniform._array );
  12442. } else if ( type === "m4") { // single THREE.Matrix4
  12443. if ( uniform._array === undefined ) {
  12444. uniform._array = new Float32Array( 16 );
  12445. }
  12446. value.flattenToArray( uniform._array );
  12447. _gl.uniformMatrix4fv( location, false, uniform._array );
  12448. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  12449. if ( uniform._array === undefined ) {
  12450. uniform._array = new Float32Array( 16 * value.length );
  12451. }
  12452. for ( i = 0, il = value.length; i < il; i ++ ) {
  12453. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  12454. }
  12455. _gl.uniformMatrix4fv( location, false, uniform._array );
  12456. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  12457. texture = value;
  12458. textureUnit = getTextureUnit();
  12459. _gl.uniform1i( location, textureUnit );
  12460. if ( !texture ) continue;
  12461. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  12462. setCubeTexture( texture, textureUnit );
  12463. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  12464. setCubeTextureDynamic( texture, textureUnit );
  12465. } else {
  12466. _this.setTexture( texture, textureUnit );
  12467. }
  12468. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  12469. if ( uniform._array === undefined ) {
  12470. uniform._array = [];
  12471. }
  12472. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12473. uniform._array[ i ] = getTextureUnit();
  12474. }
  12475. _gl.uniform1iv( location, uniform._array );
  12476. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12477. texture = uniform.value[ i ];
  12478. textureUnit = uniform._array[ i ];
  12479. if ( !texture ) continue;
  12480. _this.setTexture( texture, textureUnit );
  12481. }
  12482. }
  12483. }
  12484. };
  12485. function setupMatrices ( object, camera ) {
  12486. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  12487. object._normalMatrix.getInverse( object._modelViewMatrix );
  12488. object._normalMatrix.transpose();
  12489. };
  12490. //
  12491. function setColorGamma( array, offset, color, intensitySq ) {
  12492. array[ offset ] = color.r * color.r * intensitySq;
  12493. array[ offset + 1 ] = color.g * color.g * intensitySq;
  12494. array[ offset + 2 ] = color.b * color.b * intensitySq;
  12495. };
  12496. function setColorLinear( array, offset, color, intensity ) {
  12497. array[ offset ] = color.r * intensity;
  12498. array[ offset + 1 ] = color.g * intensity;
  12499. array[ offset + 2 ] = color.b * intensity;
  12500. };
  12501. function setupLights ( program, lights ) {
  12502. var l, ll, light, n,
  12503. r = 0, g = 0, b = 0,
  12504. color, skyColor, groundColor,
  12505. intensity, intensitySq,
  12506. position,
  12507. distance,
  12508. zlights = _lights,
  12509. dirColors = zlights.directional.colors,
  12510. dirPositions = zlights.directional.positions,
  12511. pointColors = zlights.point.colors,
  12512. pointPositions = zlights.point.positions,
  12513. pointDistances = zlights.point.distances,
  12514. spotColors = zlights.spot.colors,
  12515. spotPositions = zlights.spot.positions,
  12516. spotDistances = zlights.spot.distances,
  12517. spotDirections = zlights.spot.directions,
  12518. spotAngles = zlights.spot.angles,
  12519. spotExponents = zlights.spot.exponents,
  12520. hemiSkyColors = zlights.hemi.skyColors,
  12521. hemiGroundColors = zlights.hemi.groundColors,
  12522. hemiPositions = zlights.hemi.positions,
  12523. dirLength = 0,
  12524. pointLength = 0,
  12525. spotLength = 0,
  12526. hemiLength = 0,
  12527. dirOffset = 0,
  12528. pointOffset = 0,
  12529. spotOffset = 0,
  12530. hemiOffset = 0;
  12531. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12532. light = lights[ l ];
  12533. if ( light.onlyShadow || ! light.visible ) continue;
  12534. color = light.color;
  12535. intensity = light.intensity;
  12536. distance = light.distance;
  12537. if ( light instanceof THREE.AmbientLight ) {
  12538. if ( _this.gammaInput ) {
  12539. r += color.r * color.r;
  12540. g += color.g * color.g;
  12541. b += color.b * color.b;
  12542. } else {
  12543. r += color.r;
  12544. g += color.g;
  12545. b += color.b;
  12546. }
  12547. } else if ( light instanceof THREE.DirectionalLight ) {
  12548. dirOffset = dirLength * 3;
  12549. if ( _this.gammaInput ) {
  12550. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  12551. } else {
  12552. setColorLinear( dirColors, dirOffset, color, intensity );
  12553. }
  12554. _direction.copy( light.matrixWorld.getPosition() );
  12555. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12556. _direction.normalize();
  12557. dirPositions[ dirOffset ] = _direction.x;
  12558. dirPositions[ dirOffset + 1 ] = _direction.y;
  12559. dirPositions[ dirOffset + 2 ] = _direction.z;
  12560. dirLength += 1;
  12561. } else if( light instanceof THREE.PointLight ) {
  12562. pointOffset = pointLength * 3;
  12563. if ( _this.gammaInput ) {
  12564. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  12565. } else {
  12566. setColorLinear( pointColors, pointOffset, color, intensity );
  12567. }
  12568. position = light.matrixWorld.getPosition();
  12569. pointPositions[ pointOffset ] = position.x;
  12570. pointPositions[ pointOffset + 1 ] = position.y;
  12571. pointPositions[ pointOffset + 2 ] = position.z;
  12572. pointDistances[ pointLength ] = distance;
  12573. pointLength += 1;
  12574. } else if( light instanceof THREE.SpotLight ) {
  12575. spotOffset = spotLength * 3;
  12576. if ( _this.gammaInput ) {
  12577. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  12578. } else {
  12579. setColorLinear( spotColors, spotOffset, color, intensity );
  12580. }
  12581. position = light.matrixWorld.getPosition();
  12582. spotPositions[ spotOffset ] = position.x;
  12583. spotPositions[ spotOffset + 1 ] = position.y;
  12584. spotPositions[ spotOffset + 2 ] = position.z;
  12585. spotDistances[ spotLength ] = distance;
  12586. _direction.copy( position );
  12587. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12588. _direction.normalize();
  12589. spotDirections[ spotOffset ] = _direction.x;
  12590. spotDirections[ spotOffset + 1 ] = _direction.y;
  12591. spotDirections[ spotOffset + 2 ] = _direction.z;
  12592. spotAngles[ spotLength ] = Math.cos( light.angle );
  12593. spotExponents[ spotLength ] = light.exponent;
  12594. spotLength += 1;
  12595. } else if ( light instanceof THREE.HemisphereLight ) {
  12596. skyColor = light.color;
  12597. groundColor = light.groundColor;
  12598. hemiOffset = hemiLength * 3;
  12599. if ( _this.gammaInput ) {
  12600. intensitySq = intensity * intensity;
  12601. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  12602. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  12603. } else {
  12604. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  12605. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  12606. }
  12607. position = light.matrixWorld.getPosition();
  12608. hemiPositions[ hemiOffset ] = position.x;
  12609. hemiPositions[ hemiOffset + 1 ] = position.y;
  12610. hemiPositions[ hemiOffset + 2 ] = position.z;
  12611. hemiLength += 1;
  12612. }
  12613. }
  12614. // null eventual remains from removed lights
  12615. // (this is to avoid if in shader)
  12616. for ( l = dirLength * 3, ll = dirColors.length; l < ll; l ++ ) dirColors[ l ] = 0.0;
  12617. for ( l = pointLength * 3, ll = pointColors.length; l < ll; l ++ ) pointColors[ l ] = 0.0;
  12618. for ( l = spotLength * 3, ll = spotColors.length; l < ll; l ++ ) spotColors[ l ] = 0.0;
  12619. for ( l = hemiLength * 3, ll = hemiSkyColors.length; l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  12620. for ( l = hemiLength * 3, ll = hemiGroundColors.length; l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  12621. zlights.directional.length = dirLength;
  12622. zlights.point.length = pointLength;
  12623. zlights.spot.length = spotLength;
  12624. zlights.hemi.length = hemiLength;
  12625. zlights.ambient[ 0 ] = r;
  12626. zlights.ambient[ 1 ] = g;
  12627. zlights.ambient[ 2 ] = b;
  12628. };
  12629. // GL state setting
  12630. this.setFaceCulling = function ( cullFace, frontFace ) {
  12631. if ( cullFace ) {
  12632. if ( !frontFace || frontFace === "ccw" ) {
  12633. _gl.frontFace( _gl.CCW );
  12634. } else {
  12635. _gl.frontFace( _gl.CW );
  12636. }
  12637. if( cullFace === "back" ) {
  12638. _gl.cullFace( _gl.BACK );
  12639. } else if( cullFace === "front" ) {
  12640. _gl.cullFace( _gl.FRONT );
  12641. } else {
  12642. _gl.cullFace( _gl.FRONT_AND_BACK );
  12643. }
  12644. _gl.enable( _gl.CULL_FACE );
  12645. } else {
  12646. _gl.disable( _gl.CULL_FACE );
  12647. }
  12648. };
  12649. this.setMaterialFaces = function ( material ) {
  12650. var doubleSided = material.side === THREE.DoubleSide;
  12651. var flipSided = material.side === THREE.BackSide;
  12652. if ( _oldDoubleSided !== doubleSided ) {
  12653. if ( doubleSided ) {
  12654. _gl.disable( _gl.CULL_FACE );
  12655. } else {
  12656. _gl.enable( _gl.CULL_FACE );
  12657. }
  12658. _oldDoubleSided = doubleSided;
  12659. }
  12660. if ( _oldFlipSided !== flipSided ) {
  12661. if ( flipSided ) {
  12662. _gl.frontFace( _gl.CW );
  12663. } else {
  12664. _gl.frontFace( _gl.CCW );
  12665. }
  12666. _oldFlipSided = flipSided;
  12667. }
  12668. };
  12669. this.setDepthTest = function ( depthTest ) {
  12670. if ( _oldDepthTest !== depthTest ) {
  12671. if ( depthTest ) {
  12672. _gl.enable( _gl.DEPTH_TEST );
  12673. } else {
  12674. _gl.disable( _gl.DEPTH_TEST );
  12675. }
  12676. _oldDepthTest = depthTest;
  12677. }
  12678. };
  12679. this.setDepthWrite = function ( depthWrite ) {
  12680. if ( _oldDepthWrite !== depthWrite ) {
  12681. _gl.depthMask( depthWrite );
  12682. _oldDepthWrite = depthWrite;
  12683. }
  12684. };
  12685. function setLineWidth ( width ) {
  12686. if ( width !== _oldLineWidth ) {
  12687. _gl.lineWidth( width );
  12688. _oldLineWidth = width;
  12689. }
  12690. };
  12691. function setPolygonOffset ( polygonoffset, factor, units ) {
  12692. if ( _oldPolygonOffset !== polygonoffset ) {
  12693. if ( polygonoffset ) {
  12694. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  12695. } else {
  12696. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  12697. }
  12698. _oldPolygonOffset = polygonoffset;
  12699. }
  12700. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  12701. _gl.polygonOffset( factor, units );
  12702. _oldPolygonOffsetFactor = factor;
  12703. _oldPolygonOffsetUnits = units;
  12704. }
  12705. };
  12706. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  12707. if ( blending !== _oldBlending ) {
  12708. if ( blending === THREE.NoBlending ) {
  12709. _gl.disable( _gl.BLEND );
  12710. } else if ( blending === THREE.AdditiveBlending ) {
  12711. _gl.enable( _gl.BLEND );
  12712. _gl.blendEquation( _gl.FUNC_ADD );
  12713. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  12714. } else if ( blending === THREE.SubtractiveBlending ) {
  12715. // TODO: Find blendFuncSeparate() combination
  12716. _gl.enable( _gl.BLEND );
  12717. _gl.blendEquation( _gl.FUNC_ADD );
  12718. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  12719. } else if ( blending === THREE.MultiplyBlending ) {
  12720. // TODO: Find blendFuncSeparate() combination
  12721. _gl.enable( _gl.BLEND );
  12722. _gl.blendEquation( _gl.FUNC_ADD );
  12723. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  12724. } else if ( blending === THREE.CustomBlending ) {
  12725. _gl.enable( _gl.BLEND );
  12726. } else {
  12727. _gl.enable( _gl.BLEND );
  12728. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  12729. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  12730. }
  12731. _oldBlending = blending;
  12732. }
  12733. if ( blending === THREE.CustomBlending ) {
  12734. if ( blendEquation !== _oldBlendEquation ) {
  12735. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  12736. _oldBlendEquation = blendEquation;
  12737. }
  12738. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  12739. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  12740. _oldBlendSrc = blendSrc;
  12741. _oldBlendDst = blendDst;
  12742. }
  12743. } else {
  12744. _oldBlendEquation = null;
  12745. _oldBlendSrc = null;
  12746. _oldBlendDst = null;
  12747. }
  12748. };
  12749. // Defines
  12750. function generateDefines ( defines ) {
  12751. var value, chunk, chunks = [];
  12752. for ( var d in defines ) {
  12753. value = defines[ d ];
  12754. if ( value === false ) continue;
  12755. chunk = "#define " + d + " " + value;
  12756. chunks.push( chunk );
  12757. }
  12758. return chunks.join( "\n" );
  12759. };
  12760. // Shaders
  12761. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  12762. var p, pl, d, program, code;
  12763. var chunks = [];
  12764. // Generate code
  12765. if ( shaderID ) {
  12766. chunks.push( shaderID );
  12767. } else {
  12768. chunks.push( fragmentShader );
  12769. chunks.push( vertexShader );
  12770. }
  12771. for ( d in defines ) {
  12772. chunks.push( d );
  12773. chunks.push( defines[ d ] );
  12774. }
  12775. for ( p in parameters ) {
  12776. chunks.push( p );
  12777. chunks.push( parameters[ p ] );
  12778. }
  12779. code = chunks.join();
  12780. // Check if code has been already compiled
  12781. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  12782. var programInfo = _programs[ p ];
  12783. if ( programInfo.code === code ) {
  12784. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  12785. programInfo.usedTimes ++;
  12786. return programInfo.program;
  12787. }
  12788. }
  12789. //console.log( "building new program " );
  12790. //
  12791. var customDefines = generateDefines( defines );
  12792. //
  12793. program = _gl.createProgram();
  12794. var prefix_vertex = [
  12795. "precision " + _precision + " float;",
  12796. customDefines,
  12797. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  12798. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  12799. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  12800. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  12801. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  12802. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  12803. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  12804. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  12805. "#define MAX_SHADOWS " + parameters.maxShadows,
  12806. "#define MAX_BONES " + parameters.maxBones,
  12807. parameters.map ? "#define USE_MAP" : "",
  12808. parameters.envMap ? "#define USE_ENVMAP" : "",
  12809. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  12810. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  12811. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  12812. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  12813. parameters.vertexColors ? "#define USE_COLOR" : "",
  12814. parameters.skinning ? "#define USE_SKINNING" : "",
  12815. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  12816. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  12817. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  12818. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  12819. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  12820. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  12821. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  12822. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  12823. parameters.flipSided ? "#define FLIP_SIDED" : "",
  12824. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  12825. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  12826. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  12827. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  12828. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  12829. "uniform mat4 modelMatrix;",
  12830. "uniform mat4 modelViewMatrix;",
  12831. "uniform mat4 projectionMatrix;",
  12832. "uniform mat4 viewMatrix;",
  12833. "uniform mat3 normalMatrix;",
  12834. "uniform vec3 cameraPosition;",
  12835. "attribute vec3 position;",
  12836. "attribute vec3 normal;",
  12837. "attribute vec2 uv;",
  12838. "attribute vec2 uv2;",
  12839. "#ifdef USE_COLOR",
  12840. "attribute vec3 color;",
  12841. "#endif",
  12842. "#ifdef USE_MORPHTARGETS",
  12843. "attribute vec3 morphTarget0;",
  12844. "attribute vec3 morphTarget1;",
  12845. "attribute vec3 morphTarget2;",
  12846. "attribute vec3 morphTarget3;",
  12847. "#ifdef USE_MORPHNORMALS",
  12848. "attribute vec3 morphNormal0;",
  12849. "attribute vec3 morphNormal1;",
  12850. "attribute vec3 morphNormal2;",
  12851. "attribute vec3 morphNormal3;",
  12852. "#else",
  12853. "attribute vec3 morphTarget4;",
  12854. "attribute vec3 morphTarget5;",
  12855. "attribute vec3 morphTarget6;",
  12856. "attribute vec3 morphTarget7;",
  12857. "#endif",
  12858. "#endif",
  12859. "#ifdef USE_SKINNING",
  12860. "attribute vec4 skinIndex;",
  12861. "attribute vec4 skinWeight;",
  12862. "#endif",
  12863. ""
  12864. ].join("\n");
  12865. var prefix_fragment = [
  12866. "precision " + _precision + " float;",
  12867. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  12868. customDefines,
  12869. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  12870. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  12871. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  12872. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  12873. "#define MAX_SHADOWS " + parameters.maxShadows,
  12874. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  12875. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  12876. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  12877. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  12878. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  12879. ( parameters.useFog && parameters.fog instanceof THREE.FogExp2 ) ? "#define FOG_EXP2" : "",
  12880. parameters.map ? "#define USE_MAP" : "",
  12881. parameters.envMap ? "#define USE_ENVMAP" : "",
  12882. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  12883. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  12884. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  12885. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  12886. parameters.vertexColors ? "#define USE_COLOR" : "",
  12887. parameters.metal ? "#define METAL" : "",
  12888. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  12889. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  12890. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  12891. parameters.flipSided ? "#define FLIP_SIDED" : "",
  12892. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  12893. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  12894. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  12895. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  12896. "uniform mat4 viewMatrix;",
  12897. "uniform vec3 cameraPosition;",
  12898. ""
  12899. ].join("\n");
  12900. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  12901. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  12902. _gl.attachShader( program, glVertexShader );
  12903. _gl.attachShader( program, glFragmentShader );
  12904. _gl.linkProgram( program );
  12905. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  12906. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  12907. }
  12908. // clean up
  12909. _gl.deleteShader( glFragmentShader );
  12910. _gl.deleteShader( glVertexShader );
  12911. //console.log( prefix_fragment + fragmentShader );
  12912. //console.log( prefix_vertex + vertexShader );
  12913. program.uniforms = {};
  12914. program.attributes = {};
  12915. var identifiers, u, a, i;
  12916. // cache uniform locations
  12917. identifiers = [
  12918. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  12919. 'morphTargetInfluences'
  12920. ];
  12921. if ( parameters.useVertexTexture ) {
  12922. identifiers.push( 'boneTexture' );
  12923. } else {
  12924. identifiers.push( 'boneGlobalMatrices' );
  12925. }
  12926. for ( u in uniforms ) {
  12927. identifiers.push( u );
  12928. }
  12929. cacheUniformLocations( program, identifiers );
  12930. // cache attributes locations
  12931. identifiers = [
  12932. "position", "normal", "uv", "uv2", "tangent", "color",
  12933. "skinIndex", "skinWeight"
  12934. ];
  12935. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  12936. identifiers.push( "morphTarget" + i );
  12937. }
  12938. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  12939. identifiers.push( "morphNormal" + i );
  12940. }
  12941. for ( a in attributes ) {
  12942. identifiers.push( a );
  12943. }
  12944. cacheAttributeLocations( program, identifiers );
  12945. program.id = _programs_counter ++;
  12946. _programs.push( { program: program, code: code, usedTimes: 1 } );
  12947. _this.info.memory.programs = _programs.length;
  12948. return program;
  12949. };
  12950. // Shader parameters cache
  12951. function cacheUniformLocations ( program, identifiers ) {
  12952. var i, l, id;
  12953. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  12954. id = identifiers[ i ];
  12955. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  12956. }
  12957. };
  12958. function cacheAttributeLocations ( program, identifiers ) {
  12959. var i, l, id;
  12960. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  12961. id = identifiers[ i ];
  12962. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  12963. }
  12964. };
  12965. function addLineNumbers ( string ) {
  12966. var chunks = string.split( "\n" );
  12967. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  12968. // Chrome reports shader errors on lines
  12969. // starting counting from 1
  12970. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  12971. }
  12972. return chunks.join( "\n" );
  12973. };
  12974. function getShader ( type, string ) {
  12975. var shader;
  12976. if ( type === "fragment" ) {
  12977. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  12978. } else if ( type === "vertex" ) {
  12979. shader = _gl.createShader( _gl.VERTEX_SHADER );
  12980. }
  12981. _gl.shaderSource( shader, string );
  12982. _gl.compileShader( shader );
  12983. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  12984. console.error( _gl.getShaderInfoLog( shader ) );
  12985. console.error( addLineNumbers( string ) );
  12986. return null;
  12987. }
  12988. return shader;
  12989. };
  12990. // Textures
  12991. function isPowerOfTwo ( value ) {
  12992. return ( value & ( value - 1 ) ) === 0;
  12993. };
  12994. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  12995. if ( isImagePowerOfTwo ) {
  12996. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  12997. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  12998. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  12999. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13000. } else {
  13001. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13002. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13003. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13004. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13005. }
  13006. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  13007. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  13008. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  13009. texture.__oldAnisotropy = texture.anisotropy;
  13010. }
  13011. }
  13012. };
  13013. this.setTexture = function ( texture, slot ) {
  13014. if ( texture.needsUpdate ) {
  13015. if ( ! texture.__webglInit ) {
  13016. texture.__webglInit = true;
  13017. texture.__webglTexture = _gl.createTexture();
  13018. _this.info.memory.textures ++;
  13019. }
  13020. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13021. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13022. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13023. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13024. var image = texture.image,
  13025. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13026. glFormat = paramThreeToGL( texture.format ),
  13027. glType = paramThreeToGL( texture.type );
  13028. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  13029. if ( texture instanceof THREE.CompressedTexture ) {
  13030. var mipmap, mipmaps = texture.mipmaps;
  13031. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13032. mipmap = mipmaps[ i ];
  13033. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13034. }
  13035. } else if ( texture instanceof THREE.DataTexture ) {
  13036. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13037. } else {
  13038. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13039. }
  13040. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13041. texture.needsUpdate = false;
  13042. if ( texture.onUpdate ) texture.onUpdate();
  13043. } else {
  13044. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13045. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13046. }
  13047. };
  13048. function clampToMaxSize ( image, maxSize ) {
  13049. if ( image.width <= maxSize && image.height <= maxSize ) {
  13050. return image;
  13051. }
  13052. // Warning: Scaling through the canvas will only work with images that use
  13053. // premultiplied alpha.
  13054. var maxDimension = Math.max( image.width, image.height );
  13055. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  13056. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  13057. var canvas = document.createElement( 'canvas' );
  13058. canvas.width = newWidth;
  13059. canvas.height = newHeight;
  13060. var ctx = canvas.getContext( "2d" );
  13061. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  13062. return canvas;
  13063. }
  13064. function setCubeTexture ( texture, slot ) {
  13065. if ( texture.image.length === 6 ) {
  13066. if ( texture.needsUpdate ) {
  13067. if ( ! texture.image.__webglTextureCube ) {
  13068. texture.image.__webglTextureCube = _gl.createTexture();
  13069. }
  13070. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13071. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13072. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13073. var isCompressed = texture instanceof THREE.CompressedTexture;
  13074. var cubeImage = [];
  13075. for ( var i = 0; i < 6; i ++ ) {
  13076. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  13077. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  13078. } else {
  13079. cubeImage[ i ] = texture.image[ i ];
  13080. }
  13081. }
  13082. var image = cubeImage[ 0 ],
  13083. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13084. glFormat = paramThreeToGL( texture.format ),
  13085. glType = paramThreeToGL( texture.type );
  13086. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  13087. for ( var i = 0; i < 6; i ++ ) {
  13088. if ( isCompressed ) {
  13089. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13090. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13091. mipmap = mipmaps[ j ];
  13092. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13093. }
  13094. } else {
  13095. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13096. }
  13097. }
  13098. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  13099. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13100. }
  13101. texture.needsUpdate = false;
  13102. if ( texture.onUpdate ) texture.onUpdate();
  13103. } else {
  13104. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13105. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13106. }
  13107. }
  13108. };
  13109. function setCubeTextureDynamic ( texture, slot ) {
  13110. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13111. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  13112. };
  13113. // Render targets
  13114. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  13115. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13116. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  13117. };
  13118. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  13119. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13120. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13121. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13122. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13123. /* For some reason this is not working. Defaulting to RGBA4.
  13124. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13125. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  13126. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13127. */
  13128. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13129. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  13130. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13131. } else {
  13132. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  13133. }
  13134. };
  13135. this.setRenderTarget = function ( renderTarget ) {
  13136. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  13137. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  13138. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  13139. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  13140. renderTarget.__webglTexture = _gl.createTexture();
  13141. // Setup texture, create render and frame buffers
  13142. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  13143. glFormat = paramThreeToGL( renderTarget.format ),
  13144. glType = paramThreeToGL( renderTarget.type );
  13145. if ( isCube ) {
  13146. renderTarget.__webglFramebuffer = [];
  13147. renderTarget.__webglRenderbuffer = [];
  13148. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13149. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  13150. for ( var i = 0; i < 6; i ++ ) {
  13151. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13152. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  13153. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13154. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  13155. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  13156. }
  13157. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13158. } else {
  13159. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  13160. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  13161. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13162. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  13163. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13164. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  13165. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  13166. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13167. }
  13168. // Release everything
  13169. if ( isCube ) {
  13170. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13171. } else {
  13172. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13173. }
  13174. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  13175. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
  13176. }
  13177. var framebuffer, width, height, vx, vy;
  13178. if ( renderTarget ) {
  13179. if ( isCube ) {
  13180. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13181. } else {
  13182. framebuffer = renderTarget.__webglFramebuffer;
  13183. }
  13184. width = renderTarget.width;
  13185. height = renderTarget.height;
  13186. vx = 0;
  13187. vy = 0;
  13188. } else {
  13189. framebuffer = null;
  13190. width = _viewportWidth;
  13191. height = _viewportHeight;
  13192. vx = _viewportX;
  13193. vy = _viewportY;
  13194. }
  13195. if ( framebuffer !== _currentFramebuffer ) {
  13196. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13197. _gl.viewport( vx, vy, width, height );
  13198. _currentFramebuffer = framebuffer;
  13199. }
  13200. _currentWidth = width;
  13201. _currentHeight = height;
  13202. };
  13203. function updateRenderTargetMipmap ( renderTarget ) {
  13204. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  13205. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13206. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13207. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13208. } else {
  13209. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13210. _gl.generateMipmap( _gl.TEXTURE_2D );
  13211. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13212. }
  13213. };
  13214. // Fallback filters for non-power-of-2 textures
  13215. function filterFallback ( f ) {
  13216. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  13217. return _gl.NEAREST;
  13218. }
  13219. return _gl.LINEAR;
  13220. };
  13221. // Map three.js constants to WebGL constants
  13222. function paramThreeToGL ( p ) {
  13223. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  13224. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13225. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13226. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  13227. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13228. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13229. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  13230. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13231. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13232. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13233. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13234. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13235. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13236. if ( p === THREE.ByteType ) return _gl.BYTE;
  13237. if ( p === THREE.ShortType ) return _gl.SHORT;
  13238. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13239. if ( p === THREE.IntType ) return _gl.INT;
  13240. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  13241. if ( p === THREE.FloatType ) return _gl.FLOAT;
  13242. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  13243. if ( p === THREE.RGBFormat ) return _gl.RGB;
  13244. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  13245. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  13246. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13247. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  13248. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13249. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13250. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  13251. if ( p === THREE.OneFactor ) return _gl.ONE;
  13252. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  13253. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13254. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13255. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13256. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  13257. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13258. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  13259. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13260. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13261. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  13262. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13263. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13264. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13265. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13266. }
  13267. return 0;
  13268. };
  13269. // Allocations
  13270. function allocateBones ( object ) {
  13271. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  13272. return 1024;
  13273. } else {
  13274. // default for when object is not specified
  13275. // ( for example when prebuilding shader
  13276. // to be used with multiple objects )
  13277. //
  13278. // - leave some extra space for other uniforms
  13279. // - limit here is ANGLE's 254 max uniform vectors
  13280. // (up to 54 should be safe)
  13281. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  13282. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  13283. var maxBones = nVertexMatrices;
  13284. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  13285. maxBones = Math.min( object.bones.length, maxBones );
  13286. if ( maxBones < object.bones.length ) {
  13287. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  13288. }
  13289. }
  13290. return maxBones;
  13291. }
  13292. };
  13293. function allocateLights ( lights ) {
  13294. var l, ll, light, dirLights, pointLights, spotLights, hemiLights, maxDirLights, maxPointLights, maxSpotLights, maxHemiLights;
  13295. dirLights = pointLights = spotLights = hemiLights = maxDirLights = maxPointLights = maxSpotLights = maxHemiLights = 0;
  13296. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13297. light = lights[ l ];
  13298. if ( light.onlyShadow ) continue;
  13299. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  13300. if ( light instanceof THREE.PointLight ) pointLights ++;
  13301. if ( light instanceof THREE.SpotLight ) spotLights ++;
  13302. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  13303. }
  13304. if ( ( pointLights + spotLights + dirLights + hemiLights) <= _maxLights ) {
  13305. maxDirLights = dirLights;
  13306. maxPointLights = pointLights;
  13307. maxSpotLights = spotLights;
  13308. maxHemiLights = hemiLights;
  13309. } else {
  13310. maxDirLights = Math.ceil( _maxLights * dirLights / ( pointLights + dirLights ) );
  13311. maxPointLights = _maxLights - maxDirLights;
  13312. // these are not really correct
  13313. maxSpotLights = maxPointLights;
  13314. maxHemiLights = maxDirLights;
  13315. }
  13316. return { 'directional' : maxDirLights, 'point' : maxPointLights, 'spot': maxSpotLights, 'hemi': maxHemiLights };
  13317. };
  13318. function allocateShadows ( lights ) {
  13319. var l, ll, light, maxShadows = 0;
  13320. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  13321. light = lights[ l ];
  13322. if ( ! light.castShadow ) continue;
  13323. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  13324. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  13325. }
  13326. return maxShadows;
  13327. };
  13328. // Initialization
  13329. function initGL () {
  13330. try {
  13331. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  13332. throw 'Error creating WebGL context.';
  13333. }
  13334. } catch ( error ) {
  13335. console.error( error );
  13336. }
  13337. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  13338. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  13339. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  13340. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  13341. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  13342. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  13343. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  13344. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  13345. if ( ! _glExtensionTextureFloat ) {
  13346. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  13347. }
  13348. if ( ! _glExtensionStandardDerivatives ) {
  13349. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  13350. }
  13351. if ( ! _glExtensionTextureFilterAnisotropic ) {
  13352. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  13353. }
  13354. if ( ! _glExtensionCompressedTextureS3TC ) {
  13355. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  13356. }
  13357. };
  13358. function setDefaultGLState () {
  13359. _gl.clearColor( 0, 0, 0, 1 );
  13360. _gl.clearDepth( 1 );
  13361. _gl.clearStencil( 0 );
  13362. _gl.enable( _gl.DEPTH_TEST );
  13363. _gl.depthFunc( _gl.LEQUAL );
  13364. _gl.frontFace( _gl.CCW );
  13365. _gl.cullFace( _gl.BACK );
  13366. _gl.enable( _gl.CULL_FACE );
  13367. _gl.enable( _gl.BLEND );
  13368. _gl.blendEquation( _gl.FUNC_ADD );
  13369. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  13370. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  13371. };
  13372. // default plugins (order is important)
  13373. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  13374. this.addPrePlugin( this.shadowMapPlugin );
  13375. this.addPostPlugin( new THREE.SpritePlugin() );
  13376. this.addPostPlugin( new THREE.LensFlarePlugin() );
  13377. };
  13378. /**
  13379. * @author szimek / https://github.com/szimek/
  13380. * @author alteredq / http://alteredqualia.com/
  13381. */
  13382. THREE.WebGLRenderTarget = function ( width, height, options ) {
  13383. this.width = width;
  13384. this.height = height;
  13385. options = options || {};
  13386. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  13387. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  13388. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  13389. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  13390. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  13391. this.offset = new THREE.Vector2( 0, 0 );
  13392. this.repeat = new THREE.Vector2( 1, 1 );
  13393. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  13394. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  13395. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  13396. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  13397. this.generateMipmaps = true;
  13398. };
  13399. THREE.WebGLRenderTarget.prototype.clone = function() {
  13400. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  13401. tmp.wrapS = this.wrapS;
  13402. tmp.wrapT = this.wrapT;
  13403. tmp.magFilter = this.magFilter;
  13404. tmp.anisotropy = this.anisotropy;
  13405. tmp.minFilter = this.minFilter;
  13406. tmp.offset.copy( this.offset );
  13407. tmp.repeat.copy( this.repeat );
  13408. tmp.format = this.format;
  13409. tmp.type = this.type;
  13410. tmp.depthBuffer = this.depthBuffer;
  13411. tmp.stencilBuffer = this.stencilBuffer;
  13412. tmp.generateMipmaps = this.generateMipmaps;
  13413. return tmp;
  13414. };
  13415. /**
  13416. * @author alteredq / http://alteredqualia.com
  13417. */
  13418. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  13419. THREE.WebGLRenderTarget.call( this, width, height, options );
  13420. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  13421. };
  13422. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  13423. /**
  13424. * @author mrdoob / http://mrdoob.com/
  13425. */
  13426. THREE.RenderableVertex = function () {
  13427. this.positionWorld = new THREE.Vector3();
  13428. this.positionScreen = new THREE.Vector4();
  13429. this.visible = true;
  13430. };
  13431. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  13432. this.positionWorld.copy( vertex.positionWorld );
  13433. this.positionScreen.copy( vertex.positionScreen );
  13434. }
  13435. /**
  13436. * @author mrdoob / http://mrdoob.com/
  13437. */
  13438. THREE.RenderableFace3 = function () {
  13439. this.v1 = new THREE.RenderableVertex();
  13440. this.v2 = new THREE.RenderableVertex();
  13441. this.v3 = new THREE.RenderableVertex();
  13442. this.centroidWorld = new THREE.Vector3();
  13443. this.centroidScreen = new THREE.Vector3();
  13444. this.normalWorld = new THREE.Vector3();
  13445. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13446. this.vertexNormalsLength = 0;
  13447. this.color = null;
  13448. this.material = null;
  13449. this.uvs = [[]];
  13450. this.z = null;
  13451. };
  13452. /**
  13453. * @author mrdoob / http://mrdoob.com/
  13454. */
  13455. THREE.RenderableFace4 = function () {
  13456. this.v1 = new THREE.RenderableVertex();
  13457. this.v2 = new THREE.RenderableVertex();
  13458. this.v3 = new THREE.RenderableVertex();
  13459. this.v4 = new THREE.RenderableVertex();
  13460. this.centroidWorld = new THREE.Vector3();
  13461. this.centroidScreen = new THREE.Vector3();
  13462. this.normalWorld = new THREE.Vector3();
  13463. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13464. this.vertexNormalsLength = 0;
  13465. this.color = null;
  13466. this.material = null;
  13467. this.uvs = [[]];
  13468. this.z = null;
  13469. };
  13470. /**
  13471. * @author mrdoob / http://mrdoob.com/
  13472. */
  13473. THREE.RenderableObject = function () {
  13474. this.object = null;
  13475. this.z = null;
  13476. };
  13477. /**
  13478. * @author mrdoob / http://mrdoob.com/
  13479. */
  13480. THREE.RenderableParticle = function () {
  13481. this.object = null;
  13482. this.x = null;
  13483. this.y = null;
  13484. this.z = null;
  13485. this.rotation = null;
  13486. this.scale = new THREE.Vector2();
  13487. this.material = null;
  13488. };
  13489. /**
  13490. * @author mrdoob / http://mrdoob.com/
  13491. */
  13492. THREE.RenderableLine = function () {
  13493. this.z = null;
  13494. this.v1 = new THREE.RenderableVertex();
  13495. this.v2 = new THREE.RenderableVertex();
  13496. this.material = null;
  13497. };
  13498. /**
  13499. * @author alteredq / http://alteredqualia.com/
  13500. */
  13501. THREE.ColorUtils = {
  13502. adjustHSV : function ( color, h, s, v ) {
  13503. var hsv = THREE.ColorUtils.__hsv;
  13504. THREE.ColorUtils.rgbToHsv( color, hsv );
  13505. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  13506. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  13507. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  13508. color.setHSV( hsv.h, hsv.s, hsv.v );
  13509. },
  13510. // based on MochiKit implementation by Bob Ippolito
  13511. rgbToHsv : function ( color, hsv ) {
  13512. var r = color.r;
  13513. var g = color.g;
  13514. var b = color.b;
  13515. var max = Math.max( Math.max( r, g ), b );
  13516. var min = Math.min( Math.min( r, g ), b );
  13517. var hue;
  13518. var saturation;
  13519. var value = max;
  13520. if ( min === max ) {
  13521. hue = 0;
  13522. saturation = 0;
  13523. } else {
  13524. var delta = ( max - min );
  13525. saturation = delta / max;
  13526. if ( r === max ) {
  13527. hue = ( g - b ) / delta;
  13528. } else if ( g === max ) {
  13529. hue = 2 + ( ( b - r ) / delta );
  13530. } else {
  13531. hue = 4 + ( ( r - g ) / delta );
  13532. }
  13533. hue /= 6;
  13534. if ( hue < 0 ) {
  13535. hue += 1;
  13536. }
  13537. if ( hue > 1 ) {
  13538. hue -= 1;
  13539. }
  13540. }
  13541. if ( hsv === undefined ) {
  13542. hsv = { h: 0, s: 0, v: 0 };
  13543. }
  13544. hsv.h = hue;
  13545. hsv.s = saturation;
  13546. hsv.v = value;
  13547. return hsv;
  13548. }
  13549. };
  13550. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  13551. * @author mrdoob / http://mrdoob.com/
  13552. * @author alteredq / http://alteredqualia.com/
  13553. */
  13554. THREE.GeometryUtils = {
  13555. // Merge two geometries or geometry and geometry from object (using object's transform)
  13556. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  13557. var matrix, matrixRotation,
  13558. vertexOffset = geometry1.vertices.length,
  13559. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  13560. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  13561. vertices1 = geometry1.vertices,
  13562. vertices2 = geometry2.vertices,
  13563. faces1 = geometry1.faces,
  13564. faces2 = geometry2.faces,
  13565. uvs1 = geometry1.faceVertexUvs[ 0 ],
  13566. uvs2 = geometry2.faceVertexUvs[ 0 ];
  13567. var geo1MaterialsMap = {};
  13568. for ( var i = 0; i < geometry1.materials.length; i ++ ) {
  13569. var id = geometry1.materials[ i ].id;
  13570. geo1MaterialsMap[ id ] = i;
  13571. }
  13572. if ( object2 instanceof THREE.Mesh ) {
  13573. object2.matrixAutoUpdate && object2.updateMatrix();
  13574. matrix = object2.matrix;
  13575. matrixRotation = new THREE.Matrix4();
  13576. matrixRotation.extractRotation( matrix, object2.scale );
  13577. }
  13578. // vertices
  13579. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  13580. var vertex = vertices2[ i ];
  13581. var vertexCopy = vertex.clone();
  13582. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  13583. vertices1.push( vertexCopy );
  13584. }
  13585. // faces
  13586. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  13587. var face = faces2[ i ], faceCopy, normal, color,
  13588. faceVertexNormals = face.vertexNormals,
  13589. faceVertexColors = face.vertexColors;
  13590. if ( face instanceof THREE.Face3 ) {
  13591. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  13592. } else if ( face instanceof THREE.Face4 ) {
  13593. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  13594. }
  13595. faceCopy.normal.copy( face.normal );
  13596. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  13597. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  13598. normal = faceVertexNormals[ j ].clone();
  13599. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  13600. faceCopy.vertexNormals.push( normal );
  13601. }
  13602. faceCopy.color.copy( face.color );
  13603. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  13604. color = faceVertexColors[ j ];
  13605. faceCopy.vertexColors.push( color.clone() );
  13606. }
  13607. if ( face.materialIndex !== undefined ) {
  13608. var material2 = geometry2.materials[ face.materialIndex ];
  13609. var materialId2 = material2.id;
  13610. var materialIndex = geo1MaterialsMap[ materialId2 ];
  13611. if ( materialIndex === undefined ) {
  13612. materialIndex = geometry1.materials.length;
  13613. geo1MaterialsMap[ materialId2 ] = materialIndex;
  13614. geometry1.materials.push( material2 );
  13615. }
  13616. faceCopy.materialIndex = materialIndex;
  13617. }
  13618. faceCopy.centroid.copy( face.centroid );
  13619. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  13620. faces1.push( faceCopy );
  13621. }
  13622. // uvs
  13623. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  13624. var uv = uvs2[ i ], uvCopy = [];
  13625. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13626. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13627. }
  13628. uvs1.push( uvCopy );
  13629. }
  13630. },
  13631. clone: function ( geometry ) {
  13632. var cloneGeo = new THREE.Geometry();
  13633. var i, il;
  13634. var vertices = geometry.vertices,
  13635. faces = geometry.faces,
  13636. uvs = geometry.faceVertexUvs[ 0 ];
  13637. // materials
  13638. if ( geometry.materials ) {
  13639. cloneGeo.materials = geometry.materials.slice();
  13640. }
  13641. // vertices
  13642. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  13643. var vertex = vertices[ i ];
  13644. cloneGeo.vertices.push( vertex.clone() );
  13645. }
  13646. // faces
  13647. for ( i = 0, il = faces.length; i < il; i ++ ) {
  13648. var face = faces[ i ];
  13649. cloneGeo.faces.push( face.clone() );
  13650. }
  13651. // uvs
  13652. for ( i = 0, il = uvs.length; i < il; i ++ ) {
  13653. var uv = uvs[ i ], uvCopy = [];
  13654. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13655. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13656. }
  13657. cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );
  13658. }
  13659. return cloneGeo;
  13660. },
  13661. // Get random point in triangle (via barycentric coordinates)
  13662. // (uniform distribution)
  13663. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  13664. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  13665. var a, b, c,
  13666. point = new THREE.Vector3(),
  13667. tmp = THREE.GeometryUtils.__v1;
  13668. a = THREE.GeometryUtils.random();
  13669. b = THREE.GeometryUtils.random();
  13670. if ( ( a + b ) > 1 ) {
  13671. a = 1 - a;
  13672. b = 1 - b;
  13673. }
  13674. c = 1 - a - b;
  13675. point.copy( vectorA );
  13676. point.multiplyScalar( a );
  13677. tmp.copy( vectorB );
  13678. tmp.multiplyScalar( b );
  13679. point.addSelf( tmp );
  13680. tmp.copy( vectorC );
  13681. tmp.multiplyScalar( c );
  13682. point.addSelf( tmp );
  13683. return point;
  13684. },
  13685. // Get random point in face (triangle / quad)
  13686. // (uniform distribution)
  13687. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  13688. var vA, vB, vC, vD;
  13689. if ( face instanceof THREE.Face3 ) {
  13690. vA = geometry.vertices[ face.a ];
  13691. vB = geometry.vertices[ face.b ];
  13692. vC = geometry.vertices[ face.c ];
  13693. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  13694. } else if ( face instanceof THREE.Face4 ) {
  13695. vA = geometry.vertices[ face.a ];
  13696. vB = geometry.vertices[ face.b ];
  13697. vC = geometry.vertices[ face.c ];
  13698. vD = geometry.vertices[ face.d ];
  13699. var area1, area2;
  13700. if ( useCachedAreas ) {
  13701. if ( face._area1 && face._area2 ) {
  13702. area1 = face._area1;
  13703. area2 = face._area2;
  13704. } else {
  13705. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13706. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13707. face._area1 = area1;
  13708. face._area2 = area2;
  13709. }
  13710. } else {
  13711. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  13712. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13713. }
  13714. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  13715. if ( r < area1 ) {
  13716. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  13717. } else {
  13718. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  13719. }
  13720. }
  13721. },
  13722. // Get uniformly distributed random points in mesh
  13723. // - create array with cumulative sums of face areas
  13724. // - pick random number from 0 to total area
  13725. // - find corresponding place in area array by binary search
  13726. // - get random point in face
  13727. randomPointsInGeometry: function ( geometry, n ) {
  13728. var face, i,
  13729. faces = geometry.faces,
  13730. vertices = geometry.vertices,
  13731. il = faces.length,
  13732. totalArea = 0,
  13733. cumulativeAreas = [],
  13734. vA, vB, vC, vD;
  13735. // precompute face areas
  13736. for ( i = 0; i < il; i ++ ) {
  13737. face = faces[ i ];
  13738. if ( face instanceof THREE.Face3 ) {
  13739. vA = vertices[ face.a ];
  13740. vB = vertices[ face.b ];
  13741. vC = vertices[ face.c ];
  13742. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  13743. } else if ( face instanceof THREE.Face4 ) {
  13744. vA = vertices[ face.a ];
  13745. vB = vertices[ face.b ];
  13746. vC = vertices[ face.c ];
  13747. vD = vertices[ face.d ];
  13748. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13749. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13750. face._area = face._area1 + face._area2;
  13751. }
  13752. totalArea += face._area;
  13753. cumulativeAreas[ i ] = totalArea;
  13754. }
  13755. // binary search cumulative areas array
  13756. function binarySearchIndices( value ) {
  13757. function binarySearch( start, end ) {
  13758. // return closest larger index
  13759. // if exact number is not found
  13760. if ( end < start )
  13761. return start;
  13762. var mid = start + Math.floor( ( end - start ) / 2 );
  13763. if ( cumulativeAreas[ mid ] > value ) {
  13764. return binarySearch( start, mid - 1 );
  13765. } else if ( cumulativeAreas[ mid ] < value ) {
  13766. return binarySearch( mid + 1, end );
  13767. } else {
  13768. return mid;
  13769. }
  13770. }
  13771. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  13772. return result;
  13773. }
  13774. // pick random face weighted by face area
  13775. var r, index,
  13776. result = [];
  13777. var stats = {};
  13778. for ( i = 0; i < n; i ++ ) {
  13779. r = THREE.GeometryUtils.random() * totalArea;
  13780. index = binarySearchIndices( r );
  13781. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  13782. if ( ! stats[ index ] ) {
  13783. stats[ index ] = 1;
  13784. } else {
  13785. stats[ index ] += 1;
  13786. }
  13787. }
  13788. return result;
  13789. },
  13790. // Get triangle area (by Heron's formula)
  13791. // http://en.wikipedia.org/wiki/Heron%27s_formula
  13792. triangleArea: function ( vectorA, vectorB, vectorC ) {
  13793. var s, a, b, c,
  13794. tmp = THREE.GeometryUtils.__v1;
  13795. tmp.sub( vectorA, vectorB );
  13796. a = tmp.length();
  13797. tmp.sub( vectorA, vectorC );
  13798. b = tmp.length();
  13799. tmp.sub( vectorB, vectorC );
  13800. c = tmp.length();
  13801. s = 0.5 * ( a + b + c );
  13802. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  13803. },
  13804. // Center geometry so that 0,0,0 is in center of bounding box
  13805. center: function ( geometry ) {
  13806. geometry.computeBoundingBox();
  13807. var bb = geometry.boundingBox;
  13808. var offset = new THREE.Vector3();
  13809. offset.add( bb.min, bb.max );
  13810. offset.multiplyScalar( -0.5 );
  13811. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  13812. geometry.computeBoundingBox();
  13813. return offset;
  13814. },
  13815. // Normalize UVs to be from <0,1>
  13816. // (for now just the first set of UVs)
  13817. normalizeUVs: function ( geometry ) {
  13818. var uvSet = geometry.faceVertexUvs[ 0 ];
  13819. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  13820. var uvs = uvSet[ i ];
  13821. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  13822. // texture repeat
  13823. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  13824. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  13825. }
  13826. }
  13827. },
  13828. triangulateQuads: function ( geometry ) {
  13829. var i, il, j, jl;
  13830. var faces = [];
  13831. var faceUvs = [];
  13832. var faceVertexUvs = [];
  13833. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  13834. faceUvs[ i ] = [];
  13835. }
  13836. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  13837. faceVertexUvs[ i ] = [];
  13838. }
  13839. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13840. var face = geometry.faces[ i ];
  13841. if ( face instanceof THREE.Face4 ) {
  13842. var a = face.a;
  13843. var b = face.b;
  13844. var c = face.c;
  13845. var d = face.d;
  13846. var triA = new THREE.Face3();
  13847. var triB = new THREE.Face3();
  13848. triA.color.copy( face.color );
  13849. triB.color.copy( face.color );
  13850. triA.materialIndex = face.materialIndex;
  13851. triB.materialIndex = face.materialIndex;
  13852. triA.a = a;
  13853. triA.b = b;
  13854. triA.c = d;
  13855. triB.a = b;
  13856. triB.b = c;
  13857. triB.c = d;
  13858. if ( face.vertexColors.length === 4 ) {
  13859. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  13860. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  13861. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  13862. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  13863. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  13864. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  13865. }
  13866. faces.push( triA, triB );
  13867. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13868. if ( geometry.faceVertexUvs[ j ].length ) {
  13869. var uvs = geometry.faceVertexUvs[ j ][ i ];
  13870. var uvA = uvs[ 0 ];
  13871. var uvB = uvs[ 1 ];
  13872. var uvC = uvs[ 2 ];
  13873. var uvD = uvs[ 3 ];
  13874. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  13875. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  13876. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  13877. }
  13878. }
  13879. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  13880. if ( geometry.faceUvs[ j ].length ) {
  13881. var faceUv = geometry.faceUvs[ j ][ i ];
  13882. faceUvs[ j ].push( faceUv, faceUv );
  13883. }
  13884. }
  13885. } else {
  13886. faces.push( face );
  13887. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  13888. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  13889. }
  13890. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13891. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  13892. }
  13893. }
  13894. }
  13895. geometry.faces = faces;
  13896. geometry.faceUvs = faceUvs;
  13897. geometry.faceVertexUvs = faceVertexUvs;
  13898. geometry.computeCentroids();
  13899. geometry.computeFaceNormals();
  13900. geometry.computeVertexNormals();
  13901. if ( geometry.hasTangents ) geometry.computeTangents();
  13902. },
  13903. // Make all faces use unique vertices
  13904. // so that each face can be separated from others
  13905. explode: function( geometry ) {
  13906. var vertices = [];
  13907. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13908. var n = vertices.length;
  13909. var face = geometry.faces[ i ];
  13910. if ( face instanceof THREE.Face4 ) {
  13911. var a = face.a;
  13912. var b = face.b;
  13913. var c = face.c;
  13914. var d = face.d;
  13915. var va = geometry.vertices[ a ];
  13916. var vb = geometry.vertices[ b ];
  13917. var vc = geometry.vertices[ c ];
  13918. var vd = geometry.vertices[ d ];
  13919. vertices.push( va.clone() );
  13920. vertices.push( vb.clone() );
  13921. vertices.push( vc.clone() );
  13922. vertices.push( vd.clone() );
  13923. face.a = n;
  13924. face.b = n + 1;
  13925. face.c = n + 2;
  13926. face.d = n + 3;
  13927. } else {
  13928. var a = face.a;
  13929. var b = face.b;
  13930. var c = face.c;
  13931. var va = geometry.vertices[ a ];
  13932. var vb = geometry.vertices[ b ];
  13933. var vc = geometry.vertices[ c ];
  13934. vertices.push( va.clone() );
  13935. vertices.push( vb.clone() );
  13936. vertices.push( vc.clone() );
  13937. face.a = n;
  13938. face.b = n + 1;
  13939. face.c = n + 2;
  13940. }
  13941. }
  13942. geometry.vertices = vertices;
  13943. delete geometry.__tmpVertices;
  13944. },
  13945. // Break faces with edges longer than maxEdgeLength
  13946. // - not recursive
  13947. tessellate: function ( geometry, maxEdgeLength ) {
  13948. var i, il, face,
  13949. a, b, c, d,
  13950. va, vb, vc, vd,
  13951. dab, dbc, dac, dcd, dad,
  13952. m, m1, m2,
  13953. vm, vm1, vm2,
  13954. vnm, vnm1, vnm2,
  13955. vcm, vcm1, vcm2,
  13956. triA, triB,
  13957. quadA, quadB,
  13958. edge;
  13959. var faces = [];
  13960. var faceVertexUvs = [];
  13961. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  13962. faceVertexUvs[ i ] = [];
  13963. }
  13964. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13965. face = geometry.faces[ i ];
  13966. if ( face instanceof THREE.Face3 ) {
  13967. a = face.a;
  13968. b = face.b;
  13969. c = face.c;
  13970. va = geometry.vertices[ a ];
  13971. vb = geometry.vertices[ b ];
  13972. vc = geometry.vertices[ c ];
  13973. dab = va.distanceTo( vb );
  13974. dbc = vb.distanceTo( vc );
  13975. dac = va.distanceTo( vc );
  13976. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  13977. m = geometry.vertices.length;
  13978. triA = face.clone();
  13979. triB = face.clone();
  13980. if ( dab >= dbc && dab >= dac ) {
  13981. vm = va.clone();
  13982. vm.lerpSelf( vb, 0.5 );
  13983. triA.a = a;
  13984. triA.b = m;
  13985. triA.c = c;
  13986. triB.a = m;
  13987. triB.b = b;
  13988. triB.c = c;
  13989. if ( face.vertexNormals.length === 3 ) {
  13990. vnm = face.vertexNormals[ 0 ].clone();
  13991. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  13992. triA.vertexNormals[ 1 ].copy( vnm );
  13993. triB.vertexNormals[ 0 ].copy( vnm );
  13994. }
  13995. if ( face.vertexColors.length === 3 ) {
  13996. vcm = face.vertexColors[ 0 ].clone();
  13997. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  13998. triA.vertexColors[ 1 ].copy( vcm );
  13999. triB.vertexColors[ 0 ].copy( vcm );
  14000. }
  14001. edge = 0;
  14002. } else if ( dbc >= dab && dbc >= dac ) {
  14003. vm = vb.clone();
  14004. vm.lerpSelf( vc, 0.5 );
  14005. triA.a = a;
  14006. triA.b = b;
  14007. triA.c = m;
  14008. triB.a = m;
  14009. triB.b = c;
  14010. triB.c = a;
  14011. if ( face.vertexNormals.length === 3 ) {
  14012. vnm = face.vertexNormals[ 1 ].clone();
  14013. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14014. triA.vertexNormals[ 2 ].copy( vnm );
  14015. triB.vertexNormals[ 0 ].copy( vnm );
  14016. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  14017. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  14018. }
  14019. if ( face.vertexColors.length === 3 ) {
  14020. vcm = face.vertexColors[ 1 ].clone();
  14021. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14022. triA.vertexColors[ 2 ].copy( vcm );
  14023. triB.vertexColors[ 0 ].copy( vcm );
  14024. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  14025. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  14026. }
  14027. edge = 1;
  14028. } else {
  14029. vm = va.clone();
  14030. vm.lerpSelf( vc, 0.5 );
  14031. triA.a = a;
  14032. triA.b = b;
  14033. triA.c = m;
  14034. triB.a = m;
  14035. triB.b = b;
  14036. triB.c = c;
  14037. if ( face.vertexNormals.length === 3 ) {
  14038. vnm = face.vertexNormals[ 0 ].clone();
  14039. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14040. triA.vertexNormals[ 2 ].copy( vnm );
  14041. triB.vertexNormals[ 0 ].copy( vnm );
  14042. }
  14043. if ( face.vertexColors.length === 3 ) {
  14044. vcm = face.vertexColors[ 0 ].clone();
  14045. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14046. triA.vertexColors[ 2 ].copy( vcm );
  14047. triB.vertexColors[ 0 ].copy( vcm );
  14048. }
  14049. edge = 2;
  14050. }
  14051. faces.push( triA, triB );
  14052. geometry.vertices.push( vm );
  14053. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  14054. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14055. if ( geometry.faceVertexUvs[ j ].length ) {
  14056. uvs = geometry.faceVertexUvs[ j ][ i ];
  14057. uvA = uvs[ 0 ];
  14058. uvB = uvs[ 1 ];
  14059. uvC = uvs[ 2 ];
  14060. // AB
  14061. if ( edge === 0 ) {
  14062. uvM = uvA.clone();
  14063. uvM.lerpSelf( uvB, 0.5 );
  14064. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  14065. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14066. // BC
  14067. } else if ( edge === 1 ) {
  14068. uvM = uvB.clone();
  14069. uvM.lerpSelf( uvC, 0.5 );
  14070. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14071. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  14072. // AC
  14073. } else {
  14074. uvM = uvA.clone();
  14075. uvM.lerpSelf( uvC, 0.5 );
  14076. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14077. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14078. }
  14079. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14080. }
  14081. }
  14082. } else {
  14083. faces.push( face );
  14084. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14085. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14086. }
  14087. }
  14088. } else {
  14089. a = face.a;
  14090. b = face.b;
  14091. c = face.c;
  14092. d = face.d;
  14093. va = geometry.vertices[ a ];
  14094. vb = geometry.vertices[ b ];
  14095. vc = geometry.vertices[ c ];
  14096. vd = geometry.vertices[ d ];
  14097. dab = va.distanceTo( vb );
  14098. dbc = vb.distanceTo( vc );
  14099. dcd = vc.distanceTo( vd );
  14100. dad = va.distanceTo( vd );
  14101. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  14102. m1 = geometry.vertices.length;
  14103. m2 = geometry.vertices.length + 1;
  14104. quadA = face.clone();
  14105. quadB = face.clone();
  14106. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  14107. vm1 = va.clone();
  14108. vm1.lerpSelf( vb, 0.5 );
  14109. vm2 = vc.clone();
  14110. vm2.lerpSelf( vd, 0.5 );
  14111. quadA.a = a;
  14112. quadA.b = m1;
  14113. quadA.c = m2;
  14114. quadA.d = d;
  14115. quadB.a = m1;
  14116. quadB.b = b;
  14117. quadB.c = c;
  14118. quadB.d = m2;
  14119. if ( face.vertexNormals.length === 4 ) {
  14120. vnm1 = face.vertexNormals[ 0 ].clone();
  14121. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14122. vnm2 = face.vertexNormals[ 2 ].clone();
  14123. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  14124. quadA.vertexNormals[ 1 ].copy( vnm1 );
  14125. quadA.vertexNormals[ 2 ].copy( vnm2 );
  14126. quadB.vertexNormals[ 0 ].copy( vnm1 );
  14127. quadB.vertexNormals[ 3 ].copy( vnm2 );
  14128. }
  14129. if ( face.vertexColors.length === 4 ) {
  14130. vcm1 = face.vertexColors[ 0 ].clone();
  14131. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14132. vcm2 = face.vertexColors[ 2 ].clone();
  14133. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  14134. quadA.vertexColors[ 1 ].copy( vcm1 );
  14135. quadA.vertexColors[ 2 ].copy( vcm2 );
  14136. quadB.vertexColors[ 0 ].copy( vcm1 );
  14137. quadB.vertexColors[ 3 ].copy( vcm2 );
  14138. }
  14139. edge = 0;
  14140. } else {
  14141. vm1 = vb.clone();
  14142. vm1.lerpSelf( vc, 0.5 );
  14143. vm2 = vd.clone();
  14144. vm2.lerpSelf( va, 0.5 );
  14145. quadA.a = a;
  14146. quadA.b = b;
  14147. quadA.c = m1;
  14148. quadA.d = m2;
  14149. quadB.a = m2;
  14150. quadB.b = m1;
  14151. quadB.c = c;
  14152. quadB.d = d;
  14153. if ( face.vertexNormals.length === 4 ) {
  14154. vnm1 = face.vertexNormals[ 1 ].clone();
  14155. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14156. vnm2 = face.vertexNormals[ 3 ].clone();
  14157. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  14158. quadA.vertexNormals[ 2 ].copy( vnm1 );
  14159. quadA.vertexNormals[ 3 ].copy( vnm2 );
  14160. quadB.vertexNormals[ 0 ].copy( vnm2 );
  14161. quadB.vertexNormals[ 1 ].copy( vnm1 );
  14162. }
  14163. if ( face.vertexColors.length === 4 ) {
  14164. vcm1 = face.vertexColors[ 1 ].clone();
  14165. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14166. vcm2 = face.vertexColors[ 3 ].clone();
  14167. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  14168. quadA.vertexColors[ 2 ].copy( vcm1 );
  14169. quadA.vertexColors[ 3 ].copy( vcm2 );
  14170. quadB.vertexColors[ 0 ].copy( vcm2 );
  14171. quadB.vertexColors[ 1 ].copy( vcm1 );
  14172. }
  14173. edge = 1;
  14174. }
  14175. faces.push( quadA, quadB );
  14176. geometry.vertices.push( vm1, vm2 );
  14177. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  14178. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14179. if ( geometry.faceVertexUvs[ j ].length ) {
  14180. uvs = geometry.faceVertexUvs[ j ][ i ];
  14181. uvA = uvs[ 0 ];
  14182. uvB = uvs[ 1 ];
  14183. uvC = uvs[ 2 ];
  14184. uvD = uvs[ 3 ];
  14185. // AB + CD
  14186. if ( edge === 0 ) {
  14187. uvM1 = uvA.clone();
  14188. uvM1.lerpSelf( uvB, 0.5 );
  14189. uvM2 = uvC.clone();
  14190. uvM2.lerpSelf( uvD, 0.5 );
  14191. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  14192. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  14193. // BC + AD
  14194. } else {
  14195. uvM1 = uvB.clone();
  14196. uvM1.lerpSelf( uvC, 0.5 );
  14197. uvM2 = uvD.clone();
  14198. uvM2.lerpSelf( uvA, 0.5 );
  14199. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  14200. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  14201. }
  14202. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  14203. }
  14204. }
  14205. } else {
  14206. faces.push( face );
  14207. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14208. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14209. }
  14210. }
  14211. }
  14212. }
  14213. geometry.faces = faces;
  14214. geometry.faceVertexUvs = faceVertexUvs;
  14215. }
  14216. };
  14217. THREE.GeometryUtils.random = THREE.Math.random16;
  14218. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  14219. /**
  14220. * @author alteredq / http://alteredqualia.com/
  14221. * @author mrdoob / http://mrdoob.com/
  14222. */
  14223. THREE.ImageUtils = {
  14224. crossOrigin: 'anonymous',
  14225. loadTexture: function ( url, mapping, onLoad, onError ) {
  14226. var image = new Image();
  14227. var texture = new THREE.Texture( image, mapping );
  14228. var loader = new THREE.ImageLoader();
  14229. loader.addEventListener( 'load', function ( event ) {
  14230. texture.image = event.content;
  14231. texture.needsUpdate = true;
  14232. if ( onLoad ) onLoad( texture );
  14233. } );
  14234. loader.addEventListener( 'error', function ( event ) {
  14235. if ( onError ) onError( event.message );
  14236. } );
  14237. loader.crossOrigin = this.crossOrigin;
  14238. loader.load( url, image );
  14239. return texture;
  14240. },
  14241. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  14242. var texture = new THREE.CompressedTexture();
  14243. texture.mapping = mapping;
  14244. var request = new XMLHttpRequest();
  14245. request.onload = function () {
  14246. var buffer = request.response;
  14247. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14248. texture.format = dds.format;
  14249. texture.mipmaps = dds.mipmaps;
  14250. texture.image.width = dds.width;
  14251. texture.image.height = dds.height;
  14252. // gl.generateMipmap fails for compressed textures
  14253. // mipmaps must be embedded in the DDS file
  14254. // or texture filters must not use mipmapping
  14255. texture.generateMipmaps = false;
  14256. texture.needsUpdate = true;
  14257. if ( onLoad ) onLoad( texture );
  14258. }
  14259. request.onerror = onError;
  14260. request.open( 'GET', url, true );
  14261. request.responseType = "arraybuffer";
  14262. request.send( null );
  14263. return texture;
  14264. },
  14265. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  14266. var images = [];
  14267. images.loadCount = 0;
  14268. var texture = new THREE.Texture();
  14269. texture.image = images;
  14270. if ( mapping !== undefined ) texture.mapping = mapping;
  14271. // no flipping needed for cube textures
  14272. texture.flipY = false;
  14273. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14274. var cubeImage = new Image();
  14275. images[ i ] = cubeImage;
  14276. cubeImage.onload = function () {
  14277. images.loadCount += 1;
  14278. if ( images.loadCount === 6 ) {
  14279. texture.needsUpdate = true;
  14280. if ( onLoad ) onLoad();
  14281. }
  14282. };
  14283. cubeImage.onerror = onError;
  14284. cubeImage.crossOrigin = this.crossOrigin;
  14285. cubeImage.src = array[ i ];
  14286. }
  14287. return texture;
  14288. },
  14289. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  14290. var images = [];
  14291. images.loadCount = 0;
  14292. var texture = new THREE.CompressedTexture();
  14293. texture.image = images;
  14294. if ( mapping !== undefined ) texture.mapping = mapping;
  14295. // no flipping for cube textures
  14296. // (also flipping doesn't work for compressed textures )
  14297. texture.flipY = false;
  14298. // can't generate mipmaps for compressed textures
  14299. // mips must be embedded in DDS files
  14300. texture.generateMipmaps = false;
  14301. var generateCubeFaceCallback = function ( rq, img ) {
  14302. return function () {
  14303. var buffer = rq.response;
  14304. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14305. img.format = dds.format;
  14306. img.mipmaps = dds.mipmaps;
  14307. img.width = dds.width;
  14308. img.height = dds.height;
  14309. images.loadCount += 1;
  14310. if ( images.loadCount === 6 ) {
  14311. texture.format = dds.format;
  14312. texture.needsUpdate = true;
  14313. if ( onLoad ) onLoad();
  14314. }
  14315. }
  14316. }
  14317. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14318. var cubeImage = {};
  14319. images[ i ] = cubeImage;
  14320. var request = new XMLHttpRequest();
  14321. request.onload = generateCubeFaceCallback( request, cubeImage );
  14322. request.onerror = onError;
  14323. var url = array[ i ];
  14324. request.open( 'GET', url, true );
  14325. request.responseType = "arraybuffer";
  14326. request.send( null );
  14327. }
  14328. return texture;
  14329. },
  14330. parseDDS: function ( buffer, loadMipmaps ) {
  14331. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  14332. // Adapted from @toji's DDS utils
  14333. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  14334. // All values and structures referenced from:
  14335. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  14336. var DDS_MAGIC = 0x20534444;
  14337. var DDSD_CAPS = 0x1,
  14338. DDSD_HEIGHT = 0x2,
  14339. DDSD_WIDTH = 0x4,
  14340. DDSD_PITCH = 0x8,
  14341. DDSD_PIXELFORMAT = 0x1000,
  14342. DDSD_MIPMAPCOUNT = 0x20000,
  14343. DDSD_LINEARSIZE = 0x80000,
  14344. DDSD_DEPTH = 0x800000;
  14345. var DDSCAPS_COMPLEX = 0x8,
  14346. DDSCAPS_MIPMAP = 0x400000,
  14347. DDSCAPS_TEXTURE = 0x1000;
  14348. var DDSCAPS2_CUBEMAP = 0x200,
  14349. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  14350. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  14351. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  14352. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  14353. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  14354. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  14355. DDSCAPS2_VOLUME = 0x200000;
  14356. var DDPF_ALPHAPIXELS = 0x1,
  14357. DDPF_ALPHA = 0x2,
  14358. DDPF_FOURCC = 0x4,
  14359. DDPF_RGB = 0x40,
  14360. DDPF_YUV = 0x200,
  14361. DDPF_LUMINANCE = 0x20000;
  14362. function fourCCToInt32( value ) {
  14363. return value.charCodeAt(0) +
  14364. (value.charCodeAt(1) << 8) +
  14365. (value.charCodeAt(2) << 16) +
  14366. (value.charCodeAt(3) << 24);
  14367. }
  14368. function int32ToFourCC( value ) {
  14369. return String.fromCharCode(
  14370. value & 0xff,
  14371. (value >> 8) & 0xff,
  14372. (value >> 16) & 0xff,
  14373. (value >> 24) & 0xff
  14374. );
  14375. }
  14376. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  14377. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  14378. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  14379. var headerLengthInt = 31; // The header length in 32 bit ints
  14380. // Offsets into the header array
  14381. var off_magic = 0;
  14382. var off_size = 1;
  14383. var off_flags = 2;
  14384. var off_height = 3;
  14385. var off_width = 4;
  14386. var off_mipmapCount = 7;
  14387. var off_pfFlags = 20;
  14388. var off_pfFourCC = 21;
  14389. // Parse header
  14390. var header = new Int32Array( buffer, 0, headerLengthInt );
  14391. if ( header[ off_magic ] !== DDS_MAGIC ) {
  14392. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  14393. return dds;
  14394. }
  14395. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  14396. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  14397. return dds;
  14398. }
  14399. var blockBytes;
  14400. var fourCC = header[ off_pfFourCC ];
  14401. switch ( fourCC ) {
  14402. case FOURCC_DXT1:
  14403. blockBytes = 8;
  14404. dds.format = THREE.RGB_S3TC_DXT1_Format;
  14405. break;
  14406. case FOURCC_DXT3:
  14407. blockBytes = 16;
  14408. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  14409. break;
  14410. case FOURCC_DXT5:
  14411. blockBytes = 16;
  14412. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  14413. break;
  14414. default:
  14415. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  14416. return dds;
  14417. }
  14418. dds.mipmapCount = 1;
  14419. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  14420. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  14421. }
  14422. dds.width = header[ off_width ];
  14423. dds.height = header[ off_height ];
  14424. var dataOffset = header[ off_size ] + 4;
  14425. // Extract mipmaps buffers
  14426. var width = dds.width;
  14427. var height = dds.height;
  14428. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  14429. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  14430. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  14431. var mipmap = { "data": byteArray, "width": width, "height": height };
  14432. dds.mipmaps.push( mipmap );
  14433. dataOffset += dataLength;
  14434. width = Math.max( width * 0.5, 1 );
  14435. height = Math.max( height * 0.5, 1 );
  14436. }
  14437. return dds;
  14438. },
  14439. getNormalMap: function ( image, depth ) {
  14440. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  14441. var cross = function ( a, b ) {
  14442. 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 ] ];
  14443. }
  14444. var subtract = function ( a, b ) {
  14445. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  14446. }
  14447. var normalize = function ( a ) {
  14448. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  14449. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  14450. }
  14451. depth = depth | 1;
  14452. var width = image.width;
  14453. var height = image.height;
  14454. var canvas = document.createElement( 'canvas' );
  14455. canvas.width = width;
  14456. canvas.height = height;
  14457. var context = canvas.getContext( '2d' );
  14458. context.drawImage( image, 0, 0 );
  14459. var data = context.getImageData( 0, 0, width, height ).data;
  14460. var imageData = context.createImageData( width, height );
  14461. var output = imageData.data;
  14462. for ( var x = 0; x < width; x ++ ) {
  14463. for ( var y = 0; y < height; y ++ ) {
  14464. var ly = y - 1 < 0 ? 0 : y - 1;
  14465. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  14466. var lx = x - 1 < 0 ? 0 : x - 1;
  14467. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  14468. var points = [];
  14469. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  14470. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  14471. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  14472. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  14473. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  14474. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  14475. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  14476. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  14477. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  14478. var normals = [];
  14479. var num_points = points.length;
  14480. for ( var i = 0; i < num_points; i ++ ) {
  14481. var v1 = points[ i ];
  14482. var v2 = points[ ( i + 1 ) % num_points ];
  14483. v1 = subtract( v1, origin );
  14484. v2 = subtract( v2, origin );
  14485. normals.push( normalize( cross( v1, v2 ) ) );
  14486. }
  14487. var normal = [ 0, 0, 0 ];
  14488. for ( var i = 0; i < normals.length; i ++ ) {
  14489. normal[ 0 ] += normals[ i ][ 0 ];
  14490. normal[ 1 ] += normals[ i ][ 1 ];
  14491. normal[ 2 ] += normals[ i ][ 2 ];
  14492. }
  14493. normal[ 0 ] /= normals.length;
  14494. normal[ 1 ] /= normals.length;
  14495. normal[ 2 ] /= normals.length;
  14496. var idx = ( y * width + x ) * 4;
  14497. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14498. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14499. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  14500. output[ idx + 3 ] = 255;
  14501. }
  14502. }
  14503. context.putImageData( imageData, 0, 0 );
  14504. return canvas;
  14505. },
  14506. generateDataTexture: function ( width, height, color ) {
  14507. var size = width * height;
  14508. var data = new Uint8Array( 3 * size );
  14509. var r = Math.floor( color.r * 255 );
  14510. var g = Math.floor( color.g * 255 );
  14511. var b = Math.floor( color.b * 255 );
  14512. for ( var i = 0; i < size; i ++ ) {
  14513. data[ i * 3 ] = r;
  14514. data[ i * 3 + 1 ] = g;
  14515. data[ i * 3 + 2 ] = b;
  14516. }
  14517. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  14518. texture.needsUpdate = true;
  14519. return texture;
  14520. }
  14521. };
  14522. /**
  14523. * @author alteredq / http://alteredqualia.com/
  14524. */
  14525. THREE.SceneUtils = {
  14526. createMultiMaterialObject: function ( geometry, materials ) {
  14527. var group = new THREE.Object3D();
  14528. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  14529. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  14530. }
  14531. return group;
  14532. },
  14533. detach : function ( child, parent, scene ) {
  14534. child.applyMatrix( parent.matrixWorld );
  14535. parent.remove( child );
  14536. scene.add( child );
  14537. },
  14538. attach: function ( child, scene, parent ) {
  14539. var matrixWorldInverse = new THREE.Matrix4();
  14540. matrixWorldInverse.getInverse( parent.matrixWorld );
  14541. child.applyMatrix( matrixWorldInverse );
  14542. scene.remove( child );
  14543. parent.add( child );
  14544. }
  14545. };
  14546. /**
  14547. * @author alteredq / http://alteredqualia.com/
  14548. * @author mrdoob / http://mrdoob.com/
  14549. *
  14550. * ShaderUtils currently contains:
  14551. *
  14552. * fresnel
  14553. * normal
  14554. * cube
  14555. *
  14556. */
  14557. if ( THREE.WebGLRenderer ) {
  14558. THREE.ShaderUtils = {
  14559. lib: {
  14560. /* -------------------------------------------------------------------------
  14561. // Fresnel shader
  14562. // - based on Nvidia Cg tutorial
  14563. ------------------------------------------------------------------------- */
  14564. 'fresnel': {
  14565. uniforms: {
  14566. "mRefractionRatio": { type: "f", value: 1.02 },
  14567. "mFresnelBias": { type: "f", value: 0.1 },
  14568. "mFresnelPower": { type: "f", value: 2.0 },
  14569. "mFresnelScale": { type: "f", value: 1.0 },
  14570. "tCube": { type: "t", value: null }
  14571. },
  14572. fragmentShader: [
  14573. "uniform samplerCube tCube;",
  14574. "varying vec3 vReflect;",
  14575. "varying vec3 vRefract[3];",
  14576. "varying float vReflectionFactor;",
  14577. "void main() {",
  14578. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  14579. "vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  14580. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  14581. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  14582. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  14583. "refractedColor.a = 1.0;",
  14584. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  14585. "}"
  14586. ].join("\n"),
  14587. vertexShader: [
  14588. "uniform float mRefractionRatio;",
  14589. "uniform float mFresnelBias;",
  14590. "uniform float mFresnelScale;",
  14591. "uniform float mFresnelPower;",
  14592. "varying vec3 vReflect;",
  14593. "varying vec3 vRefract[3];",
  14594. "varying float vReflectionFactor;",
  14595. "void main() {",
  14596. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14597. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  14598. "vec3 nWorld = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  14599. "vec3 I = mPosition.xyz - cameraPosition;",
  14600. "vReflect = reflect( I, nWorld );",
  14601. "vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
  14602. "vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
  14603. "vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
  14604. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",
  14605. "gl_Position = projectionMatrix * mvPosition;",
  14606. "}"
  14607. ].join("\n")
  14608. },
  14609. /* -------------------------------------------------------------------------
  14610. // Normal map shader
  14611. // - Blinn-Phong
  14612. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  14613. // - point and directional lights (use with "lights: true" material option)
  14614. ------------------------------------------------------------------------- */
  14615. 'normal' : {
  14616. uniforms: THREE.UniformsUtils.merge( [
  14617. THREE.UniformsLib[ "fog" ],
  14618. THREE.UniformsLib[ "lights" ],
  14619. THREE.UniformsLib[ "shadowmap" ],
  14620. {
  14621. "enableAO" : { type: "i", value: 0 },
  14622. "enableDiffuse" : { type: "i", value: 0 },
  14623. "enableSpecular" : { type: "i", value: 0 },
  14624. "enableReflection": { type: "i", value: 0 },
  14625. "enableDisplacement": { type: "i", value: 0 },
  14626. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  14627. "tDiffuse" : { type: "t", value: null },
  14628. "tCube" : { type: "t", value: null },
  14629. "tNormal" : { type: "t", value: null },
  14630. "tSpecular" : { type: "t", value: null },
  14631. "tAO" : { type: "t", value: null },
  14632. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14633. "uDisplacementBias": { type: "f", value: 0.0 },
  14634. "uDisplacementScale": { type: "f", value: 1.0 },
  14635. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14636. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  14637. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14638. "uShininess": { type: "f", value: 30 },
  14639. "uOpacity": { type: "f", value: 1 },
  14640. "useRefract": { type: "i", value: 0 },
  14641. "uRefractionRatio": { type: "f", value: 0.98 },
  14642. "uReflectivity": { type: "f", value: 0.5 },
  14643. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  14644. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14645. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  14646. }
  14647. ] ),
  14648. fragmentShader: [
  14649. "uniform vec3 uAmbientColor;",
  14650. "uniform vec3 uDiffuseColor;",
  14651. "uniform vec3 uSpecularColor;",
  14652. "uniform float uShininess;",
  14653. "uniform float uOpacity;",
  14654. "uniform bool enableDiffuse;",
  14655. "uniform bool enableSpecular;",
  14656. "uniform bool enableAO;",
  14657. "uniform bool enableReflection;",
  14658. "uniform sampler2D tDiffuse;",
  14659. "uniform sampler2D tNormal;",
  14660. "uniform sampler2D tSpecular;",
  14661. "uniform sampler2D tAO;",
  14662. "uniform samplerCube tCube;",
  14663. "uniform vec2 uNormalScale;",
  14664. "uniform bool useRefract;",
  14665. "uniform float uRefractionRatio;",
  14666. "uniform float uReflectivity;",
  14667. "varying vec3 vTangent;",
  14668. "varying vec3 vBinormal;",
  14669. "varying vec3 vNormal;",
  14670. "varying vec2 vUv;",
  14671. "uniform vec3 ambientLightColor;",
  14672. "#if MAX_DIR_LIGHTS > 0",
  14673. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  14674. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  14675. "#endif",
  14676. "#if MAX_HEMI_LIGHTS > 0",
  14677. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  14678. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  14679. "uniform vec3 hemisphereLightPosition[ MAX_HEMI_LIGHTS ];",
  14680. "#endif",
  14681. "#if MAX_POINT_LIGHTS > 0",
  14682. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  14683. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  14684. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  14685. "#endif",
  14686. "#if MAX_SPOT_LIGHTS > 0",
  14687. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  14688. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  14689. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  14690. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  14691. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  14692. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  14693. "#endif",
  14694. "#ifdef WRAP_AROUND",
  14695. "uniform vec3 wrapRGB;",
  14696. "#endif",
  14697. "varying vec3 vWorldPosition;",
  14698. "varying vec3 vViewPosition;",
  14699. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14700. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14701. "void main() {",
  14702. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  14703. "vec3 specularTex = vec3( 1.0 );",
  14704. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  14705. "normalTex.xy *= uNormalScale;",
  14706. "normalTex = normalize( normalTex );",
  14707. "if( enableDiffuse ) {",
  14708. "#ifdef GAMMA_INPUT",
  14709. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  14710. "texelColor.xyz *= texelColor.xyz;",
  14711. "gl_FragColor = gl_FragColor * texelColor;",
  14712. "#else",
  14713. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  14714. "#endif",
  14715. "}",
  14716. "if( enableAO ) {",
  14717. "#ifdef GAMMA_INPUT",
  14718. "vec4 aoColor = texture2D( tAO, vUv );",
  14719. "aoColor.xyz *= aoColor.xyz;",
  14720. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  14721. "#else",
  14722. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  14723. "#endif",
  14724. "}",
  14725. "if( enableSpecular )",
  14726. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  14727. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  14728. "vec3 finalNormal = tsb * normalTex;",
  14729. "#ifdef FLIP_SIDED",
  14730. "finalNormal = -finalNormal;",
  14731. "#endif",
  14732. "vec3 normal = normalize( finalNormal );",
  14733. "vec3 viewPosition = normalize( vViewPosition );",
  14734. // point lights
  14735. "#if MAX_POINT_LIGHTS > 0",
  14736. "vec3 pointDiffuse = vec3( 0.0 );",
  14737. "vec3 pointSpecular = vec3( 0.0 );",
  14738. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  14739. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  14740. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  14741. "float pointDistance = 1.0;",
  14742. "if ( pointLightDistance[ i ] > 0.0 )",
  14743. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  14744. "pointVector = normalize( pointVector );",
  14745. // diffuse
  14746. "#ifdef WRAP_AROUND",
  14747. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  14748. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  14749. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  14750. "#else",
  14751. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  14752. "#endif",
  14753. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  14754. // specular
  14755. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  14756. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  14757. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  14758. "#ifdef PHYSICALLY_BASED_SHADING",
  14759. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14760. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14761. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  14762. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  14763. "#else",
  14764. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  14765. "#endif",
  14766. "}",
  14767. "#endif",
  14768. // spot lights
  14769. "#if MAX_SPOT_LIGHTS > 0",
  14770. "vec3 spotDiffuse = vec3( 0.0 );",
  14771. "vec3 spotSpecular = vec3( 0.0 );",
  14772. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  14773. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  14774. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  14775. "float spotDistance = 1.0;",
  14776. "if ( spotLightDistance[ i ] > 0.0 )",
  14777. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  14778. "spotVector = normalize( spotVector );",
  14779. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  14780. "if ( spotEffect > spotLightAngle[ i ] ) {",
  14781. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  14782. // diffuse
  14783. "#ifdef WRAP_AROUND",
  14784. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  14785. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  14786. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  14787. "#else",
  14788. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  14789. "#endif",
  14790. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  14791. // specular
  14792. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  14793. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  14794. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  14795. "#ifdef PHYSICALLY_BASED_SHADING",
  14796. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14797. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14798. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  14799. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  14800. "#else",
  14801. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  14802. "#endif",
  14803. "}",
  14804. "}",
  14805. "#endif",
  14806. // directional lights
  14807. "#if MAX_DIR_LIGHTS > 0",
  14808. "vec3 dirDiffuse = vec3( 0.0 );",
  14809. "vec3 dirSpecular = vec3( 0.0 );",
  14810. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  14811. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  14812. "vec3 dirVector = normalize( lDirection.xyz );",
  14813. // diffuse
  14814. "#ifdef WRAP_AROUND",
  14815. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  14816. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  14817. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  14818. "#else",
  14819. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  14820. "#endif",
  14821. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  14822. // specular
  14823. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  14824. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  14825. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  14826. "#ifdef PHYSICALLY_BASED_SHADING",
  14827. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14828. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14829. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  14830. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  14831. "#else",
  14832. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  14833. "#endif",
  14834. "}",
  14835. "#endif",
  14836. // hemisphere lights
  14837. "#if MAX_HEMI_LIGHTS > 0",
  14838. "vec3 hemiDiffuse = vec3( 0.0 );",
  14839. "vec3 hemiSpecular = vec3( 0.0 );" ,
  14840. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  14841. "vec4 lPosition = viewMatrix * vec4( hemisphereLightPosition[ i ], 1.0 );",
  14842. "vec3 lVector = normalize( lPosition.xyz + vViewPosition.xyz );",
  14843. // diffuse
  14844. "float dotProduct = dot( normal, lVector );",
  14845. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  14846. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  14847. "hemiDiffuse += uDiffuseColor * hemiColor;",
  14848. // specular (sky light)
  14849. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  14850. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  14851. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  14852. // specular (ground light)
  14853. "vec3 lVectorGround = normalize( -lPosition.xyz + vViewPosition.xyz );",
  14854. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  14855. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  14856. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  14857. "#ifdef PHYSICALLY_BASED_SHADING",
  14858. "float dotProductGround = dot( normal, lVectorGround );",
  14859. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14860. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14861. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  14862. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  14863. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  14864. "#else",
  14865. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  14866. "#endif",
  14867. "}",
  14868. "#endif",
  14869. // all lights contribution summation
  14870. "vec3 totalDiffuse = vec3( 0.0 );",
  14871. "vec3 totalSpecular = vec3( 0.0 );",
  14872. "#if MAX_DIR_LIGHTS > 0",
  14873. "totalDiffuse += dirDiffuse;",
  14874. "totalSpecular += dirSpecular;",
  14875. "#endif",
  14876. "#if MAX_HEMI_LIGHTS > 0",
  14877. "totalDiffuse += hemiDiffuse;",
  14878. "totalSpecular += hemiSpecular;",
  14879. "#endif",
  14880. "#if MAX_POINT_LIGHTS > 0",
  14881. "totalDiffuse += pointDiffuse;",
  14882. "totalSpecular += pointSpecular;",
  14883. "#endif",
  14884. "#if MAX_SPOT_LIGHTS > 0",
  14885. "totalDiffuse += spotDiffuse;",
  14886. "totalSpecular += spotSpecular;",
  14887. "#endif",
  14888. "#ifdef METAL",
  14889. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  14890. "#else",
  14891. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  14892. "#endif",
  14893. "if ( enableReflection ) {",
  14894. "vec3 vReflect;",
  14895. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  14896. "if ( useRefract ) {",
  14897. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  14898. "} else {",
  14899. "vReflect = reflect( cameraToVertex, normal );",
  14900. "}",
  14901. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  14902. "#ifdef GAMMA_INPUT",
  14903. "cubeColor.xyz *= cubeColor.xyz;",
  14904. "#endif",
  14905. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  14906. "}",
  14907. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14908. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14909. THREE.ShaderChunk[ "fog_fragment" ],
  14910. "}"
  14911. ].join("\n"),
  14912. vertexShader: [
  14913. "attribute vec4 tangent;",
  14914. "uniform vec2 uOffset;",
  14915. "uniform vec2 uRepeat;",
  14916. "uniform bool enableDisplacement;",
  14917. "#ifdef VERTEX_TEXTURES",
  14918. "uniform sampler2D tDisplacement;",
  14919. "uniform float uDisplacementScale;",
  14920. "uniform float uDisplacementBias;",
  14921. "#endif",
  14922. "varying vec3 vTangent;",
  14923. "varying vec3 vBinormal;",
  14924. "varying vec3 vNormal;",
  14925. "varying vec2 vUv;",
  14926. "varying vec3 vWorldPosition;",
  14927. "varying vec3 vViewPosition;",
  14928. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14929. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14930. "void main() {",
  14931. THREE.ShaderChunk[ "skinbase_vertex" ],
  14932. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14933. // normal, tangent and binormal vectors
  14934. "#ifdef USE_SKINNING",
  14935. "vNormal = normalMatrix * skinnedNormal.xyz;",
  14936. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  14937. "vTangent = normalMatrix * skinnedTangent.xyz;",
  14938. "#else",
  14939. "vNormal = normalMatrix * normal;",
  14940. "vTangent = normalMatrix * tangent.xyz;",
  14941. "#endif",
  14942. "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
  14943. "vUv = uv * uRepeat + uOffset;",
  14944. // displacement mapping
  14945. "vec3 displacedPosition;",
  14946. "#ifdef VERTEX_TEXTURES",
  14947. "if ( enableDisplacement ) {",
  14948. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  14949. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  14950. "displacedPosition = position + normalize( normal ) * df;",
  14951. "} else {",
  14952. "#ifdef USE_SKINNING",
  14953. "vec4 skinVertex = vec4( position, 1.0 );",
  14954. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  14955. "skinned += boneMatY * skinVertex * skinWeight.y;",
  14956. "displacedPosition = skinned.xyz;",
  14957. "#else",
  14958. "displacedPosition = position;",
  14959. "#endif",
  14960. "}",
  14961. "#else",
  14962. "#ifdef USE_SKINNING",
  14963. "vec4 skinVertex = vec4( position, 1.0 );",
  14964. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  14965. "skinned += boneMatY * skinVertex * skinWeight.y;",
  14966. "displacedPosition = skinned.xyz;",
  14967. "#else",
  14968. "displacedPosition = position;",
  14969. "#endif",
  14970. "#endif",
  14971. //
  14972. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  14973. "vec4 mPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  14974. "gl_Position = projectionMatrix * mvPosition;",
  14975. //
  14976. "vWorldPosition = mPosition.xyz;",
  14977. "vViewPosition = -mvPosition.xyz;",
  14978. // shadows
  14979. "#ifdef USE_SHADOWMAP",
  14980. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  14981. "vShadowCoord[ i ] = shadowMatrix[ i ] * mPosition;",
  14982. "}",
  14983. "#endif",
  14984. "}"
  14985. ].join("\n")
  14986. },
  14987. /* -------------------------------------------------------------------------
  14988. // Cube map shader
  14989. ------------------------------------------------------------------------- */
  14990. 'cube': {
  14991. uniforms: { "tCube": { type: "t", value: null },
  14992. "tFlip": { type: "f", value: -1 } },
  14993. vertexShader: [
  14994. "varying vec3 vViewPosition;",
  14995. "void main() {",
  14996. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  14997. "vViewPosition = cameraPosition - mPosition.xyz;",
  14998. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  14999. "}"
  15000. ].join("\n"),
  15001. fragmentShader: [
  15002. "uniform samplerCube tCube;",
  15003. "uniform float tFlip;",
  15004. "varying vec3 vViewPosition;",
  15005. "void main() {",
  15006. "vec3 wPos = cameraPosition - vViewPosition;",
  15007. "gl_FragColor = textureCube( tCube, vec3( tFlip * wPos.x, wPos.yz ) );",
  15008. "}"
  15009. ].join("\n")
  15010. }
  15011. }
  15012. };
  15013. };
  15014. /**
  15015. * @author zz85 / http://www.lab4games.net/zz85/blog
  15016. * @author alteredq / http://alteredqualia.com/
  15017. *
  15018. * For Text operations in three.js (See TextGeometry)
  15019. *
  15020. * It uses techniques used in:
  15021. *
  15022. * typeface.js and canvastext
  15023. * For converting fonts and rendering with javascript
  15024. * http://typeface.neocracy.org
  15025. *
  15026. * Triangulation ported from AS3
  15027. * Simple Polygon Triangulation
  15028. * http://actionsnippet.com/?p=1462
  15029. *
  15030. * A Method to triangulate shapes with holes
  15031. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15032. *
  15033. */
  15034. THREE.FontUtils = {
  15035. faces : {},
  15036. // Just for now. face[weight][style]
  15037. face : "helvetiker",
  15038. weight: "normal",
  15039. style : "normal",
  15040. size : 150,
  15041. divisions : 10,
  15042. getFace : function() {
  15043. return this.faces[ this.face ][ this.weight ][ this.style ];
  15044. },
  15045. loadFace : function( data ) {
  15046. var family = data.familyName.toLowerCase();
  15047. var ThreeFont = this;
  15048. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15049. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15050. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15051. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15052. return data;
  15053. },
  15054. drawText : function( text ) {
  15055. var characterPts = [], allPts = [];
  15056. // RenderText
  15057. var i, p,
  15058. face = this.getFace(),
  15059. scale = this.size / face.resolution,
  15060. offset = 0,
  15061. chars = String( text ).split( '' ),
  15062. length = chars.length;
  15063. var fontPaths = [];
  15064. for ( i = 0; i < length; i ++ ) {
  15065. var path = new THREE.Path();
  15066. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15067. offset += ret.offset;
  15068. fontPaths.push( ret.path );
  15069. }
  15070. // get the width
  15071. var width = offset / 2;
  15072. //
  15073. // for ( p = 0; p < allPts.length; p++ ) {
  15074. //
  15075. // allPts[ p ].x -= width;
  15076. //
  15077. // }
  15078. //var extract = this.extractPoints( allPts, characterPts );
  15079. //extract.contour = allPts;
  15080. //extract.paths = fontPaths;
  15081. //extract.offset = width;
  15082. return { paths : fontPaths, offset : width };
  15083. },
  15084. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15085. var pts = [];
  15086. var i, i2, divisions,
  15087. outline, action, length,
  15088. scaleX, scaleY,
  15089. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15090. laste,
  15091. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15092. if ( !glyph ) return;
  15093. if ( glyph.o ) {
  15094. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15095. length = outline.length;
  15096. scaleX = scale;
  15097. scaleY = scale;
  15098. for ( i = 0; i < length; ) {
  15099. action = outline[ i ++ ];
  15100. //console.log( action );
  15101. switch( action ) {
  15102. case 'm':
  15103. // Move To
  15104. x = outline[ i++ ] * scaleX + offset;
  15105. y = outline[ i++ ] * scaleY;
  15106. path.moveTo( x, y );
  15107. break;
  15108. case 'l':
  15109. // Line To
  15110. x = outline[ i++ ] * scaleX + offset;
  15111. y = outline[ i++ ] * scaleY;
  15112. path.lineTo(x,y);
  15113. break;
  15114. case 'q':
  15115. // QuadraticCurveTo
  15116. cpx = outline[ i++ ] * scaleX + offset;
  15117. cpy = outline[ i++ ] * scaleY;
  15118. cpx1 = outline[ i++ ] * scaleX + offset;
  15119. cpy1 = outline[ i++ ] * scaleY;
  15120. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15121. laste = pts[ pts.length - 1 ];
  15122. if ( laste ) {
  15123. cpx0 = laste.x;
  15124. cpy0 = laste.y;
  15125. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15126. var t = i2 / divisions;
  15127. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15128. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15129. }
  15130. }
  15131. break;
  15132. case 'b':
  15133. // Cubic Bezier Curve
  15134. cpx = outline[ i++ ] * scaleX + offset;
  15135. cpy = outline[ i++ ] * scaleY;
  15136. cpx1 = outline[ i++ ] * scaleX + offset;
  15137. cpy1 = outline[ i++ ] * -scaleY;
  15138. cpx2 = outline[ i++ ] * scaleX + offset;
  15139. cpy2 = outline[ i++ ] * -scaleY;
  15140. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15141. laste = pts[ pts.length - 1 ];
  15142. if ( laste ) {
  15143. cpx0 = laste.x;
  15144. cpy0 = laste.y;
  15145. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15146. var t = i2 / divisions;
  15147. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15148. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15149. }
  15150. }
  15151. break;
  15152. }
  15153. }
  15154. }
  15155. return { offset: glyph.ha*scale, path:path};
  15156. }
  15157. };
  15158. THREE.FontUtils.generateShapes = function( text, parameters ) {
  15159. // Parameters
  15160. parameters = parameters || {};
  15161. var size = parameters.size !== undefined ? parameters.size : 100;
  15162. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  15163. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  15164. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  15165. var style = parameters.style !== undefined ? parameters.style : "normal";
  15166. THREE.FontUtils.size = size;
  15167. THREE.FontUtils.divisions = curveSegments;
  15168. THREE.FontUtils.face = font;
  15169. THREE.FontUtils.weight = weight;
  15170. THREE.FontUtils.style = style;
  15171. // Get a Font data json object
  15172. var data = THREE.FontUtils.drawText( text );
  15173. var paths = data.paths;
  15174. var shapes = [];
  15175. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  15176. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  15177. }
  15178. return shapes;
  15179. };
  15180. /**
  15181. * This code is a quick port of code written in C++ which was submitted to
  15182. * flipcode.com by John W. Ratcliff // July 22, 2000
  15183. * See original code and more information here:
  15184. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15185. *
  15186. * ported to actionscript by Zevan Rosser
  15187. * www.actionsnippet.com
  15188. *
  15189. * ported to javascript by Joshua Koo
  15190. * http://www.lab4games.net/zz85/blog
  15191. *
  15192. */
  15193. ( function( namespace ) {
  15194. var EPSILON = 0.0000000001;
  15195. // takes in an contour array and returns
  15196. var process = function( contour, indices ) {
  15197. var n = contour.length;
  15198. if ( n < 3 ) return null;
  15199. var result = [],
  15200. verts = [],
  15201. vertIndices = [];
  15202. /* we want a counter-clockwise polygon in verts */
  15203. var u, v, w;
  15204. if ( area( contour ) > 0.0 ) {
  15205. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  15206. } else {
  15207. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  15208. }
  15209. var nv = n;
  15210. /* remove nv - 2 vertices, creating 1 triangle every time */
  15211. var count = 2 * nv; /* error detection */
  15212. for( v = nv - 1; nv > 2; ) {
  15213. /* if we loop, it is probably a non-simple polygon */
  15214. if ( ( count-- ) <= 0 ) {
  15215. //** Triangulate: ERROR - probable bad polygon!
  15216. //throw ( "Warning, unable to triangulate polygon!" );
  15217. //return null;
  15218. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15219. console.log( "Warning, unable to triangulate polygon!" );
  15220. if ( indices ) return vertIndices;
  15221. return result;
  15222. }
  15223. /* three consecutive vertices in current polygon, <u,v,w> */
  15224. u = v; if ( nv <= u ) u = 0; /* previous */
  15225. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15226. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15227. if ( snip( contour, u, v, w, nv, verts ) ) {
  15228. var a, b, c, s, t;
  15229. /* true names of the vertices */
  15230. a = verts[ u ];
  15231. b = verts[ v ];
  15232. c = verts[ w ];
  15233. /* output Triangle */
  15234. /*
  15235. result.push( contour[ a ] );
  15236. result.push( contour[ b ] );
  15237. result.push( contour[ c ] );
  15238. */
  15239. result.push( [ contour[ a ],
  15240. contour[ b ],
  15241. contour[ c ] ] );
  15242. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15243. /* remove v from the remaining polygon */
  15244. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  15245. verts[ s ] = verts[ t ];
  15246. }
  15247. nv--;
  15248. /* reset error detection counter */
  15249. count = 2 * nv;
  15250. }
  15251. }
  15252. if ( indices ) return vertIndices;
  15253. return result;
  15254. };
  15255. // calculate area of the contour polygon
  15256. var area = function ( contour ) {
  15257. var n = contour.length;
  15258. var a = 0.0;
  15259. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  15260. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15261. }
  15262. return a * 0.5;
  15263. };
  15264. // see if p is inside triangle abc
  15265. var insideTriangle = function( ax, ay,
  15266. bx, by,
  15267. cx, cy,
  15268. px, py ) {
  15269. var aX, aY, bX, bY;
  15270. var cX, cY, apx, apy;
  15271. var bpx, bpy, cpx, cpy;
  15272. var cCROSSap, bCROSScp, aCROSSbp;
  15273. aX = cx - bx; aY = cy - by;
  15274. bX = ax - cx; bY = ay - cy;
  15275. cX = bx - ax; cY = by - ay;
  15276. apx= px -ax; apy= py - ay;
  15277. bpx= px - bx; bpy= py - by;
  15278. cpx= px - cx; cpy= py - cy;
  15279. aCROSSbp = aX*bpy - aY*bpx;
  15280. cCROSSap = cX*apy - cY*apx;
  15281. bCROSScp = bX*cpy - bY*cpx;
  15282. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  15283. };
  15284. var snip = function ( contour, u, v, w, n, verts ) {
  15285. var p;
  15286. var ax, ay, bx, by;
  15287. var cx, cy, px, py;
  15288. ax = contour[ verts[ u ] ].x;
  15289. ay = contour[ verts[ u ] ].y;
  15290. bx = contour[ verts[ v ] ].x;
  15291. by = contour[ verts[ v ] ].y;
  15292. cx = contour[ verts[ w ] ].x;
  15293. cy = contour[ verts[ w ] ].y;
  15294. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  15295. for ( p = 0; p < n; p++ ) {
  15296. if( (p == u) || (p == v) || (p == w) ) continue;
  15297. px = contour[ verts[ p ] ].x
  15298. py = contour[ verts[ p ] ].y
  15299. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  15300. }
  15301. return true;
  15302. };
  15303. namespace.Triangulate = process;
  15304. namespace.Triangulate.area = area;
  15305. return namespace;
  15306. })(THREE.FontUtils);
  15307. // To use the typeface.js face files, hook up the API
  15308. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  15309. * @author zz85 / http://www.lab4games.net/zz85/blog
  15310. * Extensible curve object
  15311. *
  15312. * Some common of Curve methods
  15313. * .getPoint(t), getTangent(t)
  15314. * .getPointAt(u), getTagentAt(u)
  15315. * .getPoints(), .getSpacedPoints()
  15316. * .getLength()
  15317. * .updateArcLengths()
  15318. *
  15319. * This file contains following classes:
  15320. *
  15321. * -- 2d classes --
  15322. * THREE.Curve
  15323. * THREE.LineCurve
  15324. * THREE.QuadraticBezierCurve
  15325. * THREE.CubicBezierCurve
  15326. * THREE.SplineCurve
  15327. * THREE.ArcCurve
  15328. * THREE.EllipseCurve
  15329. *
  15330. * -- 3d classes --
  15331. * THREE.LineCurve3
  15332. * THREE.QuadraticBezierCurve3
  15333. * THREE.CubicBezierCurve3
  15334. * THREE.SplineCurve3
  15335. * THREE.ClosedSplineCurve3
  15336. *
  15337. * A series of curves can be represented as a THREE.CurvePath
  15338. *
  15339. **/
  15340. /**************************************************************
  15341. * Abstract Curve base class
  15342. **************************************************************/
  15343. THREE.Curve = function () {
  15344. };
  15345. // Virtual base class method to overwrite and implement in subclasses
  15346. // - t [0 .. 1]
  15347. THREE.Curve.prototype.getPoint = function ( t ) {
  15348. console.log( "Warning, getPoint() not implemented!" );
  15349. return null;
  15350. };
  15351. // Get point at relative position in curve according to arc length
  15352. // - u [0 .. 1]
  15353. THREE.Curve.prototype.getPointAt = function ( u ) {
  15354. var t = this.getUtoTmapping( u );
  15355. return this.getPoint( t );
  15356. };
  15357. // Get sequence of points using getPoint( t )
  15358. THREE.Curve.prototype.getPoints = function ( divisions ) {
  15359. if ( !divisions ) divisions = 5;
  15360. var d, pts = [];
  15361. for ( d = 0; d <= divisions; d ++ ) {
  15362. pts.push( this.getPoint( d / divisions ) );
  15363. }
  15364. return pts;
  15365. };
  15366. // Get sequence of points using getPointAt( u )
  15367. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  15368. if ( !divisions ) divisions = 5;
  15369. var d, pts = [];
  15370. for ( d = 0; d <= divisions; d ++ ) {
  15371. pts.push( this.getPointAt( d / divisions ) );
  15372. }
  15373. return pts;
  15374. };
  15375. // Get total curve arc length
  15376. THREE.Curve.prototype.getLength = function () {
  15377. var lengths = this.getLengths();
  15378. return lengths[ lengths.length - 1 ];
  15379. };
  15380. // Get list of cumulative segment lengths
  15381. THREE.Curve.prototype.getLengths = function ( divisions ) {
  15382. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  15383. if ( this.cacheArcLengths
  15384. && ( this.cacheArcLengths.length == divisions + 1 )
  15385. && !this.needsUpdate) {
  15386. //console.log( "cached", this.cacheArcLengths );
  15387. return this.cacheArcLengths;
  15388. }
  15389. this.needsUpdate = false;
  15390. var cache = [];
  15391. var current, last = this.getPoint( 0 );
  15392. var p, sum = 0;
  15393. cache.push( 0 );
  15394. for ( p = 1; p <= divisions; p ++ ) {
  15395. current = this.getPoint ( p / divisions );
  15396. sum += current.distanceTo( last );
  15397. cache.push( sum );
  15398. last = current;
  15399. }
  15400. this.cacheArcLengths = cache;
  15401. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  15402. };
  15403. THREE.Curve.prototype.updateArcLengths = function() {
  15404. this.needsUpdate = true;
  15405. this.getLengths();
  15406. };
  15407. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  15408. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  15409. var arcLengths = this.getLengths();
  15410. var i = 0, il = arcLengths.length;
  15411. var targetArcLength; // The targeted u distance value to get
  15412. if ( distance ) {
  15413. targetArcLength = distance;
  15414. } else {
  15415. targetArcLength = u * arcLengths[ il - 1 ];
  15416. }
  15417. //var time = Date.now();
  15418. // binary search for the index with largest value smaller than target u distance
  15419. var low = 0, high = il - 1, comparison;
  15420. while ( low <= high ) {
  15421. 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
  15422. comparison = arcLengths[ i ] - targetArcLength;
  15423. if ( comparison < 0 ) {
  15424. low = i + 1;
  15425. continue;
  15426. } else if ( comparison > 0 ) {
  15427. high = i - 1;
  15428. continue;
  15429. } else {
  15430. high = i;
  15431. break;
  15432. // DONE
  15433. }
  15434. }
  15435. i = high;
  15436. //console.log('b' , i, low, high, Date.now()- time);
  15437. if ( arcLengths[ i ] == targetArcLength ) {
  15438. var t = i / ( il - 1 );
  15439. return t;
  15440. }
  15441. // we could get finer grain at lengths, or use simple interpolatation between two points
  15442. var lengthBefore = arcLengths[ i ];
  15443. var lengthAfter = arcLengths[ i + 1 ];
  15444. var segmentLength = lengthAfter - lengthBefore;
  15445. // determine where we are between the 'before' and 'after' points
  15446. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  15447. // add that fractional amount to t
  15448. var t = ( i + segmentFraction ) / ( il -1 );
  15449. return t;
  15450. };
  15451. // In 2D space, there are actually 2 normal vectors,
  15452. // and in 3D space, infinte
  15453. // TODO this should be depreciated.
  15454. THREE.Curve.prototype.getNormalVector = function( t ) {
  15455. var vec = this.getTangent( t );
  15456. return new THREE.Vector2( -vec.y , vec.x );
  15457. };
  15458. // Returns a unit vector tangent at t
  15459. // In case any sub curve does not implement its tangent / normal finding,
  15460. // we get 2 points with a small delta and find a gradient of the 2 points
  15461. // which seems to make a reasonable approximation
  15462. THREE.Curve.prototype.getTangent = function( t ) {
  15463. var delta = 0.0001;
  15464. var t1 = t - delta;
  15465. var t2 = t + delta;
  15466. // Capping in case of danger
  15467. if ( t1 < 0 ) t1 = 0;
  15468. if ( t2 > 1 ) t2 = 1;
  15469. var pt1 = this.getPoint( t1 );
  15470. var pt2 = this.getPoint( t2 );
  15471. var vec = pt2.clone().subSelf(pt1);
  15472. return vec.normalize();
  15473. };
  15474. THREE.Curve.prototype.getTangentAt = function ( u ) {
  15475. var t = this.getUtoTmapping( u );
  15476. return this.getTangent( t );
  15477. };
  15478. /**************************************************************
  15479. * Line
  15480. **************************************************************/
  15481. THREE.LineCurve = function ( v1, v2 ) {
  15482. this.v1 = v1;
  15483. this.v2 = v2;
  15484. };
  15485. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  15486. THREE.LineCurve.prototype.getPoint = function ( t ) {
  15487. var point = this.v2.clone().subSelf(this.v1);
  15488. point.multiplyScalar( t ).addSelf( this.v1 );
  15489. return point;
  15490. };
  15491. // Line curve is linear, so we can overwrite default getPointAt
  15492. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  15493. return this.getPoint( u );
  15494. };
  15495. THREE.LineCurve.prototype.getTangent = function( t ) {
  15496. var tangent = this.v2.clone().subSelf(this.v1);
  15497. return tangent.normalize();
  15498. };
  15499. /**************************************************************
  15500. * Quadratic Bezier curve
  15501. **************************************************************/
  15502. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  15503. this.v0 = v0;
  15504. this.v1 = v1;
  15505. this.v2 = v2;
  15506. };
  15507. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15508. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  15509. var tx, ty;
  15510. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15511. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15512. return new THREE.Vector2( tx, ty );
  15513. };
  15514. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  15515. var tx, ty;
  15516. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  15517. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  15518. // returns unit vector
  15519. var tangent = new THREE.Vector2( tx, ty );
  15520. tangent.normalize();
  15521. return tangent;
  15522. };
  15523. /**************************************************************
  15524. * Cubic Bezier curve
  15525. **************************************************************/
  15526. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  15527. this.v0 = v0;
  15528. this.v1 = v1;
  15529. this.v2 = v2;
  15530. this.v3 = v3;
  15531. };
  15532. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15533. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  15534. var tx, ty;
  15535. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15536. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15537. return new THREE.Vector2( tx, ty );
  15538. };
  15539. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  15540. var tx, ty;
  15541. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15542. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15543. var tangent = new THREE.Vector2( tx, ty );
  15544. tangent.normalize();
  15545. return tangent;
  15546. };
  15547. /**************************************************************
  15548. * Spline curve
  15549. **************************************************************/
  15550. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  15551. this.points = (points == undefined) ? [] : points;
  15552. };
  15553. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  15554. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  15555. var v = new THREE.Vector2();
  15556. var c = [];
  15557. var points = this.points, point, intPoint, weight;
  15558. point = ( points.length - 1 ) * t;
  15559. intPoint = Math.floor( point );
  15560. weight = point - intPoint;
  15561. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15562. c[ 1 ] = intPoint;
  15563. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  15564. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  15565. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15566. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15567. return v;
  15568. };
  15569. /**************************************************************
  15570. * Ellipse curve
  15571. **************************************************************/
  15572. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  15573. aStartAngle, aEndAngle,
  15574. aClockwise ) {
  15575. this.aX = aX;
  15576. this.aY = aY;
  15577. this.xRadius = xRadius;
  15578. this.yRadius = yRadius;
  15579. this.aStartAngle = aStartAngle;
  15580. this.aEndAngle = aEndAngle;
  15581. this.aClockwise = aClockwise;
  15582. };
  15583. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  15584. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  15585. var deltaAngle = this.aEndAngle - this.aStartAngle;
  15586. if ( !this.aClockwise ) {
  15587. t = 1 - t;
  15588. }
  15589. var angle = this.aStartAngle + t * deltaAngle;
  15590. var tx = this.aX + this.xRadius * Math.cos( angle );
  15591. var ty = this.aY + this.yRadius * Math.sin( angle );
  15592. return new THREE.Vector2( tx, ty );
  15593. };
  15594. /**************************************************************
  15595. * Arc curve
  15596. **************************************************************/
  15597. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  15598. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  15599. };
  15600. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  15601. /**************************************************************
  15602. * Utils
  15603. **************************************************************/
  15604. THREE.Curve.Utils = {
  15605. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  15606. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  15607. },
  15608. // Puay Bing, thanks for helping with this derivative!
  15609. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  15610. return -3 * p0 * (1 - t) * (1 - t) +
  15611. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  15612. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  15613. 3 * t * t * p3;
  15614. },
  15615. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  15616. // To check if my formulas are correct
  15617. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  15618. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  15619. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  15620. var h11 = 3 * t * t - 2 * t; // t3 − t2
  15621. return h00 + h10 + h01 + h11;
  15622. },
  15623. // Catmull-Rom
  15624. interpolate: function( p0, p1, p2, p3, t ) {
  15625. var v0 = ( p2 - p0 ) * 0.5;
  15626. var v1 = ( p3 - p1 ) * 0.5;
  15627. var t2 = t * t;
  15628. var t3 = t * t2;
  15629. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  15630. }
  15631. };
  15632. // TODO: Transformation for Curves?
  15633. /**************************************************************
  15634. * 3D Curves
  15635. **************************************************************/
  15636. // A Factory method for creating new curve subclasses
  15637. THREE.Curve.create = function ( constructor, getPointFunc ) {
  15638. constructor.prototype = Object.create( THREE.Curve.prototype );
  15639. constructor.prototype.getPoint = getPointFunc;
  15640. return constructor;
  15641. };
  15642. /**************************************************************
  15643. * Line3D
  15644. **************************************************************/
  15645. THREE.LineCurve3 = THREE.Curve.create(
  15646. function ( v1, v2 ) {
  15647. this.v1 = v1;
  15648. this.v2 = v2;
  15649. },
  15650. function ( t ) {
  15651. var r = new THREE.Vector3();
  15652. r.sub( this.v2, this.v1 ); // diff
  15653. r.multiplyScalar( t );
  15654. r.addSelf( this.v1 );
  15655. return r;
  15656. }
  15657. );
  15658. /**************************************************************
  15659. * Quadratic Bezier 3D curve
  15660. **************************************************************/
  15661. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  15662. function ( v0, v1, v2 ) {
  15663. this.v0 = v0;
  15664. this.v1 = v1;
  15665. this.v2 = v2;
  15666. },
  15667. function ( t ) {
  15668. var tx, ty, tz;
  15669. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15670. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15671. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  15672. return new THREE.Vector3( tx, ty, tz );
  15673. }
  15674. );
  15675. /**************************************************************
  15676. * Cubic Bezier 3D curve
  15677. **************************************************************/
  15678. THREE.CubicBezierCurve3 = THREE.Curve.create(
  15679. function ( v0, v1, v2, v3 ) {
  15680. this.v0 = v0;
  15681. this.v1 = v1;
  15682. this.v2 = v2;
  15683. this.v3 = v3;
  15684. },
  15685. function ( t ) {
  15686. var tx, ty, tz;
  15687. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15688. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15689. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  15690. return new THREE.Vector3( tx, ty, tz );
  15691. }
  15692. );
  15693. /**************************************************************
  15694. * Spline 3D curve
  15695. **************************************************************/
  15696. THREE.SplineCurve3 = THREE.Curve.create(
  15697. function ( points /* array of Vector3 */) {
  15698. this.points = (points == undefined) ? [] : points;
  15699. },
  15700. function ( t ) {
  15701. var v = new THREE.Vector3();
  15702. var c = [];
  15703. var points = this.points, point, intPoint, weight;
  15704. point = ( points.length - 1 ) * t;
  15705. intPoint = Math.floor( point );
  15706. weight = point - intPoint;
  15707. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15708. c[ 1 ] = intPoint;
  15709. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15710. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15711. var pt0 = points[ c[0] ],
  15712. pt1 = points[ c[1] ],
  15713. pt2 = points[ c[2] ],
  15714. pt3 = points[ c[3] ];
  15715. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  15716. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  15717. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  15718. return v;
  15719. }
  15720. );
  15721. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  15722. // var v = new THREE.Vector3();
  15723. // var c = [];
  15724. // var points = this.points, point, intPoint, weight;
  15725. // point = ( points.length - 1 ) * t;
  15726. // intPoint = Math.floor( point );
  15727. // weight = point - intPoint;
  15728. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15729. // c[ 1 ] = intPoint;
  15730. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15731. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15732. // var pt0 = points[ c[0] ],
  15733. // pt1 = points[ c[1] ],
  15734. // pt2 = points[ c[2] ],
  15735. // pt3 = points[ c[3] ];
  15736. // // t = weight;
  15737. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  15738. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  15739. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  15740. // return v;
  15741. // }
  15742. /**************************************************************
  15743. * Closed Spline 3D curve
  15744. **************************************************************/
  15745. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  15746. function ( points /* array of Vector3 */) {
  15747. this.points = (points == undefined) ? [] : points;
  15748. },
  15749. function ( t ) {
  15750. var v = new THREE.Vector3();
  15751. var c = [];
  15752. var points = this.points, point, intPoint, weight;
  15753. point = ( points.length - 0 ) * t;
  15754. // This needs to be from 0-length +1
  15755. intPoint = Math.floor( point );
  15756. weight = point - intPoint;
  15757. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  15758. c[ 0 ] = ( intPoint - 1 ) % points.length;
  15759. c[ 1 ] = ( intPoint ) % points.length;
  15760. c[ 2 ] = ( intPoint + 1 ) % points.length;
  15761. c[ 3 ] = ( intPoint + 2 ) % points.length;
  15762. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15763. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15764. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  15765. return v;
  15766. }
  15767. );
  15768. /**
  15769. * @author zz85 / http://www.lab4games.net/zz85/blog
  15770. *
  15771. **/
  15772. /**************************************************************
  15773. * Curved Path - a curve path is simply a array of connected
  15774. * curves, but retains the api of a curve
  15775. **************************************************************/
  15776. THREE.CurvePath = function () {
  15777. this.curves = [];
  15778. this.bends = [];
  15779. this.autoClose = false; // Automatically closes the path
  15780. };
  15781. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  15782. THREE.CurvePath.prototype.add = function ( curve ) {
  15783. this.curves.push( curve );
  15784. };
  15785. THREE.CurvePath.prototype.checkConnection = function() {
  15786. // TODO
  15787. // If the ending of curve is not connected to the starting
  15788. // or the next curve, then, this is not a real path
  15789. };
  15790. THREE.CurvePath.prototype.closePath = function() {
  15791. // TODO Test
  15792. // and verify for vector3 (needs to implement equals)
  15793. // Add a line curve if start and end of lines are not connected
  15794. var startPoint = this.curves[0].getPoint(0);
  15795. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  15796. if (!startPoint.equals(endPoint)) {
  15797. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  15798. }
  15799. };
  15800. // To get accurate point with reference to
  15801. // entire path distance at time t,
  15802. // following has to be done:
  15803. // 1. Length of each sub path have to be known
  15804. // 2. Locate and identify type of curve
  15805. // 3. Get t for the curve
  15806. // 4. Return curve.getPointAt(t')
  15807. THREE.CurvePath.prototype.getPoint = function( t ) {
  15808. var d = t * this.getLength();
  15809. var curveLengths = this.getCurveLengths();
  15810. var i = 0, diff, curve;
  15811. // To think about boundaries points.
  15812. while ( i < curveLengths.length ) {
  15813. if ( curveLengths[ i ] >= d ) {
  15814. diff = curveLengths[ i ] - d;
  15815. curve = this.curves[ i ];
  15816. var u = 1 - diff / curve.getLength();
  15817. return curve.getPointAt( u );
  15818. break;
  15819. }
  15820. i ++;
  15821. }
  15822. return null;
  15823. // loop where sum != 0, sum > d , sum+1 <d
  15824. };
  15825. /*
  15826. THREE.CurvePath.prototype.getTangent = function( t ) {
  15827. };*/
  15828. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  15829. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  15830. // getPoint() depends on getLength
  15831. THREE.CurvePath.prototype.getLength = function() {
  15832. var lens = this.getCurveLengths();
  15833. return lens[ lens.length - 1 ];
  15834. };
  15835. // Compute lengths and cache them
  15836. // We cannot overwrite getLengths() because UtoT mapping uses it.
  15837. THREE.CurvePath.prototype.getCurveLengths = function() {
  15838. // We use cache values if curves and cache array are same length
  15839. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  15840. return this.cacheLengths;
  15841. };
  15842. // Get length of subsurve
  15843. // Push sums into cached array
  15844. var lengths = [], sums = 0;
  15845. var i, il = this.curves.length;
  15846. for ( i = 0; i < il; i ++ ) {
  15847. sums += this.curves[ i ].getLength();
  15848. lengths.push( sums );
  15849. }
  15850. this.cacheLengths = lengths;
  15851. return lengths;
  15852. };
  15853. // Returns min and max coordinates, as well as centroid
  15854. THREE.CurvePath.prototype.getBoundingBox = function () {
  15855. var points = this.getPoints();
  15856. var maxX, maxY, maxZ;
  15857. var minX, minY, minZ;
  15858. maxX = maxY = Number.NEGATIVE_INFINITY;
  15859. minX = minY = Number.POSITIVE_INFINITY;
  15860. var p, i, il, sum;
  15861. var v3 = points[0] instanceof THREE.Vector3;
  15862. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  15863. for ( i = 0, il = points.length; i < il; i ++ ) {
  15864. p = points[ i ];
  15865. if ( p.x > maxX ) maxX = p.x;
  15866. else if ( p.x < minX ) minX = p.x;
  15867. if ( p.y > maxY ) maxY = p.y;
  15868. else if ( p.y < minY ) minY = p.y;
  15869. if (v3) {
  15870. if ( p.z > maxZ ) maxZ = p.z;
  15871. else if ( p.z < minZ ) minZ = p.z;
  15872. }
  15873. sum.addSelf( p );
  15874. }
  15875. var ret = {
  15876. minX: minX,
  15877. minY: minY,
  15878. maxX: maxX,
  15879. maxY: maxY,
  15880. centroid: sum.divideScalar( il )
  15881. };
  15882. if (v3) {
  15883. ret.maxZ = maxZ;
  15884. ret.minZ = minZ;
  15885. }
  15886. return ret;
  15887. };
  15888. /**************************************************************
  15889. * Create Geometries Helpers
  15890. **************************************************************/
  15891. /// Generate geometry from path points (for Line or ParticleSystem objects)
  15892. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  15893. var pts = this.getPoints( divisions, true );
  15894. return this.createGeometry( pts );
  15895. };
  15896. // Generate geometry from equidistance sampling along the path
  15897. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  15898. var pts = this.getSpacedPoints( divisions, true );
  15899. return this.createGeometry( pts );
  15900. };
  15901. THREE.CurvePath.prototype.createGeometry = function( points ) {
  15902. var geometry = new THREE.Geometry();
  15903. for ( var i = 0; i < points.length; i ++ ) {
  15904. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  15905. }
  15906. return geometry;
  15907. };
  15908. /**************************************************************
  15909. * Bend / Wrap Helper Methods
  15910. **************************************************************/
  15911. // Wrap path / Bend modifiers?
  15912. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  15913. this.bends.push( bendpath );
  15914. };
  15915. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  15916. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  15917. var i, il;
  15918. if ( !bends ) {
  15919. bends = this.bends;
  15920. }
  15921. for ( i = 0, il = bends.length; i < il; i ++ ) {
  15922. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  15923. }
  15924. return oldPts;
  15925. };
  15926. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  15927. var oldPts = this.getSpacedPoints( segments );
  15928. var i, il;
  15929. if ( !bends ) {
  15930. bends = this.bends;
  15931. }
  15932. for ( i = 0, il = bends.length; i < il; i ++ ) {
  15933. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  15934. }
  15935. return oldPts;
  15936. };
  15937. // This returns getPoints() bend/wrapped around the contour of a path.
  15938. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  15939. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  15940. var bounds = this.getBoundingBox();
  15941. var i, il, p, oldX, oldY, xNorm;
  15942. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  15943. p = oldPts[ i ];
  15944. oldX = p.x;
  15945. oldY = p.y;
  15946. xNorm = oldX / bounds.maxX;
  15947. // If using actual distance, for length > path, requires line extrusions
  15948. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  15949. xNorm = path.getUtoTmapping( xNorm, oldX );
  15950. // check for out of bounds?
  15951. var pathPt = path.getPoint( xNorm );
  15952. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  15953. p.x = pathPt.x + normal.x;
  15954. p.y = pathPt.y + normal.y;
  15955. }
  15956. return oldPts;
  15957. };
  15958. /**
  15959. * @author alteredq / http://alteredqualia.com/
  15960. */
  15961. THREE.Gyroscope = function () {
  15962. THREE.Object3D.call( this );
  15963. };
  15964. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  15965. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  15966. this.matrixAutoUpdate && this.updateMatrix();
  15967. // update matrixWorld
  15968. if ( this.matrixWorldNeedsUpdate || force ) {
  15969. if ( this.parent ) {
  15970. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  15971. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  15972. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  15973. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  15974. } else {
  15975. this.matrixWorld.copy( this.matrix );
  15976. }
  15977. this.matrixWorldNeedsUpdate = false;
  15978. force = true;
  15979. }
  15980. // update children
  15981. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  15982. this.children[ i ].updateMatrixWorld( force );
  15983. }
  15984. };
  15985. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  15986. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  15987. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  15988. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  15989. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  15990. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  15991. /**
  15992. * @author zz85 / http://www.lab4games.net/zz85/blog
  15993. * Creates free form 2d path using series of points, lines or curves.
  15994. *
  15995. **/
  15996. THREE.Path = function ( points ) {
  15997. THREE.CurvePath.call(this);
  15998. this.actions = [];
  15999. if ( points ) {
  16000. this.fromPoints( points );
  16001. }
  16002. };
  16003. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16004. THREE.PathActions = {
  16005. MOVE_TO: 'moveTo',
  16006. LINE_TO: 'lineTo',
  16007. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16008. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16009. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16010. ARC: 'arc', // Circle
  16011. ELLIPSE: 'ellipse'
  16012. };
  16013. // TODO Clean up PATH API
  16014. // Create path using straight lines to connect all points
  16015. // - vectors: array of Vector2
  16016. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16017. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16018. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16019. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16020. };
  16021. };
  16022. // startPath() endPath()?
  16023. THREE.Path.prototype.moveTo = function ( x, y ) {
  16024. var args = Array.prototype.slice.call( arguments );
  16025. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16026. };
  16027. THREE.Path.prototype.lineTo = function ( x, y ) {
  16028. var args = Array.prototype.slice.call( arguments );
  16029. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16030. var x0 = lastargs[ lastargs.length - 2 ];
  16031. var y0 = lastargs[ lastargs.length - 1 ];
  16032. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16033. this.curves.push( curve );
  16034. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16035. };
  16036. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16037. var args = Array.prototype.slice.call( arguments );
  16038. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16039. var x0 = lastargs[ lastargs.length - 2 ];
  16040. var y0 = lastargs[ lastargs.length - 1 ];
  16041. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16042. new THREE.Vector2( aCPx, aCPy ),
  16043. new THREE.Vector2( aX, aY ) );
  16044. this.curves.push( curve );
  16045. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16046. };
  16047. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16048. aCP2x, aCP2y,
  16049. aX, aY ) {
  16050. var args = Array.prototype.slice.call( arguments );
  16051. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16052. var x0 = lastargs[ lastargs.length - 2 ];
  16053. var y0 = lastargs[ lastargs.length - 1 ];
  16054. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16055. new THREE.Vector2( aCP1x, aCP1y ),
  16056. new THREE.Vector2( aCP2x, aCP2y ),
  16057. new THREE.Vector2( aX, aY ) );
  16058. this.curves.push( curve );
  16059. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16060. };
  16061. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16062. var args = Array.prototype.slice.call( arguments );
  16063. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16064. var x0 = lastargs[ lastargs.length - 2 ];
  16065. var y0 = lastargs[ lastargs.length - 1 ];
  16066. //---
  16067. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16068. Array.prototype.push.apply( npts, pts );
  16069. var curve = new THREE.SplineCurve( npts );
  16070. this.curves.push( curve );
  16071. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16072. };
  16073. // FUTURE: Change the API or follow canvas API?
  16074. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16075. aStartAngle, aEndAngle, aClockwise ) {
  16076. var lastargs = this.actions[ this.actions.length - 1].args;
  16077. var x0 = lastargs[ lastargs.length - 2 ];
  16078. var y0 = lastargs[ lastargs.length - 1 ];
  16079. this.absarc(aX + x0, aY + y0, aRadius,
  16080. aStartAngle, aEndAngle, aClockwise );
  16081. };
  16082. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16083. aStartAngle, aEndAngle, aClockwise ) {
  16084. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16085. };
  16086. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16087. aStartAngle, aEndAngle, aClockwise ) {
  16088. var lastargs = this.actions[ this.actions.length - 1].args;
  16089. var x0 = lastargs[ lastargs.length - 2 ];
  16090. var y0 = lastargs[ lastargs.length - 1 ];
  16091. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16092. aStartAngle, aEndAngle, aClockwise );
  16093. };
  16094. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16095. aStartAngle, aEndAngle, aClockwise ) {
  16096. var args = Array.prototype.slice.call( arguments );
  16097. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16098. aStartAngle, aEndAngle, aClockwise );
  16099. this.curves.push( curve );
  16100. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  16101. args.push(lastPoint.x);
  16102. args.push(lastPoint.y);
  16103. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16104. };
  16105. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16106. if ( ! divisions ) divisions = 40;
  16107. var points = [];
  16108. for ( var i = 0; i < divisions; i ++ ) {
  16109. points.push( this.getPoint( i / divisions ) );
  16110. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16111. }
  16112. // if ( closedPath ) {
  16113. //
  16114. // points.push( points[ 0 ] );
  16115. //
  16116. // }
  16117. return points;
  16118. };
  16119. /* Return an array of vectors based on contour of the path */
  16120. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16121. if (this.useSpacedPoints) {
  16122. console.log('tata');
  16123. return this.getSpacedPoints( divisions, closedPath );
  16124. }
  16125. divisions = divisions || 12;
  16126. var points = [];
  16127. var i, il, item, action, args;
  16128. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16129. laste, j,
  16130. t, tx, ty;
  16131. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16132. item = this.actions[ i ];
  16133. action = item.action;
  16134. args = item.args;
  16135. switch( action ) {
  16136. case THREE.PathActions.MOVE_TO:
  16137. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16138. break;
  16139. case THREE.PathActions.LINE_TO:
  16140. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16141. break;
  16142. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16143. cpx = args[ 2 ];
  16144. cpy = args[ 3 ];
  16145. cpx1 = args[ 0 ];
  16146. cpy1 = args[ 1 ];
  16147. if ( points.length > 0 ) {
  16148. laste = points[ points.length - 1 ];
  16149. cpx0 = laste.x;
  16150. cpy0 = laste.y;
  16151. } else {
  16152. laste = this.actions[ i - 1 ].args;
  16153. cpx0 = laste[ laste.length - 2 ];
  16154. cpy0 = laste[ laste.length - 1 ];
  16155. }
  16156. for ( j = 1; j <= divisions; j ++ ) {
  16157. t = j / divisions;
  16158. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16159. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16160. points.push( new THREE.Vector2( tx, ty ) );
  16161. }
  16162. break;
  16163. case THREE.PathActions.BEZIER_CURVE_TO:
  16164. cpx = args[ 4 ];
  16165. cpy = args[ 5 ];
  16166. cpx1 = args[ 0 ];
  16167. cpy1 = args[ 1 ];
  16168. cpx2 = args[ 2 ];
  16169. cpy2 = args[ 3 ];
  16170. if ( points.length > 0 ) {
  16171. laste = points[ points.length - 1 ];
  16172. cpx0 = laste.x;
  16173. cpy0 = laste.y;
  16174. } else {
  16175. laste = this.actions[ i - 1 ].args;
  16176. cpx0 = laste[ laste.length - 2 ];
  16177. cpy0 = laste[ laste.length - 1 ];
  16178. }
  16179. for ( j = 1; j <= divisions; j ++ ) {
  16180. t = j / divisions;
  16181. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16182. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16183. points.push( new THREE.Vector2( tx, ty ) );
  16184. }
  16185. break;
  16186. case THREE.PathActions.CSPLINE_THRU:
  16187. laste = this.actions[ i - 1 ].args;
  16188. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16189. var spts = [ last ];
  16190. var n = divisions * args[ 0 ].length;
  16191. spts = spts.concat( args[ 0 ] );
  16192. var spline = new THREE.SplineCurve( spts );
  16193. for ( j = 1; j <= n; j ++ ) {
  16194. points.push( spline.getPointAt( j / n ) ) ;
  16195. }
  16196. break;
  16197. case THREE.PathActions.ARC:
  16198. var aX = args[ 0 ], aY = args[ 1 ],
  16199. aRadius = args[ 2 ],
  16200. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16201. aClockwise = !!args[ 5 ];
  16202. var deltaAngle = aEndAngle - aStartAngle;
  16203. var angle;
  16204. var tdivisions = divisions * 2;
  16205. for ( j = 1; j <= tdivisions; j ++ ) {
  16206. t = j / tdivisions;
  16207. if ( ! aClockwise ) {
  16208. t = 1 - t;
  16209. }
  16210. angle = aStartAngle + t * deltaAngle;
  16211. tx = aX + aRadius * Math.cos( angle );
  16212. ty = aY + aRadius * Math.sin( angle );
  16213. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16214. points.push( new THREE.Vector2( tx, ty ) );
  16215. }
  16216. //console.log(points);
  16217. break;
  16218. case THREE.PathActions.ELLIPSE:
  16219. var aX = args[ 0 ], aY = args[ 1 ],
  16220. xRadius = args[ 2 ],
  16221. yRadius = args[ 3 ],
  16222. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16223. aClockwise = !!args[ 6 ];
  16224. var deltaAngle = aEndAngle - aStartAngle;
  16225. var angle;
  16226. var tdivisions = divisions * 2;
  16227. for ( j = 1; j <= tdivisions; j ++ ) {
  16228. t = j / tdivisions;
  16229. if ( ! aClockwise ) {
  16230. t = 1 - t;
  16231. }
  16232. angle = aStartAngle + t * deltaAngle;
  16233. tx = aX + xRadius * Math.cos( angle );
  16234. ty = aY + yRadius * Math.sin( angle );
  16235. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16236. points.push( new THREE.Vector2( tx, ty ) );
  16237. }
  16238. //console.log(points);
  16239. break;
  16240. } // end switch
  16241. }
  16242. // Normalize to remove the closing point by default.
  16243. var lastPoint = points[ points.length - 1];
  16244. var EPSILON = 0.0000000001;
  16245. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  16246. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  16247. points.splice( points.length - 1, 1);
  16248. if ( closedPath ) {
  16249. points.push( points[ 0 ] );
  16250. }
  16251. return points;
  16252. };
  16253. // Breaks path into shapes
  16254. THREE.Path.prototype.toShapes = function() {
  16255. var i, il, item, action, args;
  16256. var subPaths = [], lastPath = new THREE.Path();
  16257. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16258. item = this.actions[ i ];
  16259. args = item.args;
  16260. action = item.action;
  16261. if ( action == THREE.PathActions.MOVE_TO ) {
  16262. if ( lastPath.actions.length != 0 ) {
  16263. subPaths.push( lastPath );
  16264. lastPath = new THREE.Path();
  16265. }
  16266. }
  16267. lastPath[ action ].apply( lastPath, args );
  16268. }
  16269. if ( lastPath.actions.length != 0 ) {
  16270. subPaths.push( lastPath );
  16271. }
  16272. // console.log(subPaths);
  16273. if ( subPaths.length == 0 ) return [];
  16274. var tmpPath, tmpShape, shapes = [];
  16275. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  16276. // console.log("Holes first", holesFirst);
  16277. if ( subPaths.length == 1) {
  16278. tmpPath = subPaths[0];
  16279. tmpShape = new THREE.Shape();
  16280. tmpShape.actions = tmpPath.actions;
  16281. tmpShape.curves = tmpPath.curves;
  16282. shapes.push( tmpShape );
  16283. return shapes;
  16284. };
  16285. if ( holesFirst ) {
  16286. tmpShape = new THREE.Shape();
  16287. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16288. tmpPath = subPaths[ i ];
  16289. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16290. tmpShape.actions = tmpPath.actions;
  16291. tmpShape.curves = tmpPath.curves;
  16292. shapes.push( tmpShape );
  16293. tmpShape = new THREE.Shape();
  16294. //console.log('cw', i);
  16295. } else {
  16296. tmpShape.holes.push( tmpPath );
  16297. //console.log('ccw', i);
  16298. }
  16299. }
  16300. } else {
  16301. // Shapes first
  16302. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16303. tmpPath = subPaths[ i ];
  16304. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16305. if ( tmpShape ) shapes.push( tmpShape );
  16306. tmpShape = new THREE.Shape();
  16307. tmpShape.actions = tmpPath.actions;
  16308. tmpShape.curves = tmpPath.curves;
  16309. } else {
  16310. tmpShape.holes.push( tmpPath );
  16311. }
  16312. }
  16313. shapes.push( tmpShape );
  16314. }
  16315. //console.log("shape", shapes);
  16316. return shapes;
  16317. };
  16318. /**
  16319. * @author zz85 / http://www.lab4games.net/zz85/blog
  16320. * Defines a 2d shape plane using paths.
  16321. **/
  16322. // STEP 1 Create a path.
  16323. // STEP 2 Turn path into shape.
  16324. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  16325. // STEP 3a - Extract points from each shape, turn to vertices
  16326. // STEP 3b - Triangulate each shape, add faces.
  16327. THREE.Shape = function ( ) {
  16328. THREE.Path.apply( this, arguments );
  16329. this.holes = [];
  16330. };
  16331. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  16332. // Convenience method to return ExtrudeGeometry
  16333. THREE.Shape.prototype.extrude = function ( options ) {
  16334. var extruded = new THREE.ExtrudeGeometry( this, options );
  16335. return extruded;
  16336. };
  16337. // Convenience method to return ShapeGeometry
  16338. THREE.Shape.prototype.makeGeometry = function ( options ) {
  16339. var geometry = new THREE.ShapeGeometry( this, options );
  16340. return geometry;
  16341. };
  16342. // Get points of holes
  16343. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  16344. var i, il = this.holes.length, holesPts = [];
  16345. for ( i = 0; i < il; i ++ ) {
  16346. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  16347. }
  16348. return holesPts;
  16349. };
  16350. // Get points of holes (spaced by regular distance)
  16351. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  16352. var i, il = this.holes.length, holesPts = [];
  16353. for ( i = 0; i < il; i ++ ) {
  16354. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  16355. }
  16356. return holesPts;
  16357. };
  16358. // Get points of shape and holes (keypoints based on segments parameter)
  16359. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  16360. return {
  16361. shape: this.getTransformedPoints( divisions ),
  16362. holes: this.getPointsHoles( divisions )
  16363. };
  16364. };
  16365. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  16366. if (this.useSpacedPoints) {
  16367. return this.extractAllSpacedPoints(divisions);
  16368. }
  16369. return this.extractAllPoints(divisions);
  16370. };
  16371. //
  16372. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  16373. //
  16374. // return {
  16375. //
  16376. // shape: this.transform( bend, divisions ),
  16377. // holes: this.getPointsHoles( divisions, bend )
  16378. //
  16379. // };
  16380. //
  16381. // };
  16382. // Get points of shape and holes (spaced by regular distance)
  16383. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  16384. return {
  16385. shape: this.getTransformedSpacedPoints( divisions ),
  16386. holes: this.getSpacedPointsHoles( divisions )
  16387. };
  16388. };
  16389. /**************************************************************
  16390. * Utils
  16391. **************************************************************/
  16392. THREE.Shape.Utils = {
  16393. /*
  16394. contour - array of vector2 for contour
  16395. holes - array of array of vector2
  16396. */
  16397. removeHoles: function ( contour, holes ) {
  16398. var shape = contour.concat(); // work on this shape
  16399. var allpoints = shape.concat();
  16400. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  16401. var prevShapeVert, nextShapeVert,
  16402. prevHoleVert, nextHoleVert,
  16403. holeIndex, shapeIndex,
  16404. shapeId, shapeGroup,
  16405. h, h2,
  16406. hole, shortest, d,
  16407. p, pts1, pts2,
  16408. tmpShape1, tmpShape2,
  16409. tmpHole1, tmpHole2,
  16410. verts = [];
  16411. for ( h = 0; h < holes.length; h ++ ) {
  16412. hole = holes[ h ];
  16413. /*
  16414. shapeholes[ h ].concat(); // preserves original
  16415. holes.push( hole );
  16416. */
  16417. Array.prototype.push.apply( allpoints, hole );
  16418. shortest = Number.POSITIVE_INFINITY;
  16419. // Find the shortest pair of pts between shape and hole
  16420. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  16421. // Using distanceToSquared() intead of distanceTo() should speed a little
  16422. // since running square roots operations are reduced.
  16423. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  16424. pts1 = hole[ h2 ];
  16425. var dist = [];
  16426. for ( p = 0; p < shape.length; p++ ) {
  16427. pts2 = shape[ p ];
  16428. d = pts1.distanceToSquared( pts2 );
  16429. dist.push( d );
  16430. if ( d < shortest ) {
  16431. shortest = d;
  16432. holeIndex = h2;
  16433. shapeIndex = p;
  16434. }
  16435. }
  16436. }
  16437. //console.log("shortest", shortest, dist);
  16438. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16439. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16440. var areaapts = [
  16441. hole[ holeIndex ],
  16442. shape[ shapeIndex ],
  16443. shape[ prevShapeVert ]
  16444. ];
  16445. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  16446. var areabpts = [
  16447. hole[ holeIndex ],
  16448. hole[ prevHoleVert ],
  16449. shape[ shapeIndex ]
  16450. ];
  16451. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  16452. var shapeOffset = 1;
  16453. var holeOffset = -1;
  16454. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  16455. shapeIndex += shapeOffset;
  16456. holeIndex += holeOffset;
  16457. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16458. shapeIndex %= shape.length;
  16459. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16460. holeIndex %= hole.length;
  16461. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16462. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16463. areaapts = [
  16464. hole[ holeIndex ],
  16465. shape[ shapeIndex ],
  16466. shape[ prevShapeVert ]
  16467. ];
  16468. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  16469. areabpts = [
  16470. hole[ holeIndex ],
  16471. hole[ prevHoleVert ],
  16472. shape[ shapeIndex ]
  16473. ];
  16474. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  16475. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  16476. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  16477. // In case areas are not correct.
  16478. //console.log("USE THIS");
  16479. shapeIndex = oldShapeIndex;
  16480. holeIndex = oldHoleIndex ;
  16481. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16482. shapeIndex %= shape.length;
  16483. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16484. holeIndex %= hole.length;
  16485. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16486. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16487. } else {
  16488. //console.log("USE THAT ")
  16489. }
  16490. tmpShape1 = shape.slice( 0, shapeIndex );
  16491. tmpShape2 = shape.slice( shapeIndex );
  16492. tmpHole1 = hole.slice( holeIndex );
  16493. tmpHole2 = hole.slice( 0, holeIndex );
  16494. // Should check orders here again?
  16495. var trianglea = [
  16496. hole[ holeIndex ],
  16497. shape[ shapeIndex ],
  16498. shape[ prevShapeVert ]
  16499. ];
  16500. var triangleb = [
  16501. hole[ holeIndex ] ,
  16502. hole[ prevHoleVert ],
  16503. shape[ shapeIndex ]
  16504. ];
  16505. verts.push( trianglea );
  16506. verts.push( triangleb );
  16507. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  16508. }
  16509. return {
  16510. shape:shape, /* shape with no holes */
  16511. isolatedPts: verts, /* isolated faces */
  16512. allpoints: allpoints
  16513. }
  16514. },
  16515. triangulateShape: function ( contour, holes ) {
  16516. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  16517. var shape = shapeWithoutHoles.shape,
  16518. allpoints = shapeWithoutHoles.allpoints,
  16519. isolatedPts = shapeWithoutHoles.isolatedPts;
  16520. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  16521. // 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.
  16522. //console.log( "triangles",triangles, triangles.length );
  16523. //console.log( "allpoints",allpoints, allpoints.length );
  16524. var i, il, f, face,
  16525. key, index,
  16526. allPointsMap = {},
  16527. isolatedPointsMap = {};
  16528. // prepare all points map
  16529. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  16530. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  16531. if ( allPointsMap[ key ] !== undefined ) {
  16532. console.log( "Duplicate point", key );
  16533. }
  16534. allPointsMap[ key ] = i;
  16535. }
  16536. // check all face vertices against all points map
  16537. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  16538. face = triangles[ i ];
  16539. for ( f = 0; f < 3; f ++ ) {
  16540. key = face[ f ].x + ":" + face[ f ].y;
  16541. index = allPointsMap[ key ];
  16542. if ( index !== undefined ) {
  16543. face[ f ] = index;
  16544. }
  16545. }
  16546. }
  16547. // check isolated points vertices against all points map
  16548. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  16549. face = isolatedPts[ i ];
  16550. for ( f = 0; f < 3; f ++ ) {
  16551. key = face[ f ].x + ":" + face[ f ].y;
  16552. index = allPointsMap[ key ];
  16553. if ( index !== undefined ) {
  16554. face[ f ] = index;
  16555. }
  16556. }
  16557. }
  16558. return triangles.concat( isolatedPts );
  16559. }, // end triangulate shapes
  16560. /*
  16561. triangulate2 : function( pts, holes ) {
  16562. // For use with Poly2Tri.js
  16563. var allpts = pts.concat();
  16564. var shape = [];
  16565. for (var p in pts) {
  16566. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  16567. }
  16568. var swctx = new js.poly2tri.SweepContext(shape);
  16569. for (var h in holes) {
  16570. var aHole = holes[h];
  16571. var newHole = []
  16572. for (i in aHole) {
  16573. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  16574. allpts.push(aHole[i]);
  16575. }
  16576. swctx.AddHole(newHole);
  16577. }
  16578. var find;
  16579. var findIndexForPt = function (pt) {
  16580. find = new THREE.Vector2(pt.x, pt.y);
  16581. var p;
  16582. for (p=0, pl = allpts.length; p<pl; p++) {
  16583. if (allpts[p].equals(find)) return p;
  16584. }
  16585. return -1;
  16586. };
  16587. // triangulate
  16588. js.poly2tri.sweep.Triangulate(swctx);
  16589. var triangles = swctx.GetTriangles();
  16590. var tr ;
  16591. var facesPts = [];
  16592. for (var t in triangles) {
  16593. tr = triangles[t];
  16594. facesPts.push([
  16595. findIndexForPt(tr.GetPoint(0)),
  16596. findIndexForPt(tr.GetPoint(1)),
  16597. findIndexForPt(tr.GetPoint(2))
  16598. ]);
  16599. }
  16600. // console.log(facesPts);
  16601. // console.log("triangles", triangles.length, triangles);
  16602. // Returns array of faces with 3 element each
  16603. return facesPts;
  16604. },
  16605. */
  16606. isClockWise: function ( pts ) {
  16607. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  16608. },
  16609. // Bezier Curves formulas obtained from
  16610. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  16611. // Quad Bezier Functions
  16612. b2p0: function ( t, p ) {
  16613. var k = 1 - t;
  16614. return k * k * p;
  16615. },
  16616. b2p1: function ( t, p ) {
  16617. return 2 * ( 1 - t ) * t * p;
  16618. },
  16619. b2p2: function ( t, p ) {
  16620. return t * t * p;
  16621. },
  16622. b2: function ( t, p0, p1, p2 ) {
  16623. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  16624. },
  16625. // Cubic Bezier Functions
  16626. b3p0: function ( t, p ) {
  16627. var k = 1 - t;
  16628. return k * k * k * p;
  16629. },
  16630. b3p1: function ( t, p ) {
  16631. var k = 1 - t;
  16632. return 3 * k * k * t * p;
  16633. },
  16634. b3p2: function ( t, p ) {
  16635. var k = 1 - t;
  16636. return 3 * k * t * t * p;
  16637. },
  16638. b3p3: function ( t, p ) {
  16639. return t * t * t * p;
  16640. },
  16641. b3: function ( t, p0, p1, p2, p3 ) {
  16642. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  16643. }
  16644. };
  16645. /**
  16646. * @author mikael emtinger / http://gomo.se/
  16647. */
  16648. THREE.AnimationHandler = (function() {
  16649. var playing = [];
  16650. var library = {};
  16651. var that = {};
  16652. //--- update ---
  16653. that.update = function( deltaTimeMS ) {
  16654. for( var i = 0; i < playing.length; i ++ )
  16655. playing[ i ].update( deltaTimeMS );
  16656. };
  16657. //--- add ---
  16658. that.addToUpdate = function( animation ) {
  16659. if ( playing.indexOf( animation ) === -1 )
  16660. playing.push( animation );
  16661. };
  16662. //--- remove ---
  16663. that.removeFromUpdate = function( animation ) {
  16664. var index = playing.indexOf( animation );
  16665. if( index !== -1 )
  16666. playing.splice( index, 1 );
  16667. };
  16668. //--- add ---
  16669. that.add = function( data ) {
  16670. if ( library[ data.name ] !== undefined )
  16671. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  16672. library[ data.name ] = data;
  16673. initData( data );
  16674. };
  16675. //--- get ---
  16676. that.get = function( name ) {
  16677. if ( typeof name === "string" ) {
  16678. if ( library[ name ] ) {
  16679. return library[ name ];
  16680. } else {
  16681. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  16682. return null;
  16683. }
  16684. } else {
  16685. // todo: add simple tween library
  16686. }
  16687. };
  16688. //--- parse ---
  16689. that.parse = function( root ) {
  16690. // setup hierarchy
  16691. var hierarchy = [];
  16692. if ( root instanceof THREE.SkinnedMesh ) {
  16693. for( var b = 0; b < root.bones.length; b++ ) {
  16694. hierarchy.push( root.bones[ b ] );
  16695. }
  16696. } else {
  16697. parseRecurseHierarchy( root, hierarchy );
  16698. }
  16699. return hierarchy;
  16700. };
  16701. var parseRecurseHierarchy = function( root, hierarchy ) {
  16702. hierarchy.push( root );
  16703. for( var c = 0; c < root.children.length; c++ )
  16704. parseRecurseHierarchy( root.children[ c ], hierarchy );
  16705. }
  16706. //--- init data ---
  16707. var initData = function( data ) {
  16708. if( data.initialized === true )
  16709. return;
  16710. // loop through all keys
  16711. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  16712. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16713. // remove minus times
  16714. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  16715. data.hierarchy[ h ].keys[ k ].time = 0;
  16716. // create quaternions
  16717. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  16718. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  16719. var quat = data.hierarchy[ h ].keys[ k ].rot;
  16720. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  16721. }
  16722. }
  16723. // prepare morph target keys
  16724. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  16725. // get all used
  16726. var usedMorphTargets = {};
  16727. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16728. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16729. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  16730. usedMorphTargets[ morphTargetName ] = -1;
  16731. }
  16732. }
  16733. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  16734. // set all used on all frames
  16735. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16736. var influences = {};
  16737. for ( var morphTargetName in usedMorphTargets ) {
  16738. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16739. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  16740. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  16741. break;
  16742. }
  16743. }
  16744. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  16745. influences[ morphTargetName ] = 0;
  16746. }
  16747. }
  16748. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  16749. }
  16750. }
  16751. // remove all keys that are on the same time
  16752. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16753. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  16754. data.hierarchy[ h ].keys.splice( k, 1 );
  16755. k --;
  16756. }
  16757. }
  16758. // set index
  16759. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16760. data.hierarchy[ h ].keys[ k ].index = k;
  16761. }
  16762. }
  16763. // JIT
  16764. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  16765. data.JIT = {};
  16766. data.JIT.hierarchy = [];
  16767. for( var h = 0; h < data.hierarchy.length; h ++ )
  16768. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  16769. // done
  16770. data.initialized = true;
  16771. };
  16772. // interpolation types
  16773. that.LINEAR = 0;
  16774. that.CATMULLROM = 1;
  16775. that.CATMULLROM_FORWARD = 2;
  16776. return that;
  16777. }());
  16778. /**
  16779. * @author mikael emtinger / http://gomo.se/
  16780. * @author mrdoob / http://mrdoob.com/
  16781. * @author alteredq / http://alteredqualia.com/
  16782. */
  16783. THREE.Animation = function ( root, name, interpolationType ) {
  16784. this.root = root;
  16785. this.data = THREE.AnimationHandler.get( name );
  16786. this.hierarchy = THREE.AnimationHandler.parse( root );
  16787. this.currentTime = 0;
  16788. this.timeScale = 1;
  16789. this.isPlaying = false;
  16790. this.isPaused = true;
  16791. this.loop = true;
  16792. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  16793. this.points = [];
  16794. this.target = new THREE.Vector3();
  16795. };
  16796. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  16797. if ( this.isPlaying === false ) {
  16798. this.isPlaying = true;
  16799. this.loop = loop !== undefined ? loop : true;
  16800. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  16801. // reset key cache
  16802. var h, hl = this.hierarchy.length,
  16803. object;
  16804. for ( h = 0; h < hl; h ++ ) {
  16805. object = this.hierarchy[ h ];
  16806. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16807. object.useQuaternion = true;
  16808. }
  16809. object.matrixAutoUpdate = true;
  16810. if ( object.animationCache === undefined ) {
  16811. object.animationCache = {};
  16812. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  16813. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  16814. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  16815. }
  16816. var prevKey = object.animationCache.prevKey;
  16817. var nextKey = object.animationCache.nextKey;
  16818. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  16819. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  16820. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  16821. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  16822. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  16823. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  16824. }
  16825. this.update( 0 );
  16826. }
  16827. this.isPaused = false;
  16828. THREE.AnimationHandler.addToUpdate( this );
  16829. };
  16830. THREE.Animation.prototype.pause = function() {
  16831. if ( this.isPaused === true ) {
  16832. THREE.AnimationHandler.addToUpdate( this );
  16833. } else {
  16834. THREE.AnimationHandler.removeFromUpdate( this );
  16835. }
  16836. this.isPaused = !this.isPaused;
  16837. };
  16838. THREE.Animation.prototype.stop = function() {
  16839. this.isPlaying = false;
  16840. this.isPaused = false;
  16841. THREE.AnimationHandler.removeFromUpdate( this );
  16842. };
  16843. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  16844. // early out
  16845. if ( this.isPlaying === false ) return;
  16846. // vars
  16847. var types = [ "pos", "rot", "scl" ];
  16848. var type;
  16849. var scale;
  16850. var vector;
  16851. var prevXYZ, nextXYZ;
  16852. var prevKey, nextKey;
  16853. var object;
  16854. var animationCache;
  16855. var frame;
  16856. var JIThierarchy = this.data.JIT.hierarchy;
  16857. var currentTime, unloopedCurrentTime;
  16858. var currentPoint, forwardPoint, angle;
  16859. this.currentTime += deltaTimeMS * this.timeScale;
  16860. unloopedCurrentTime = this.currentTime;
  16861. currentTime = this.currentTime = this.currentTime % this.data.length;
  16862. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  16863. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  16864. object = this.hierarchy[ h ];
  16865. animationCache = object.animationCache;
  16866. // loop through pos/rot/scl
  16867. for ( var t = 0; t < 3; t ++ ) {
  16868. // get keys
  16869. type = types[ t ];
  16870. prevKey = animationCache.prevKey[ type ];
  16871. nextKey = animationCache.nextKey[ type ];
  16872. // switch keys?
  16873. if ( nextKey.time <= unloopedCurrentTime ) {
  16874. // did we loop?
  16875. if ( currentTime < unloopedCurrentTime ) {
  16876. if ( this.loop ) {
  16877. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  16878. nextKey = this.getNextKeyWith( type, h, 1 );
  16879. while( nextKey.time < currentTime ) {
  16880. prevKey = nextKey;
  16881. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  16882. }
  16883. } else {
  16884. this.stop();
  16885. return;
  16886. }
  16887. } else {
  16888. do {
  16889. prevKey = nextKey;
  16890. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  16891. } while( nextKey.time < currentTime )
  16892. }
  16893. animationCache.prevKey[ type ] = prevKey;
  16894. animationCache.nextKey[ type ] = nextKey;
  16895. }
  16896. object.matrixAutoUpdate = true;
  16897. object.matrixWorldNeedsUpdate = true;
  16898. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  16899. prevXYZ = prevKey[ type ];
  16900. nextXYZ = nextKey[ type ];
  16901. // check scale error
  16902. if ( scale < 0 || scale > 1 ) {
  16903. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  16904. scale = scale < 0 ? 0 : 1;
  16905. }
  16906. // interpolate
  16907. if ( type === "pos" ) {
  16908. vector = object.position;
  16909. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  16910. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  16911. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  16912. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  16913. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  16914. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16915. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  16916. this.points[ 1 ] = prevXYZ;
  16917. this.points[ 2 ] = nextXYZ;
  16918. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  16919. scale = scale * 0.33 + 0.33;
  16920. currentPoint = this.interpolateCatmullRom( this.points, scale );
  16921. vector.x = currentPoint[ 0 ];
  16922. vector.y = currentPoint[ 1 ];
  16923. vector.z = currentPoint[ 2 ];
  16924. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16925. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  16926. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  16927. this.target.subSelf( vector );
  16928. this.target.y = 0;
  16929. this.target.normalize();
  16930. angle = Math.atan2( this.target.x, this.target.z );
  16931. object.rotation.set( 0, angle, 0 );
  16932. }
  16933. }
  16934. } else if ( type === "rot" ) {
  16935. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  16936. } else if ( type === "scl" ) {
  16937. vector = object.scale;
  16938. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  16939. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  16940. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  16941. }
  16942. }
  16943. }
  16944. };
  16945. // Catmull-Rom spline
  16946. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  16947. var c = [], v3 = [],
  16948. point, intPoint, weight, w2, w3,
  16949. pa, pb, pc, pd;
  16950. point = ( points.length - 1 ) * scale;
  16951. intPoint = Math.floor( point );
  16952. weight = point - intPoint;
  16953. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  16954. c[ 1 ] = intPoint;
  16955. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  16956. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  16957. pa = points[ c[ 0 ] ];
  16958. pb = points[ c[ 1 ] ];
  16959. pc = points[ c[ 2 ] ];
  16960. pd = points[ c[ 3 ] ];
  16961. w2 = weight * weight;
  16962. w3 = weight * w2;
  16963. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  16964. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  16965. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  16966. return v3;
  16967. };
  16968. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  16969. var v0 = ( p2 - p0 ) * 0.5,
  16970. v1 = ( p3 - p1 ) * 0.5;
  16971. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16972. };
  16973. // Get next key with
  16974. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  16975. var keys = this.data.hierarchy[ h ].keys;
  16976. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  16977. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16978. key = key < keys.length - 1 ? key : keys.length - 1;
  16979. } else {
  16980. key = key % keys.length;
  16981. }
  16982. for ( ; key < keys.length; key++ ) {
  16983. if ( keys[ key ][ type ] !== undefined ) {
  16984. return keys[ key ];
  16985. }
  16986. }
  16987. return this.data.hierarchy[ h ].keys[ 0 ];
  16988. };
  16989. // Get previous key with
  16990. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  16991. var keys = this.data.hierarchy[ h ].keys;
  16992. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  16993. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16994. key = key > 0 ? key : 0;
  16995. } else {
  16996. key = key >= 0 ? key : key + keys.length;
  16997. }
  16998. for ( ; key >= 0; key -- ) {
  16999. if ( keys[ key ][ type ] !== undefined ) {
  17000. return keys[ key ];
  17001. }
  17002. }
  17003. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17004. };
  17005. /**
  17006. * @author mikael emtinger / http://gomo.se/
  17007. * @author mrdoob / http://mrdoob.com/
  17008. * @author alteredq / http://alteredqualia.com/
  17009. * @author khang duong
  17010. * @author erik kitson
  17011. */
  17012. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17013. this.root = root;
  17014. this.data = THREE.AnimationHandler.get( data );
  17015. this.hierarchy = THREE.AnimationHandler.parse( root );
  17016. this.currentTime = 0;
  17017. this.timeScale = 0.001;
  17018. this.isPlaying = false;
  17019. this.isPaused = true;
  17020. this.loop = true;
  17021. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17022. // initialize to first keyframes
  17023. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17024. var keys = this.data.hierarchy[h].keys,
  17025. sids = this.data.hierarchy[h].sids,
  17026. obj = this.hierarchy[h];
  17027. if ( keys.length && sids ) {
  17028. for ( var s = 0; s < sids.length; s++ ) {
  17029. var sid = sids[ s ],
  17030. next = this.getNextKeyWith( sid, h, 0 );
  17031. if ( next ) {
  17032. next.apply( sid );
  17033. }
  17034. }
  17035. obj.matrixAutoUpdate = false;
  17036. this.data.hierarchy[h].node.updateMatrix();
  17037. obj.matrixWorldNeedsUpdate = true;
  17038. }
  17039. }
  17040. };
  17041. // Play
  17042. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  17043. if( !this.isPlaying ) {
  17044. this.isPlaying = true;
  17045. this.loop = loop !== undefined ? loop : true;
  17046. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17047. this.startTimeMs = startTimeMS;
  17048. this.startTime = 10000000;
  17049. this.endTime = -this.startTime;
  17050. // reset key cache
  17051. var h, hl = this.hierarchy.length,
  17052. object,
  17053. node;
  17054. for ( h = 0; h < hl; h++ ) {
  17055. object = this.hierarchy[ h ];
  17056. node = this.data.hierarchy[ h ];
  17057. object.useQuaternion = true;
  17058. if ( node.animationCache === undefined ) {
  17059. node.animationCache = {};
  17060. node.animationCache.prevKey = null;
  17061. node.animationCache.nextKey = null;
  17062. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17063. }
  17064. var keys = this.data.hierarchy[h].keys;
  17065. if (keys.length) {
  17066. node.animationCache.prevKey = keys[ 0 ];
  17067. node.animationCache.nextKey = keys[ 1 ];
  17068. this.startTime = Math.min( keys[0].time, this.startTime );
  17069. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17070. }
  17071. }
  17072. this.update( 0 );
  17073. }
  17074. this.isPaused = false;
  17075. THREE.AnimationHandler.addToUpdate( this );
  17076. };
  17077. // Pause
  17078. THREE.KeyFrameAnimation.prototype.pause = function() {
  17079. if( this.isPaused ) {
  17080. THREE.AnimationHandler.addToUpdate( this );
  17081. } else {
  17082. THREE.AnimationHandler.removeFromUpdate( this );
  17083. }
  17084. this.isPaused = !this.isPaused;
  17085. };
  17086. // Stop
  17087. THREE.KeyFrameAnimation.prototype.stop = function() {
  17088. this.isPlaying = false;
  17089. this.isPaused = false;
  17090. THREE.AnimationHandler.removeFromUpdate( this );
  17091. // reset JIT matrix and remove cache
  17092. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  17093. var obj = this.hierarchy[ h ];
  17094. var node = this.data.hierarchy[ h ];
  17095. if ( node.animationCache !== undefined ) {
  17096. var original = node.animationCache.originalMatrix;
  17097. if( obj instanceof THREE.Bone ) {
  17098. original.copy( obj.skinMatrix );
  17099. obj.skinMatrix = original;
  17100. } else {
  17101. original.copy( obj.matrix );
  17102. obj.matrix = original;
  17103. }
  17104. delete node.animationCache;
  17105. }
  17106. }
  17107. };
  17108. // Update
  17109. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  17110. // early out
  17111. if( !this.isPlaying ) return;
  17112. // vars
  17113. var prevKey, nextKey;
  17114. var object;
  17115. var node;
  17116. var frame;
  17117. var JIThierarchy = this.data.JIT.hierarchy;
  17118. var currentTime, unloopedCurrentTime;
  17119. var looped;
  17120. // update
  17121. this.currentTime += deltaTimeMS * this.timeScale;
  17122. unloopedCurrentTime = this.currentTime;
  17123. currentTime = this.currentTime = this.currentTime % this.data.length;
  17124. // if looped around, the current time should be based on the startTime
  17125. if ( currentTime < this.startTimeMs ) {
  17126. currentTime = this.currentTime = this.startTimeMs + currentTime;
  17127. }
  17128. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17129. looped = currentTime < unloopedCurrentTime;
  17130. if ( looped && !this.loop ) {
  17131. // Set the animation to the last keyframes and stop
  17132. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17133. var keys = this.data.hierarchy[h].keys,
  17134. sids = this.data.hierarchy[h].sids,
  17135. end = keys.length-1,
  17136. obj = this.hierarchy[h];
  17137. if ( keys.length ) {
  17138. for ( var s = 0; s < sids.length; s++ ) {
  17139. var sid = sids[ s ],
  17140. prev = this.getPrevKeyWith( sid, h, end );
  17141. if ( prev ) {
  17142. prev.apply( sid );
  17143. }
  17144. }
  17145. this.data.hierarchy[h].node.updateMatrix();
  17146. obj.matrixWorldNeedsUpdate = true;
  17147. }
  17148. }
  17149. this.stop();
  17150. return;
  17151. }
  17152. // check pre-infinity
  17153. if ( currentTime < this.startTime ) {
  17154. return;
  17155. }
  17156. // update
  17157. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17158. object = this.hierarchy[ h ];
  17159. node = this.data.hierarchy[ h ];
  17160. var keys = node.keys,
  17161. animationCache = node.animationCache;
  17162. // use JIT?
  17163. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  17164. if( object instanceof THREE.Bone ) {
  17165. object.skinMatrix = JIThierarchy[ h ][ frame ];
  17166. object.matrixWorldNeedsUpdate = false;
  17167. } else {
  17168. object.matrix = JIThierarchy[ h ][ frame ];
  17169. object.matrixWorldNeedsUpdate = true;
  17170. }
  17171. // use interpolation
  17172. } else if ( keys.length ) {
  17173. // make sure so original matrix and not JIT matrix is set
  17174. if ( this.JITCompile && animationCache ) {
  17175. if( object instanceof THREE.Bone ) {
  17176. object.skinMatrix = animationCache.originalMatrix;
  17177. } else {
  17178. object.matrix = animationCache.originalMatrix;
  17179. }
  17180. }
  17181. prevKey = animationCache.prevKey;
  17182. nextKey = animationCache.nextKey;
  17183. if ( prevKey && nextKey ) {
  17184. // switch keys?
  17185. if ( nextKey.time <= unloopedCurrentTime ) {
  17186. // did we loop?
  17187. if ( looped && this.loop ) {
  17188. prevKey = keys[ 0 ];
  17189. nextKey = keys[ 1 ];
  17190. while ( nextKey.time < currentTime ) {
  17191. prevKey = nextKey;
  17192. nextKey = keys[ prevKey.index + 1 ];
  17193. }
  17194. } else if ( !looped ) {
  17195. var lastIndex = keys.length - 1;
  17196. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  17197. prevKey = nextKey;
  17198. nextKey = keys[ prevKey.index + 1 ];
  17199. }
  17200. }
  17201. animationCache.prevKey = prevKey;
  17202. animationCache.nextKey = nextKey;
  17203. }
  17204. if(nextKey.time >= currentTime)
  17205. prevKey.interpolate( nextKey, currentTime );
  17206. else
  17207. prevKey.interpolate( nextKey, nextKey.time);
  17208. }
  17209. this.data.hierarchy[h].node.updateMatrix();
  17210. object.matrixWorldNeedsUpdate = true;
  17211. }
  17212. }
  17213. // update JIT?
  17214. if ( this.JITCompile ) {
  17215. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  17216. this.hierarchy[ 0 ].updateMatrixWorld( true );
  17217. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  17218. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  17219. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  17220. } else {
  17221. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  17222. }
  17223. }
  17224. }
  17225. }
  17226. };
  17227. // Get next key with
  17228. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  17229. var keys = this.data.hierarchy[ h ].keys;
  17230. key = key % keys.length;
  17231. for ( ; key < keys.length; key++ ) {
  17232. if ( keys[ key ].hasTarget( sid ) ) {
  17233. return keys[ key ];
  17234. }
  17235. }
  17236. return keys[ 0 ];
  17237. };
  17238. // Get previous key with
  17239. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  17240. var keys = this.data.hierarchy[ h ].keys;
  17241. key = key >= 0 ? key : key + keys.length;
  17242. for ( ; key >= 0; key-- ) {
  17243. if ( keys[ key ].hasTarget( sid ) ) {
  17244. return keys[ key ];
  17245. }
  17246. }
  17247. return keys[ keys.length - 1 ];
  17248. };
  17249. /**
  17250. * Camera for rendering cube maps
  17251. * - renders scene into axis-aligned cube
  17252. *
  17253. * @author alteredq / http://alteredqualia.com/
  17254. */
  17255. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  17256. THREE.Object3D.call( this );
  17257. var fov = 90, aspect = 1;
  17258. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17259. cameraPX.up.set( 0, -1, 0 );
  17260. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  17261. this.add( cameraPX );
  17262. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17263. cameraNX.up.set( 0, -1, 0 );
  17264. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  17265. this.add( cameraNX );
  17266. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17267. cameraPY.up.set( 0, 0, 1 );
  17268. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  17269. this.add( cameraPY );
  17270. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17271. cameraNY.up.set( 0, 0, -1 );
  17272. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  17273. this.add( cameraNY );
  17274. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17275. cameraPZ.up.set( 0, -1, 0 );
  17276. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  17277. this.add( cameraPZ );
  17278. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17279. cameraNZ.up.set( 0, -1, 0 );
  17280. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  17281. this.add( cameraNZ );
  17282. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  17283. this.updateCubeMap = function ( renderer, scene ) {
  17284. var renderTarget = this.renderTarget;
  17285. var generateMipmaps = renderTarget.generateMipmaps;
  17286. renderTarget.generateMipmaps = false;
  17287. renderTarget.activeCubeFace = 0;
  17288. renderer.render( scene, cameraPX, renderTarget );
  17289. renderTarget.activeCubeFace = 1;
  17290. renderer.render( scene, cameraNX, renderTarget );
  17291. renderTarget.activeCubeFace = 2;
  17292. renderer.render( scene, cameraPY, renderTarget );
  17293. renderTarget.activeCubeFace = 3;
  17294. renderer.render( scene, cameraNY, renderTarget );
  17295. renderTarget.activeCubeFace = 4;
  17296. renderer.render( scene, cameraPZ, renderTarget );
  17297. renderTarget.generateMipmaps = generateMipmaps;
  17298. renderTarget.activeCubeFace = 5;
  17299. renderer.render( scene, cameraNZ, renderTarget );
  17300. };
  17301. };
  17302. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  17303. /*
  17304. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  17305. *
  17306. * A general perpose camera, for setting FOV, Lens Focal Length,
  17307. * and switching between perspective and orthographic views easily.
  17308. * Use this only if you do not wish to manage
  17309. * both a Orthographic and Perspective Camera
  17310. *
  17311. */
  17312. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  17313. THREE.Camera.call( this );
  17314. this.fov = fov;
  17315. this.left = -width / 2;
  17316. this.right = width / 2
  17317. this.top = height / 2;
  17318. this.bottom = -height / 2;
  17319. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  17320. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  17321. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  17322. this.zoom = 1;
  17323. this.toPerspective();
  17324. var aspect = width/height;
  17325. };
  17326. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  17327. THREE.CombinedCamera.prototype.toPerspective = function () {
  17328. // Switches to the Perspective Camera
  17329. this.near = this.cameraP.near;
  17330. this.far = this.cameraP.far;
  17331. this.cameraP.fov = this.fov / this.zoom ;
  17332. this.cameraP.updateProjectionMatrix();
  17333. this.projectionMatrix = this.cameraP.projectionMatrix;
  17334. this.inPerspectiveMode = true;
  17335. this.inOrthographicMode = false;
  17336. };
  17337. THREE.CombinedCamera.prototype.toOrthographic = function () {
  17338. // Switches to the Orthographic camera estimating viewport from Perspective
  17339. var fov = this.fov;
  17340. var aspect = this.cameraP.aspect;
  17341. var near = this.cameraP.near;
  17342. var far = this.cameraP.far;
  17343. // The size that we set is the mid plane of the viewing frustum
  17344. var hyperfocus = ( near + far ) / 2;
  17345. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  17346. var planeHeight = 2 * halfHeight;
  17347. var planeWidth = planeHeight * aspect;
  17348. var halfWidth = planeWidth / 2;
  17349. halfHeight /= this.zoom;
  17350. halfWidth /= this.zoom;
  17351. this.cameraO.left = -halfWidth;
  17352. this.cameraO.right = halfWidth;
  17353. this.cameraO.top = halfHeight;
  17354. this.cameraO.bottom = -halfHeight;
  17355. // this.cameraO.left = -farHalfWidth;
  17356. // this.cameraO.right = farHalfWidth;
  17357. // this.cameraO.top = farHalfHeight;
  17358. // this.cameraO.bottom = -farHalfHeight;
  17359. // this.cameraO.left = this.left / this.zoom;
  17360. // this.cameraO.right = this.right / this.zoom;
  17361. // this.cameraO.top = this.top / this.zoom;
  17362. // this.cameraO.bottom = this.bottom / this.zoom;
  17363. this.cameraO.updateProjectionMatrix();
  17364. this.near = this.cameraO.near;
  17365. this.far = this.cameraO.far;
  17366. this.projectionMatrix = this.cameraO.projectionMatrix;
  17367. this.inPerspectiveMode = false;
  17368. this.inOrthographicMode = true;
  17369. };
  17370. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  17371. this.cameraP.aspect = width / height;
  17372. this.left = -width / 2;
  17373. this.right = width / 2
  17374. this.top = height / 2;
  17375. this.bottom = -height / 2;
  17376. };
  17377. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  17378. this.fov = fov;
  17379. if ( this.inPerspectiveMode ) {
  17380. this.toPerspective();
  17381. } else {
  17382. this.toOrthographic();
  17383. }
  17384. };
  17385. // For mantaining similar API with PerspectiveCamera
  17386. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  17387. if ( this.inPerspectiveMode ) {
  17388. this.toPerspective();
  17389. } else {
  17390. this.toPerspective();
  17391. this.toOrthographic();
  17392. }
  17393. };
  17394. /*
  17395. * Uses Focal Length (in mm) to estimate and set FOV
  17396. * 35mm (fullframe) camera is used if frame size is not specified;
  17397. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  17398. */
  17399. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  17400. if ( frameHeight === undefined ) frameHeight = 24;
  17401. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  17402. this.setFov( fov );
  17403. return fov;
  17404. };
  17405. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  17406. this.zoom = zoom;
  17407. if ( this.inPerspectiveMode ) {
  17408. this.toPerspective();
  17409. } else {
  17410. this.toOrthographic();
  17411. }
  17412. };
  17413. THREE.CombinedCamera.prototype.toFrontView = function() {
  17414. this.rotation.x = 0;
  17415. this.rotation.y = 0;
  17416. this.rotation.z = 0;
  17417. // should we be modifing the matrix instead?
  17418. this.rotationAutoUpdate = false;
  17419. };
  17420. THREE.CombinedCamera.prototype.toBackView = function() {
  17421. this.rotation.x = 0;
  17422. this.rotation.y = Math.PI;
  17423. this.rotation.z = 0;
  17424. this.rotationAutoUpdate = false;
  17425. };
  17426. THREE.CombinedCamera.prototype.toLeftView = function() {
  17427. this.rotation.x = 0;
  17428. this.rotation.y = - Math.PI / 2;
  17429. this.rotation.z = 0;
  17430. this.rotationAutoUpdate = false;
  17431. };
  17432. THREE.CombinedCamera.prototype.toRightView = function() {
  17433. this.rotation.x = 0;
  17434. this.rotation.y = Math.PI / 2;
  17435. this.rotation.z = 0;
  17436. this.rotationAutoUpdate = false;
  17437. };
  17438. THREE.CombinedCamera.prototype.toTopView = function() {
  17439. this.rotation.x = - Math.PI / 2;
  17440. this.rotation.y = 0;
  17441. this.rotation.z = 0;
  17442. this.rotationAutoUpdate = false;
  17443. };
  17444. THREE.CombinedCamera.prototype.toBottomView = function() {
  17445. this.rotation.x = Math.PI / 2;
  17446. this.rotation.y = 0;
  17447. this.rotation.z = 0;
  17448. this.rotationAutoUpdate = false;
  17449. };
  17450. /**
  17451. * @author mrdoob / http://mrdoob.com/
  17452. * @author alteredq / http://alteredqualia.com/
  17453. * @author paulirish / http://paulirish.com/
  17454. */
  17455. THREE.FirstPersonControls = function ( object, domElement ) {
  17456. this.object = object;
  17457. this.target = new THREE.Vector3( 0, 0, 0 );
  17458. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17459. this.movementSpeed = 1.0;
  17460. this.lookSpeed = 0.005;
  17461. this.lookVertical = true;
  17462. this.autoForward = false;
  17463. // this.invertVertical = false;
  17464. this.activeLook = true;
  17465. this.heightSpeed = false;
  17466. this.heightCoef = 1.0;
  17467. this.heightMin = 0.0;
  17468. this.heightMax = 1.0;
  17469. this.constrainVertical = false;
  17470. this.verticalMin = 0;
  17471. this.verticalMax = Math.PI;
  17472. this.autoSpeedFactor = 0.0;
  17473. this.mouseX = 0;
  17474. this.mouseY = 0;
  17475. this.lat = 0;
  17476. this.lon = 0;
  17477. this.phi = 0;
  17478. this.theta = 0;
  17479. this.moveForward = false;
  17480. this.moveBackward = false;
  17481. this.moveLeft = false;
  17482. this.moveRight = false;
  17483. this.freeze = false;
  17484. this.mouseDragOn = false;
  17485. this.viewHalfX = 0;
  17486. this.viewHalfY = 0;
  17487. if ( this.domElement !== document ) {
  17488. this.domElement.setAttribute( 'tabindex', -1 );
  17489. }
  17490. //
  17491. this.handleResize = function () {
  17492. if ( this.domElement === document ) {
  17493. this.viewHalfX = window.innerWidth / 2;
  17494. this.viewHalfY = window.innerHeight / 2;
  17495. } else {
  17496. this.viewHalfX = this.domElement.offsetWidth / 2;
  17497. this.viewHalfY = this.domElement.offsetHeight / 2;
  17498. }
  17499. };
  17500. this.onMouseDown = function ( event ) {
  17501. if ( this.domElement !== document ) {
  17502. this.domElement.focus();
  17503. }
  17504. event.preventDefault();
  17505. event.stopPropagation();
  17506. if ( this.activeLook ) {
  17507. switch ( event.button ) {
  17508. case 0: this.moveForward = true; break;
  17509. case 2: this.moveBackward = true; break;
  17510. }
  17511. }
  17512. this.mouseDragOn = true;
  17513. };
  17514. this.onMouseUp = function ( event ) {
  17515. event.preventDefault();
  17516. event.stopPropagation();
  17517. if ( this.activeLook ) {
  17518. switch ( event.button ) {
  17519. case 0: this.moveForward = false; break;
  17520. case 2: this.moveBackward = false; break;
  17521. }
  17522. }
  17523. this.mouseDragOn = false;
  17524. };
  17525. this.onMouseMove = function ( event ) {
  17526. if ( this.domElement === document ) {
  17527. this.mouseX = event.pageX - this.viewHalfX;
  17528. this.mouseY = event.pageY - this.viewHalfY;
  17529. } else {
  17530. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  17531. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  17532. }
  17533. };
  17534. this.onKeyDown = function ( event ) {
  17535. //event.preventDefault();
  17536. switch ( event.keyCode ) {
  17537. case 38: /*up*/
  17538. case 87: /*W*/ this.moveForward = true; break;
  17539. case 37: /*left*/
  17540. case 65: /*A*/ this.moveLeft = true; break;
  17541. case 40: /*down*/
  17542. case 83: /*S*/ this.moveBackward = true; break;
  17543. case 39: /*right*/
  17544. case 68: /*D*/ this.moveRight = true; break;
  17545. case 82: /*R*/ this.moveUp = true; break;
  17546. case 70: /*F*/ this.moveDown = true; break;
  17547. case 81: /*Q*/ this.freeze = !this.freeze; break;
  17548. }
  17549. };
  17550. this.onKeyUp = function ( event ) {
  17551. switch( event.keyCode ) {
  17552. case 38: /*up*/
  17553. case 87: /*W*/ this.moveForward = false; break;
  17554. case 37: /*left*/
  17555. case 65: /*A*/ this.moveLeft = false; break;
  17556. case 40: /*down*/
  17557. case 83: /*S*/ this.moveBackward = false; break;
  17558. case 39: /*right*/
  17559. case 68: /*D*/ this.moveRight = false; break;
  17560. case 82: /*R*/ this.moveUp = false; break;
  17561. case 70: /*F*/ this.moveDown = false; break;
  17562. }
  17563. };
  17564. this.update = function( delta ) {
  17565. var actualMoveSpeed = 0;
  17566. if ( this.freeze ) {
  17567. return;
  17568. } else {
  17569. if ( this.heightSpeed ) {
  17570. var y = THREE.Math.clamp( this.object.position.y, this.heightMin, this.heightMax );
  17571. var heightDelta = y - this.heightMin;
  17572. this.autoSpeedFactor = delta * ( heightDelta * this.heightCoef );
  17573. } else {
  17574. this.autoSpeedFactor = 0.0;
  17575. }
  17576. actualMoveSpeed = delta * this.movementSpeed;
  17577. if ( this.moveForward || ( this.autoForward && !this.moveBackward ) ) this.object.translateZ( - ( actualMoveSpeed + this.autoSpeedFactor ) );
  17578. if ( this.moveBackward ) this.object.translateZ( actualMoveSpeed );
  17579. if ( this.moveLeft ) this.object.translateX( - actualMoveSpeed );
  17580. if ( this.moveRight ) this.object.translateX( actualMoveSpeed );
  17581. if ( this.moveUp ) this.object.translateY( actualMoveSpeed );
  17582. if ( this.moveDown ) this.object.translateY( - actualMoveSpeed );
  17583. var actualLookSpeed = delta * this.lookSpeed;
  17584. if ( !this.activeLook ) {
  17585. actualLookSpeed = 0;
  17586. }
  17587. this.lon += this.mouseX * actualLookSpeed;
  17588. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed; // * this.invertVertical?-1:1;
  17589. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  17590. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  17591. this.theta = this.lon * Math.PI / 180;
  17592. var targetPosition = this.target,
  17593. position = this.object.position;
  17594. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  17595. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  17596. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  17597. }
  17598. var verticalLookRatio = 1;
  17599. if ( this.constrainVertical ) {
  17600. verticalLookRatio = Math.PI / ( this.verticalMax - this.verticalMin );
  17601. }
  17602. this.lon += this.mouseX * actualLookSpeed;
  17603. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed * verticalLookRatio;
  17604. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  17605. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  17606. this.theta = this.lon * Math.PI / 180;
  17607. if ( this.constrainVertical ) {
  17608. this.phi = THREE.Math.mapLinear( this.phi, 0, Math.PI, this.verticalMin, this.verticalMax );
  17609. }
  17610. var targetPosition = this.target,
  17611. position = this.object.position;
  17612. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  17613. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  17614. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  17615. this.object.lookAt( targetPosition );
  17616. };
  17617. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  17618. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  17619. this.domElement.addEventListener( 'mousedown', bind( this, this.onMouseDown ), false );
  17620. this.domElement.addEventListener( 'mouseup', bind( this, this.onMouseUp ), false );
  17621. this.domElement.addEventListener( 'keydown', bind( this, this.onKeyDown ), false );
  17622. this.domElement.addEventListener( 'keyup', bind( this, this.onKeyUp ), false );
  17623. function bind( scope, fn ) {
  17624. return function () {
  17625. fn.apply( scope, arguments );
  17626. };
  17627. };
  17628. this.handleResize();
  17629. };
  17630. /**
  17631. * @author alteredq / http://alteredqualia.com/
  17632. */
  17633. THREE.PathControls = function ( object, domElement ) {
  17634. this.object = object;
  17635. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17636. this.id = "PathControls" + THREE.PathControlsIdCounter ++;
  17637. // API
  17638. this.duration = 10 * 1000; // milliseconds
  17639. this.waypoints = [];
  17640. this.useConstantSpeed = true;
  17641. this.resamplingCoef = 50;
  17642. this.debugPath = new THREE.Object3D();
  17643. this.debugDummy = new THREE.Object3D();
  17644. this.animationParent = new THREE.Object3D();
  17645. this.lookSpeed = 0.005;
  17646. this.lookVertical = true;
  17647. this.lookHorizontal = true;
  17648. this.verticalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  17649. this.horizontalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  17650. // internals
  17651. this.target = new THREE.Object3D();
  17652. this.mouseX = 0;
  17653. this.mouseY = 0;
  17654. this.lat = 0;
  17655. this.lon = 0;
  17656. this.phi = 0;
  17657. this.theta = 0;
  17658. var PI2 = Math.PI * 2,
  17659. PI180 = Math.PI / 180;
  17660. this.viewHalfX = 0;
  17661. this.viewHalfY = 0;
  17662. if ( this.domElement !== document ) {
  17663. this.domElement.setAttribute( 'tabindex', -1 );
  17664. }
  17665. // methods
  17666. this.handleResize = function () {
  17667. if ( this.domElement === document ) {
  17668. this.viewHalfX = window.innerWidth / 2;
  17669. this.viewHalfY = window.innerHeight / 2;
  17670. } else {
  17671. this.viewHalfX = this.domElement.offsetWidth / 2;
  17672. this.viewHalfY = this.domElement.offsetHeight / 2;
  17673. }
  17674. };
  17675. this.update = function ( delta ) {
  17676. var srcRange, dstRange;
  17677. if( this.lookHorizontal ) this.lon += this.mouseX * this.lookSpeed * delta;
  17678. if( this.lookVertical ) this.lat -= this.mouseY * this.lookSpeed * delta;
  17679. this.lon = Math.max( 0, Math.min( 360, this.lon ) );
  17680. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  17681. this.phi = ( 90 - this.lat ) * PI180;
  17682. this.theta = this.lon * PI180;
  17683. this.phi = normalize_angle_rad( this.phi );
  17684. // constrain vertical look angle
  17685. srcRange = this.verticalAngleMap.srcRange;
  17686. dstRange = this.verticalAngleMap.dstRange;
  17687. var tmpPhi = THREE.Math.mapLinear( this.phi, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  17688. var tmpPhiFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  17689. var tmpPhiNormalized = ( tmpPhi - dstRange[ 0 ] ) / tmpPhiFullRange;
  17690. this.phi = QuadraticEaseInOut( tmpPhiNormalized ) * tmpPhiFullRange + dstRange[ 0 ];
  17691. // constrain horizontal look angle
  17692. srcRange = this.horizontalAngleMap.srcRange;
  17693. dstRange = this.horizontalAngleMap.dstRange;
  17694. var tmpTheta = THREE.Math.mapLinear( this.theta, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  17695. var tmpThetaFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  17696. var tmpThetaNormalized = ( tmpTheta - dstRange[ 0 ] ) / tmpThetaFullRange;
  17697. this.theta = QuadraticEaseInOut( tmpThetaNormalized ) * tmpThetaFullRange + dstRange[ 0 ];
  17698. var targetPosition = this.target.position,
  17699. position = this.object.position;
  17700. targetPosition.x = 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  17701. targetPosition.y = 100 * Math.cos( this.phi );
  17702. targetPosition.z = 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  17703. this.object.lookAt( this.target.position );
  17704. };
  17705. this.onMouseMove = function ( event ) {
  17706. if ( this.domElement === document ) {
  17707. this.mouseX = event.pageX - this.viewHalfX;
  17708. this.mouseY = event.pageY - this.viewHalfY;
  17709. } else {
  17710. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  17711. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  17712. }
  17713. };
  17714. // utils
  17715. function normalize_angle_rad( a ) {
  17716. var b = a % PI2;
  17717. return b >= 0 ? b : b + PI2;
  17718. };
  17719. function distance( a, b ) {
  17720. var dx = a[ 0 ] - b[ 0 ],
  17721. dy = a[ 1 ] - b[ 1 ],
  17722. dz = a[ 2 ] - b[ 2 ];
  17723. return Math.sqrt( dx * dx + dy * dy + dz * dz );
  17724. };
  17725. function QuadraticEaseInOut ( k ) {
  17726. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  17727. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  17728. };
  17729. function bind( scope, fn ) {
  17730. return function () {
  17731. fn.apply( scope, arguments );
  17732. };
  17733. };
  17734. function initAnimationPath( parent, spline, name, duration ) {
  17735. var animationData = {
  17736. name: name,
  17737. fps: 0.6,
  17738. length: duration,
  17739. hierarchy: []
  17740. };
  17741. var i,
  17742. parentAnimation, childAnimation,
  17743. path = spline.getControlPointsArray(),
  17744. sl = spline.getLength(),
  17745. pl = path.length,
  17746. t = 0,
  17747. first = 0,
  17748. last = pl - 1;
  17749. parentAnimation = { parent: -1, keys: [] };
  17750. parentAnimation.keys[ first ] = { time: 0, pos: path[ first ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  17751. parentAnimation.keys[ last ] = { time: duration, pos: path[ last ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  17752. for ( i = 1; i < pl - 1; i++ ) {
  17753. // real distance (approximation via linear segments)
  17754. t = duration * sl.chunks[ i ] / sl.total;
  17755. // equal distance
  17756. //t = duration * ( i / pl );
  17757. // linear distance
  17758. //t += duration * distance( path[ i ], path[ i - 1 ] ) / sl.total;
  17759. parentAnimation.keys[ i ] = { time: t, pos: path[ i ] };
  17760. }
  17761. animationData.hierarchy[ 0 ] = parentAnimation;
  17762. THREE.AnimationHandler.add( animationData );
  17763. return new THREE.Animation( parent, name, THREE.AnimationHandler.CATMULLROM_FORWARD, false );
  17764. };
  17765. function createSplineGeometry( spline, n_sub ) {
  17766. var i, index, position,
  17767. geometry = new THREE.Geometry();
  17768. for ( i = 0; i < spline.points.length * n_sub; i ++ ) {
  17769. index = i / ( spline.points.length * n_sub );
  17770. position = spline.getPoint( index );
  17771. geometry.vertices[ i ] = new THREE.Vector3( position.x, position.y, position.z );
  17772. }
  17773. return geometry;
  17774. };
  17775. function createPath( parent, spline ) {
  17776. var lineGeo = createSplineGeometry( spline, 10 ),
  17777. particleGeo = createSplineGeometry( spline, 10 ),
  17778. lineMat = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 3 } ),
  17779. lineObj = new THREE.Line( lineGeo, lineMat ),
  17780. particleObj = new THREE.ParticleSystem( particleGeo, new THREE.ParticleBasicMaterial( { color: 0xffaa00, size: 3 } ) );
  17781. lineObj.scale.set( 1, 1, 1 );
  17782. parent.add( lineObj );
  17783. particleObj.scale.set( 1, 1, 1 );
  17784. parent.add( particleObj );
  17785. var waypoint,
  17786. geo = new THREE.SphereGeometry( 1, 16, 8 ),
  17787. mat = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  17788. for ( var i = 0; i < spline.points.length; i ++ ) {
  17789. waypoint = new THREE.Mesh( geo, mat );
  17790. waypoint.position.copy( spline.points[ i ] );
  17791. parent.add( waypoint );
  17792. }
  17793. };
  17794. this.init = function ( ) {
  17795. // constructor
  17796. this.spline = new THREE.Spline();
  17797. this.spline.initFromArray( this.waypoints );
  17798. if ( this.useConstantSpeed ) {
  17799. this.spline.reparametrizeByArcLength( this.resamplingCoef );
  17800. }
  17801. if ( this.createDebugDummy ) {
  17802. var dummyParentMaterial = new THREE.MeshLambertMaterial( { color: 0x0077ff } ),
  17803. dummyChildMaterial = new THREE.MeshLambertMaterial( { color: 0x00ff00 } ),
  17804. dummyParentGeo = new THREE.CubeGeometry( 10, 10, 20 ),
  17805. dummyChildGeo = new THREE.CubeGeometry( 2, 2, 10 );
  17806. this.animationParent = new THREE.Mesh( dummyParentGeo, dummyParentMaterial );
  17807. var dummyChild = new THREE.Mesh( dummyChildGeo, dummyChildMaterial );
  17808. dummyChild.position.set( 0, 10, 0 );
  17809. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  17810. this.animationParent.add( this.object );
  17811. this.animationParent.add( this.target );
  17812. this.animationParent.add( dummyChild );
  17813. } else {
  17814. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  17815. this.animationParent.add( this.target );
  17816. this.animationParent.add( this.object );
  17817. }
  17818. if ( this.createDebugPath ) {
  17819. createPath( this.debugPath, this.spline );
  17820. }
  17821. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  17822. };
  17823. this.handleResize();
  17824. };
  17825. THREE.PathControlsIdCounter = 0;
  17826. /**
  17827. * @author James Baicoianu / http://www.baicoianu.com/
  17828. */
  17829. THREE.FlyControls = function ( object, domElement ) {
  17830. this.object = object;
  17831. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17832. if ( domElement ) this.domElement.setAttribute( 'tabindex', -1 );
  17833. // API
  17834. this.movementSpeed = 1.0;
  17835. this.rollSpeed = 0.005;
  17836. this.dragToLook = false;
  17837. this.autoForward = false;
  17838. // disable default target object behavior
  17839. this.object.useQuaternion = true;
  17840. // internals
  17841. this.tmpQuaternion = new THREE.Quaternion();
  17842. this.mouseStatus = 0;
  17843. 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 };
  17844. this.moveVector = new THREE.Vector3( 0, 0, 0 );
  17845. this.rotationVector = new THREE.Vector3( 0, 0, 0 );
  17846. this.handleEvent = function ( event ) {
  17847. if ( typeof this[ event.type ] == 'function' ) {
  17848. this[ event.type ]( event );
  17849. }
  17850. };
  17851. this.keydown = function( event ) {
  17852. if ( event.altKey ) {
  17853. return;
  17854. }
  17855. //event.preventDefault();
  17856. switch ( event.keyCode ) {
  17857. case 16: /* shift */ this.movementSpeedMultiplier = .1; break;
  17858. case 87: /*W*/ this.moveState.forward = 1; break;
  17859. case 83: /*S*/ this.moveState.back = 1; break;
  17860. case 65: /*A*/ this.moveState.left = 1; break;
  17861. case 68: /*D*/ this.moveState.right = 1; break;
  17862. case 82: /*R*/ this.moveState.up = 1; break;
  17863. case 70: /*F*/ this.moveState.down = 1; break;
  17864. case 38: /*up*/ this.moveState.pitchUp = 1; break;
  17865. case 40: /*down*/ this.moveState.pitchDown = 1; break;
  17866. case 37: /*left*/ this.moveState.yawLeft = 1; break;
  17867. case 39: /*right*/ this.moveState.yawRight = 1; break;
  17868. case 81: /*Q*/ this.moveState.rollLeft = 1; break;
  17869. case 69: /*E*/ this.moveState.rollRight = 1; break;
  17870. }
  17871. this.updateMovementVector();
  17872. this.updateRotationVector();
  17873. };
  17874. this.keyup = function( event ) {
  17875. switch( event.keyCode ) {
  17876. case 16: /* shift */ this.movementSpeedMultiplier = 1; break;
  17877. case 87: /*W*/ this.moveState.forward = 0; break;
  17878. case 83: /*S*/ this.moveState.back = 0; break;
  17879. case 65: /*A*/ this.moveState.left = 0; break;
  17880. case 68: /*D*/ this.moveState.right = 0; break;
  17881. case 82: /*R*/ this.moveState.up = 0; break;
  17882. case 70: /*F*/ this.moveState.down = 0; break;
  17883. case 38: /*up*/ this.moveState.pitchUp = 0; break;
  17884. case 40: /*down*/ this.moveState.pitchDown = 0; break;
  17885. case 37: /*left*/ this.moveState.yawLeft = 0; break;
  17886. case 39: /*right*/ this.moveState.yawRight = 0; break;
  17887. case 81: /*Q*/ this.moveState.rollLeft = 0; break;
  17888. case 69: /*E*/ this.moveState.rollRight = 0; break;
  17889. }
  17890. this.updateMovementVector();
  17891. this.updateRotationVector();
  17892. };
  17893. this.mousedown = function( event ) {
  17894. if ( this.domElement !== document ) {
  17895. this.domElement.focus();
  17896. }
  17897. event.preventDefault();
  17898. event.stopPropagation();
  17899. if ( this.dragToLook ) {
  17900. this.mouseStatus ++;
  17901. } else {
  17902. switch ( event.button ) {
  17903. case 0: this.object.moveForward = true; break;
  17904. case 2: this.object.moveBackward = true; break;
  17905. }
  17906. }
  17907. };
  17908. this.mousemove = function( event ) {
  17909. if ( !this.dragToLook || this.mouseStatus > 0 ) {
  17910. var container = this.getContainerDimensions();
  17911. var halfWidth = container.size[ 0 ] / 2;
  17912. var halfHeight = container.size[ 1 ] / 2;
  17913. this.moveState.yawLeft = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth ) / halfWidth;
  17914. this.moveState.pitchDown = ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;
  17915. this.updateRotationVector();
  17916. }
  17917. };
  17918. this.mouseup = function( event ) {
  17919. event.preventDefault();
  17920. event.stopPropagation();
  17921. if ( this.dragToLook ) {
  17922. this.mouseStatus --;
  17923. this.moveState.yawLeft = this.moveState.pitchDown = 0;
  17924. } else {
  17925. switch ( event.button ) {
  17926. case 0: this.moveForward = false; break;
  17927. case 2: this.moveBackward = false; break;
  17928. }
  17929. }
  17930. this.updateRotationVector();
  17931. };
  17932. this.update = function( delta ) {
  17933. var moveMult = delta * this.movementSpeed;
  17934. var rotMult = delta * this.rollSpeed;
  17935. this.object.translateX( this.moveVector.x * moveMult );
  17936. this.object.translateY( this.moveVector.y * moveMult );
  17937. this.object.translateZ( this.moveVector.z * moveMult );
  17938. this.tmpQuaternion.set( this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1 ).normalize();
  17939. this.object.quaternion.multiplySelf( this.tmpQuaternion );
  17940. this.object.matrix.setPosition( this.object.position );
  17941. this.object.matrix.setRotationFromQuaternion( this.object.quaternion );
  17942. this.object.matrixWorldNeedsUpdate = true;
  17943. };
  17944. this.updateMovementVector = function() {
  17945. var forward = ( this.moveState.forward || ( this.autoForward && !this.moveState.back ) ) ? 1 : 0;
  17946. this.moveVector.x = ( -this.moveState.left + this.moveState.right );
  17947. this.moveVector.y = ( -this.moveState.down + this.moveState.up );
  17948. this.moveVector.z = ( -forward + this.moveState.back );
  17949. //console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );
  17950. };
  17951. this.updateRotationVector = function() {
  17952. this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
  17953. this.rotationVector.y = ( -this.moveState.yawRight + this.moveState.yawLeft );
  17954. this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );
  17955. //console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );
  17956. };
  17957. this.getContainerDimensions = function() {
  17958. if ( this.domElement != document ) {
  17959. return {
  17960. size : [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
  17961. offset : [ this.domElement.offsetLeft, this.domElement.offsetTop ]
  17962. };
  17963. } else {
  17964. return {
  17965. size : [ window.innerWidth, window.innerHeight ],
  17966. offset : [ 0, 0 ]
  17967. };
  17968. }
  17969. };
  17970. function bind( scope, fn ) {
  17971. return function () {
  17972. fn.apply( scope, arguments );
  17973. };
  17974. };
  17975. this.domElement.addEventListener( 'mousemove', bind( this, this.mousemove ), false );
  17976. this.domElement.addEventListener( 'mousedown', bind( this, this.mousedown ), false );
  17977. this.domElement.addEventListener( 'mouseup', bind( this, this.mouseup ), false );
  17978. this.domElement.addEventListener( 'keydown', bind( this, this.keydown ), false );
  17979. this.domElement.addEventListener( 'keyup', bind( this, this.keyup ), false );
  17980. this.updateMovementVector();
  17981. this.updateRotationVector();
  17982. };
  17983. /**
  17984. * @author mikael emtinger / http://gomo.se/
  17985. * @author alteredq / http://alteredqualia.com/
  17986. */
  17987. THREE.RollControls = function ( object, domElement ) {
  17988. this.object = object;
  17989. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17990. // API
  17991. this.mouseLook = true;
  17992. this.autoForward = false;
  17993. this.lookSpeed = 1;
  17994. this.movementSpeed = 1;
  17995. this.rollSpeed = 1;
  17996. this.constrainVertical = [ -0.9, 0.9 ];
  17997. // disable default target object behavior
  17998. this.object.matrixAutoUpdate = false;
  17999. // internals
  18000. this.forward = new THREE.Vector3( 0, 0, 1 );
  18001. this.roll = 0;
  18002. var xTemp = new THREE.Vector3();
  18003. var yTemp = new THREE.Vector3();
  18004. var zTemp = new THREE.Vector3();
  18005. var rollMatrix = new THREE.Matrix4();
  18006. var doRoll = false, rollDirection = 1, forwardSpeed = 0, sideSpeed = 0, upSpeed = 0;
  18007. var mouseX = 0, mouseY = 0;
  18008. var windowHalfX = 0;
  18009. var windowHalfY = 0;
  18010. //
  18011. this.handleResize = function () {
  18012. windowHalfX = window.innerWidth / 2;
  18013. windowHalfY = window.innerHeight / 2;
  18014. };
  18015. // custom update
  18016. this.update = function ( delta ) {
  18017. if ( this.mouseLook ) {
  18018. var actualLookSpeed = delta * this.lookSpeed;
  18019. this.rotateHorizontally( actualLookSpeed * mouseX );
  18020. this.rotateVertically( actualLookSpeed * mouseY );
  18021. }
  18022. var actualSpeed = delta * this.movementSpeed;
  18023. var forwardOrAuto = ( forwardSpeed > 0 || ( this.autoForward && ! ( forwardSpeed < 0 ) ) ) ? 1 : forwardSpeed;
  18024. this.object.translateZ( -actualSpeed * forwardOrAuto );
  18025. this.object.translateX( actualSpeed * sideSpeed );
  18026. this.object.translateY( actualSpeed * upSpeed );
  18027. if( doRoll ) {
  18028. this.roll += this.rollSpeed * delta * rollDirection;
  18029. }
  18030. // cap forward up / down
  18031. if( this.forward.y > this.constrainVertical[ 1 ] ) {
  18032. this.forward.y = this.constrainVertical[ 1 ];
  18033. this.forward.normalize();
  18034. } else if( this.forward.y < this.constrainVertical[ 0 ] ) {
  18035. this.forward.y = this.constrainVertical[ 0 ];
  18036. this.forward.normalize();
  18037. }
  18038. // construct unrolled camera matrix
  18039. zTemp.copy( this.forward );
  18040. yTemp.set( 0, 1, 0 );
  18041. xTemp.cross( yTemp, zTemp ).normalize();
  18042. yTemp.cross( zTemp, xTemp ).normalize();
  18043. this.object.matrix.elements[0] = xTemp.x; this.object.matrix.elements[4] = yTemp.x; this.object.matrix.elements[8] = zTemp.x;
  18044. this.object.matrix.elements[1] = xTemp.y; this.object.matrix.elements[5] = yTemp.y; this.object.matrix.elements[9] = zTemp.y;
  18045. this.object.matrix.elements[2] = xTemp.z; this.object.matrix.elements[6] = yTemp.z; this.object.matrix.elements[10] = zTemp.z;
  18046. // calculate roll matrix
  18047. rollMatrix.identity();
  18048. rollMatrix.elements[0] = Math.cos( this.roll ); rollMatrix.elements[4] = -Math.sin( this.roll );
  18049. rollMatrix.elements[1] = Math.sin( this.roll ); rollMatrix.elements[5] = Math.cos( this.roll );
  18050. // multiply camera with roll
  18051. this.object.matrix.multiplySelf( rollMatrix );
  18052. this.object.matrixWorldNeedsUpdate = true;
  18053. // set position
  18054. this.object.matrix.elements[12] = this.object.position.x;
  18055. this.object.matrix.elements[13] = this.object.position.y;
  18056. this.object.matrix.elements[14] = this.object.position.z;
  18057. };
  18058. this.translateX = function ( distance ) {
  18059. this.object.position.x += this.object.matrix.elements[0] * distance;
  18060. this.object.position.y += this.object.matrix.elements[1] * distance;
  18061. this.object.position.z += this.object.matrix.elements[2] * distance;
  18062. };
  18063. this.translateY = function ( distance ) {
  18064. this.object.position.x += this.object.matrix.elements[4] * distance;
  18065. this.object.position.y += this.object.matrix.elements[5] * distance;
  18066. this.object.position.z += this.object.matrix.elements[6] * distance;
  18067. };
  18068. this.translateZ = function ( distance ) {
  18069. this.object.position.x -= this.object.matrix.elements[8] * distance;
  18070. this.object.position.y -= this.object.matrix.elements[9] * distance;
  18071. this.object.position.z -= this.object.matrix.elements[10] * distance;
  18072. };
  18073. this.rotateHorizontally = function ( amount ) {
  18074. // please note that the amount is NOT degrees, but a scale value
  18075. xTemp.set( this.object.matrix.elements[0], this.object.matrix.elements[1], this.object.matrix.elements[2] );
  18076. xTemp.multiplyScalar( amount );
  18077. this.forward.subSelf( xTemp );
  18078. this.forward.normalize();
  18079. };
  18080. this.rotateVertically = function ( amount ) {
  18081. // please note that the amount is NOT degrees, but a scale value
  18082. yTemp.set( this.object.matrix.elements[4], this.object.matrix.elements[5], this.object.matrix.elements[6] );
  18083. yTemp.multiplyScalar( amount );
  18084. this.forward.addSelf( yTemp );
  18085. this.forward.normalize();
  18086. };
  18087. function onKeyDown( event ) {
  18088. //event.preventDefault();
  18089. switch ( event.keyCode ) {
  18090. case 38: /*up*/
  18091. case 87: /*W*/ forwardSpeed = 1; break;
  18092. case 37: /*left*/
  18093. case 65: /*A*/ sideSpeed = -1; break;
  18094. case 40: /*down*/
  18095. case 83: /*S*/ forwardSpeed = -1; break;
  18096. case 39: /*right*/
  18097. case 68: /*D*/ sideSpeed = 1; break;
  18098. case 81: /*Q*/ doRoll = true; rollDirection = 1; break;
  18099. case 69: /*E*/ doRoll = true; rollDirection = -1; break;
  18100. case 82: /*R*/ upSpeed = 1; break;
  18101. case 70: /*F*/ upSpeed = -1; break;
  18102. }
  18103. };
  18104. function onKeyUp( event ) {
  18105. switch( event.keyCode ) {
  18106. case 38: /*up*/
  18107. case 87: /*W*/ forwardSpeed = 0; break;
  18108. case 37: /*left*/
  18109. case 65: /*A*/ sideSpeed = 0; break;
  18110. case 40: /*down*/
  18111. case 83: /*S*/ forwardSpeed = 0; break;
  18112. case 39: /*right*/
  18113. case 68: /*D*/ sideSpeed = 0; break;
  18114. case 81: /*Q*/ doRoll = false; break;
  18115. case 69: /*E*/ doRoll = false; break;
  18116. case 82: /*R*/ upSpeed = 0; break;
  18117. case 70: /*F*/ upSpeed = 0; break;
  18118. }
  18119. };
  18120. function onMouseMove( event ) {
  18121. mouseX = ( event.clientX - windowHalfX ) / window.innerWidth;
  18122. mouseY = ( event.clientY - windowHalfY ) / window.innerHeight;
  18123. };
  18124. function onMouseDown ( event ) {
  18125. event.preventDefault();
  18126. event.stopPropagation();
  18127. switch ( event.button ) {
  18128. case 0: forwardSpeed = 1; break;
  18129. case 2: forwardSpeed = -1; break;
  18130. }
  18131. };
  18132. function onMouseUp ( event ) {
  18133. event.preventDefault();
  18134. event.stopPropagation();
  18135. switch ( event.button ) {
  18136. case 0: forwardSpeed = 0; break;
  18137. case 2: forwardSpeed = 0; break;
  18138. }
  18139. };
  18140. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  18141. this.domElement.addEventListener( 'mousemove', onMouseMove, false );
  18142. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  18143. this.domElement.addEventListener( 'mouseup', onMouseUp, false );
  18144. this.domElement.addEventListener( 'keydown', onKeyDown, false );
  18145. this.domElement.addEventListener( 'keyup', onKeyUp, false );
  18146. this.handleResize();
  18147. };
  18148. /**
  18149. * @author Eberhard Graether / http://egraether.com/
  18150. */
  18151. THREE.TrackballControls = function ( object, domElement ) {
  18152. THREE.EventTarget.call( this );
  18153. var _this = this,
  18154. STATE = { NONE : -1, ROTATE : 0, ZOOM : 1, PAN : 2 };
  18155. this.object = object;
  18156. this.domElement = ( domElement !== undefined ) ? domElement : document;
  18157. // API
  18158. this.enabled = true;
  18159. this.screen = { width: 0, height: 0, offsetLeft: 0, offsetTop: 0 };
  18160. this.radius = ( this.screen.width + this.screen.height ) / 4;
  18161. this.rotateSpeed = 1.0;
  18162. this.zoomSpeed = 1.2;
  18163. this.panSpeed = 0.3;
  18164. this.noRotate = false;
  18165. this.noZoom = false;
  18166. this.noPan = false;
  18167. this.staticMoving = false;
  18168. this.dynamicDampingFactor = 0.2;
  18169. this.minDistance = 0;
  18170. this.maxDistance = Infinity;
  18171. this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];
  18172. // internals
  18173. this.target = new THREE.Vector3();
  18174. var lastPosition = new THREE.Vector3();
  18175. var _keyPressed = false,
  18176. _state = STATE.NONE,
  18177. _eye = new THREE.Vector3(),
  18178. _rotateStart = new THREE.Vector3(),
  18179. _rotateEnd = new THREE.Vector3(),
  18180. _zoomStart = new THREE.Vector2(),
  18181. _zoomEnd = new THREE.Vector2(),
  18182. _panStart = new THREE.Vector2(),
  18183. _panEnd = new THREE.Vector2();
  18184. // events
  18185. var changeEvent = { type: 'change' };
  18186. // methods
  18187. this.handleResize = function () {
  18188. this.screen.width = window.innerWidth;
  18189. this.screen.height = window.innerHeight;
  18190. this.screen.offsetLeft = 0;
  18191. this.screen.offsetTop = 0;
  18192. this.radius = ( this.screen.width + this.screen.height ) / 4;
  18193. };
  18194. this.handleEvent = function ( event ) {
  18195. if ( typeof this[ event.type ] == 'function' ) {
  18196. this[ event.type ]( event );
  18197. }
  18198. };
  18199. this.getMouseOnScreen = function ( clientX, clientY ) {
  18200. return new THREE.Vector2(
  18201. ( clientX - _this.screen.offsetLeft ) / _this.radius * 0.5,
  18202. ( clientY - _this.screen.offsetTop ) / _this.radius * 0.5
  18203. );
  18204. };
  18205. this.getMouseProjectionOnBall = function ( clientX, clientY ) {
  18206. var mouseOnBall = new THREE.Vector3(
  18207. ( clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft ) / _this.radius,
  18208. ( _this.screen.height * 0.5 + _this.screen.offsetTop - clientY ) / _this.radius,
  18209. 0.0
  18210. );
  18211. var length = mouseOnBall.length();
  18212. if ( length > 1.0 ) {
  18213. mouseOnBall.normalize();
  18214. } else {
  18215. mouseOnBall.z = Math.sqrt( 1.0 - length * length );
  18216. }
  18217. _eye.copy( _this.object.position ).subSelf( _this.target );
  18218. var projection = _this.object.up.clone().setLength( mouseOnBall.y );
  18219. projection.addSelf( _this.object.up.clone().crossSelf( _eye ).setLength( mouseOnBall.x ) );
  18220. projection.addSelf( _eye.setLength( mouseOnBall.z ) );
  18221. return projection;
  18222. };
  18223. this.rotateCamera = function () {
  18224. var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );
  18225. if ( angle ) {
  18226. var axis = ( new THREE.Vector3() ).cross( _rotateStart, _rotateEnd ).normalize(),
  18227. quaternion = new THREE.Quaternion();
  18228. angle *= _this.rotateSpeed;
  18229. quaternion.setFromAxisAngle( axis, -angle );
  18230. quaternion.multiplyVector3( _eye );
  18231. quaternion.multiplyVector3( _this.object.up );
  18232. quaternion.multiplyVector3( _rotateEnd );
  18233. if ( _this.staticMoving ) {
  18234. _rotateStart.copy( _rotateEnd );
  18235. } else {
  18236. quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
  18237. quaternion.multiplyVector3( _rotateStart );
  18238. }
  18239. }
  18240. };
  18241. this.zoomCamera = function () {
  18242. var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;
  18243. if ( factor !== 1.0 && factor > 0.0 ) {
  18244. _eye.multiplyScalar( factor );
  18245. if ( _this.staticMoving ) {
  18246. _zoomStart.copy( _zoomEnd );
  18247. } else {
  18248. _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;
  18249. }
  18250. }
  18251. };
  18252. this.panCamera = function () {
  18253. var mouseChange = _panEnd.clone().subSelf( _panStart );
  18254. if ( mouseChange.lengthSq() ) {
  18255. mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );
  18256. var pan = _eye.clone().crossSelf( _this.object.up ).setLength( mouseChange.x );
  18257. pan.addSelf( _this.object.up.clone().setLength( mouseChange.y ) );
  18258. _this.object.position.addSelf( pan );
  18259. _this.target.addSelf( pan );
  18260. if ( _this.staticMoving ) {
  18261. _panStart = _panEnd;
  18262. } else {
  18263. _panStart.addSelf( mouseChange.sub( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );
  18264. }
  18265. }
  18266. };
  18267. this.checkDistances = function () {
  18268. if ( !_this.noZoom || !_this.noPan ) {
  18269. if ( _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance ) {
  18270. _this.object.position.setLength( _this.maxDistance );
  18271. }
  18272. if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {
  18273. _this.object.position.add( _this.target, _eye.setLength( _this.minDistance ) );
  18274. }
  18275. }
  18276. };
  18277. this.update = function () {
  18278. _eye.copy( _this.object.position ).subSelf( _this.target );
  18279. if ( !_this.noRotate ) {
  18280. _this.rotateCamera();
  18281. }
  18282. if ( !_this.noZoom ) {
  18283. _this.zoomCamera();
  18284. }
  18285. if ( !_this.noPan ) {
  18286. _this.panCamera();
  18287. }
  18288. _this.object.position.add( _this.target, _eye );
  18289. _this.checkDistances();
  18290. _this.object.lookAt( _this.target );
  18291. if ( lastPosition.distanceToSquared( _this.object.position ) > 0 ) {
  18292. _this.dispatchEvent( changeEvent );
  18293. lastPosition.copy( _this.object.position );
  18294. }
  18295. };
  18296. // listeners
  18297. function keydown( event ) {
  18298. if ( ! _this.enabled ) return;
  18299. //event.preventDefault();
  18300. if ( _state !== STATE.NONE ) {
  18301. return;
  18302. } else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {
  18303. _state = STATE.ROTATE;
  18304. } else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {
  18305. _state = STATE.ZOOM;
  18306. } else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {
  18307. _state = STATE.PAN;
  18308. }
  18309. if ( _state !== STATE.NONE ) {
  18310. _keyPressed = true;
  18311. }
  18312. }
  18313. function keyup( event ) {
  18314. if ( ! _this.enabled ) return;
  18315. if ( _state !== STATE.NONE ) {
  18316. _state = STATE.NONE;
  18317. }
  18318. }
  18319. function mousedown( event ) {
  18320. if ( ! _this.enabled ) return;
  18321. event.preventDefault();
  18322. event.stopPropagation();
  18323. if ( _state === STATE.NONE ) {
  18324. _state = event.button;
  18325. if ( _state === STATE.ROTATE && !_this.noRotate ) {
  18326. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  18327. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  18328. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  18329. } else if ( !this.noPan ) {
  18330. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  18331. }
  18332. }
  18333. }
  18334. function mousemove( event ) {
  18335. if ( ! _this.enabled ) return;
  18336. if ( _keyPressed ) {
  18337. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  18338. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  18339. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  18340. _keyPressed = false;
  18341. }
  18342. if ( _state === STATE.NONE ) {
  18343. return;
  18344. } else if ( _state === STATE.ROTATE && !_this.noRotate ) {
  18345. _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  18346. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  18347. _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  18348. } else if ( _state === STATE.PAN && !_this.noPan ) {
  18349. _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  18350. }
  18351. }
  18352. function mouseup( event ) {
  18353. if ( ! _this.enabled ) return;
  18354. event.preventDefault();
  18355. event.stopPropagation();
  18356. _state = STATE.NONE;
  18357. }
  18358. function mousewheel( event ) {
  18359. if ( ! _this.enabled ) return;
  18360. event.preventDefault();
  18361. event.stopPropagation();
  18362. var delta = 0;
  18363. if ( event.wheelDelta ) { // WebKit / Opera / Explorer 9
  18364. delta = event.wheelDelta / 40;
  18365. } else if ( event.detail ) { // Firefox
  18366. delta = - event.detail / 3;
  18367. }
  18368. _zoomStart.y += ( 1 / delta ) * 0.05;
  18369. }
  18370. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  18371. this.domElement.addEventListener( 'mousemove', mousemove, false );
  18372. this.domElement.addEventListener( 'mousedown', mousedown, false );
  18373. this.domElement.addEventListener( 'mouseup', mouseup, false );
  18374. this.domElement.addEventListener( 'DOMMouseScroll', mousewheel, false );
  18375. this.domElement.addEventListener( 'mousewheel', mousewheel, false );
  18376. window.addEventListener( 'keydown', keydown, false );
  18377. window.addEventListener( 'keyup', keyup, false );
  18378. this.handleResize();
  18379. };
  18380. /**
  18381. * @author qiao / https://github.com/qiao
  18382. * @author mrdoob / http://mrdoob.com
  18383. * @author alteredq / http://alteredqualia.com/
  18384. * @author WestLangley / https://github.com/WestLangley
  18385. */
  18386. THREE.OrbitControls = function ( object, domElement ) {
  18387. THREE.EventTarget.call( this );
  18388. this.object = object;
  18389. this.domElement = ( domElement !== undefined ) ? domElement : document;
  18390. // API
  18391. this.center = new THREE.Vector3();
  18392. this.userZoom = true;
  18393. this.userZoomSpeed = 1.0;
  18394. this.userRotate = true;
  18395. this.userRotateSpeed = 1.0;
  18396. this.autoRotate = false;
  18397. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  18398. this.minPolarAngle = 0; // radians
  18399. this.maxPolarAngle = Math.PI; // radians
  18400. this.minDistance = 0;
  18401. this.maxDistance = Infinity;
  18402. // internals
  18403. var scope = this;
  18404. var EPS = 0.000001;
  18405. var PIXELS_PER_ROUND = 1800;
  18406. var rotateStart = new THREE.Vector2();
  18407. var rotateEnd = new THREE.Vector2();
  18408. var rotateDelta = new THREE.Vector2();
  18409. var zoomStart = new THREE.Vector2();
  18410. var zoomEnd = new THREE.Vector2();
  18411. var zoomDelta = new THREE.Vector2();
  18412. var phiDelta = 0;
  18413. var thetaDelta = 0;
  18414. var scale = 1;
  18415. var lastPosition = new THREE.Vector3();
  18416. var STATE = { NONE : -1, ROTATE : 0, ZOOM : 1 };
  18417. var state = STATE.NONE;
  18418. // events
  18419. var changeEvent = { type: 'change' };
  18420. this.rotateLeft = function ( angle ) {
  18421. if ( angle === undefined ) {
  18422. angle = getAutoRotationAngle();
  18423. }
  18424. thetaDelta -= angle;
  18425. };
  18426. this.rotateRight = function ( angle ) {
  18427. if ( angle === undefined ) {
  18428. angle = getAutoRotationAngle();
  18429. }
  18430. thetaDelta += angle;
  18431. };
  18432. this.rotateUp = function ( angle ) {
  18433. if ( angle === undefined ) {
  18434. angle = getAutoRotationAngle();
  18435. }
  18436. phiDelta -= angle;
  18437. };
  18438. this.rotateDown = function ( angle ) {
  18439. if ( angle === undefined ) {
  18440. angle = getAutoRotationAngle();
  18441. }
  18442. phiDelta += angle;
  18443. };
  18444. this.zoomIn = function ( zoomScale ) {
  18445. if ( zoomScale === undefined ) {
  18446. zoomScale = getZoomScale();
  18447. }
  18448. scale /= zoomScale;
  18449. };
  18450. this.zoomOut = function ( zoomScale ) {
  18451. if ( zoomScale === undefined ) {
  18452. zoomScale = getZoomScale();
  18453. }
  18454. scale *= zoomScale;
  18455. };
  18456. this.update = function () {
  18457. var position = this.object.position;
  18458. var offset = position.clone().subSelf( this.center )
  18459. // angle from z-axis around y-axis
  18460. var theta = Math.atan2( offset.x, offset.z );
  18461. // angle from y-axis
  18462. var phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y );
  18463. if ( this.autoRotate ) {
  18464. this.rotateLeft( getAutoRotationAngle() );
  18465. }
  18466. theta += thetaDelta;
  18467. phi += phiDelta;
  18468. // restrict phi to be between desired limits
  18469. phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, phi ) );
  18470. // restrict phi to be betwee EPS and PI-EPS
  18471. phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) );
  18472. var radius = offset.length() * scale;
  18473. // restrict radius to be between desired limits
  18474. radius = Math.max( this.minDistance, Math.min( this.maxDistance, radius ) );
  18475. offset.x = radius * Math.sin( phi ) * Math.sin( theta );
  18476. offset.y = radius * Math.cos( phi );
  18477. offset.z = radius * Math.sin( phi ) * Math.cos( theta );
  18478. position.copy( this.center ).addSelf( offset );
  18479. this.object.lookAt( this.center );
  18480. thetaDelta = 0;
  18481. phiDelta = 0;
  18482. scale = 1;
  18483. if ( lastPosition.distanceTo( this.object.position ) > 0 ) {
  18484. this.dispatchEvent( changeEvent );
  18485. lastPosition.copy( this.object.position );
  18486. }
  18487. };
  18488. function getAutoRotationAngle() {
  18489. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  18490. }
  18491. function getZoomScale() {
  18492. return Math.pow( 0.95, scope.userZoomSpeed );
  18493. }
  18494. function onMouseDown( event ) {
  18495. if ( !scope.userRotate ) return;
  18496. event.preventDefault();
  18497. if ( event.button === 0 || event.button === 2 ) {
  18498. state = STATE.ROTATE;
  18499. rotateStart.set( event.clientX, event.clientY );
  18500. } else if ( event.button === 1 ) {
  18501. state = STATE.ZOOM;
  18502. zoomStart.set( event.clientX, event.clientY );
  18503. }
  18504. document.addEventListener( 'mousemove', onMouseMove, false );
  18505. document.addEventListener( 'mouseup', onMouseUp, false );
  18506. }
  18507. function onMouseMove( event ) {
  18508. event.preventDefault();
  18509. if ( state === STATE.ROTATE ) {
  18510. rotateEnd.set( event.clientX, event.clientY );
  18511. rotateDelta.sub( rotateEnd, rotateStart );
  18512. scope.rotateLeft( 2 * Math.PI * rotateDelta.x / PIXELS_PER_ROUND * scope.userRotateSpeed );
  18513. scope.rotateUp( 2 * Math.PI * rotateDelta.y / PIXELS_PER_ROUND * scope.userRotateSpeed );
  18514. rotateStart.copy( rotateEnd );
  18515. } else if ( state === STATE.ZOOM ) {
  18516. zoomEnd.set( event.clientX, event.clientY );
  18517. zoomDelta.sub( zoomEnd, zoomStart );
  18518. if ( zoomDelta.y > 0 ) {
  18519. scope.zoomIn();
  18520. } else {
  18521. scope.zoomOut();
  18522. }
  18523. zoomStart.copy( zoomEnd );
  18524. }
  18525. }
  18526. function onMouseUp( event ) {
  18527. if ( ! scope.userRotate ) return;
  18528. document.removeEventListener( 'mousemove', onMouseMove, false );
  18529. document.removeEventListener( 'mouseup', onMouseUp, false );
  18530. state = STATE.NONE;
  18531. }
  18532. function onMouseWheel( event ) {
  18533. if ( ! scope.userZoom ) return;
  18534. if ( event.wheelDelta > 0 ) {
  18535. scope.zoomOut();
  18536. } else {
  18537. scope.zoomIn();
  18538. }
  18539. }
  18540. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  18541. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  18542. this.domElement.addEventListener( 'mousewheel', onMouseWheel, false );
  18543. };
  18544. /**
  18545. * @author hughes
  18546. */
  18547. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18548. THREE.Geometry.call( this );
  18549. radius = radius || 50;
  18550. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18551. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18552. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18553. var i, uvs = [],
  18554. center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );
  18555. this.vertices.push(center);
  18556. uvs.push( centerUV );
  18557. for ( i = 0; i <= segments; i ++ ) {
  18558. var vertex = new THREE.Vector3();
  18559. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  18560. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  18561. this.vertices.push( vertex );
  18562. uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  18563. }
  18564. var n = new THREE.Vector3( 0, 0, -1 );
  18565. for ( i = 1; i <= segments; i ++ ) {
  18566. var v1 = i;
  18567. var v2 = i + 1 ;
  18568. var v3 = 0;
  18569. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18570. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18571. }
  18572. this.computeCentroids();
  18573. this.computeFaceNormals();
  18574. this.boundingSphere = { radius: radius };
  18575. };
  18576. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18577. /**
  18578. * @author mrdoob / http://mrdoob.com/
  18579. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18580. */
  18581. THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides ) {
  18582. THREE.Geometry.call( this );
  18583. var scope = this,
  18584. width_half = width / 2,
  18585. height_half = height / 2,
  18586. depth_half = depth / 2;
  18587. var mpx, mpy, mpz, mnx, mny, mnz;
  18588. if ( materials !== undefined ) {
  18589. if ( materials instanceof Array ) {
  18590. this.materials = materials;
  18591. } else {
  18592. this.materials = [];
  18593. for ( var i = 0; i < 6; i ++ ) {
  18594. this.materials.push( materials );
  18595. }
  18596. }
  18597. mpx = 0; mnx = 1; mpy = 2; mny = 3; mpz = 4; mnz = 5;
  18598. } else {
  18599. this.materials = [];
  18600. }
  18601. this.sides = { px: true, nx: true, py: true, ny: true, pz: true, nz: true };
  18602. if ( sides != undefined ) {
  18603. for ( var s in sides ) {
  18604. if ( this.sides[ s ] !== undefined ) {
  18605. this.sides[ s ] = sides[ s ];
  18606. }
  18607. }
  18608. }
  18609. this.sides.px && buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, mpx ); // px
  18610. this.sides.nx && buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, mnx ); // nx
  18611. this.sides.py && buildPlane( 'x', 'z', 1, 1, width, depth, height_half, mpy ); // py
  18612. this.sides.ny && buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, mny ); // ny
  18613. this.sides.pz && buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, mpz ); // pz
  18614. this.sides.nz && buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, mnz ); // nz
  18615. function buildPlane( u, v, udir, vdir, width, height, depth, material ) {
  18616. var w, ix, iy,
  18617. gridX = segmentsWidth || 1,
  18618. gridY = segmentsHeight || 1,
  18619. width_half = width / 2,
  18620. height_half = height / 2,
  18621. offset = scope.vertices.length;
  18622. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18623. w = 'z';
  18624. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18625. w = 'y';
  18626. gridY = segmentsDepth || 1;
  18627. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18628. w = 'x';
  18629. gridX = segmentsDepth || 1;
  18630. }
  18631. var gridX1 = gridX + 1,
  18632. gridY1 = gridY + 1,
  18633. segment_width = width / gridX,
  18634. segment_height = height / gridY,
  18635. normal = new THREE.Vector3();
  18636. normal[ w ] = depth > 0 ? 1 : - 1;
  18637. for ( iy = 0; iy < gridY1; iy ++ ) {
  18638. for ( ix = 0; ix < gridX1; ix ++ ) {
  18639. var vector = new THREE.Vector3();
  18640. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18641. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18642. vector[ w ] = depth;
  18643. scope.vertices.push( vector );
  18644. }
  18645. }
  18646. for ( iy = 0; iy < gridY; iy++ ) {
  18647. for ( ix = 0; ix < gridX; ix++ ) {
  18648. var a = ix + gridX1 * iy;
  18649. var b = ix + gridX1 * ( iy + 1 );
  18650. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18651. var d = ( ix + 1 ) + gridX1 * iy;
  18652. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18653. face.normal.copy( normal );
  18654. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18655. face.materialIndex = material;
  18656. scope.faces.push( face );
  18657. scope.faceVertexUvs[ 0 ].push( [
  18658. new THREE.UV( ix / gridX, 1 - iy / gridY ),
  18659. new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18660. new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18661. new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18662. ] );
  18663. }
  18664. }
  18665. }
  18666. this.computeCentroids();
  18667. this.mergeVertices();
  18668. };
  18669. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18670. /**
  18671. * @author mrdoob / http://mrdoob.com/
  18672. */
  18673. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, segmentsRadius, segmentsHeight, openEnded ) {
  18674. THREE.Geometry.call( this );
  18675. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18676. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18677. height = height !== undefined ? height : 100;
  18678. var heightHalf = height / 2;
  18679. var segmentsX = segmentsRadius || 8;
  18680. var segmentsY = segmentsHeight || 1;
  18681. var x, y, vertices = [], uvs = [];
  18682. for ( y = 0; y <= segmentsY; y ++ ) {
  18683. var verticesRow = [];
  18684. var uvsRow = [];
  18685. var v = y / segmentsY;
  18686. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18687. for ( x = 0; x <= segmentsX; x ++ ) {
  18688. var u = x / segmentsX;
  18689. var vertex = new THREE.Vector3();
  18690. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18691. vertex.y = - v * height + heightHalf;
  18692. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18693. this.vertices.push( vertex );
  18694. verticesRow.push( this.vertices.length - 1 );
  18695. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18696. }
  18697. vertices.push( verticesRow );
  18698. uvs.push( uvsRow );
  18699. }
  18700. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18701. var na, nb;
  18702. for ( x = 0; x < segmentsX; x ++ ) {
  18703. if ( radiusTop !== 0 ) {
  18704. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18705. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18706. } else {
  18707. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18708. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18709. }
  18710. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18711. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18712. for ( y = 0; y < segmentsY; y ++ ) {
  18713. var v1 = vertices[ y ][ x ];
  18714. var v2 = vertices[ y + 1 ][ x ];
  18715. var v3 = vertices[ y + 1 ][ x + 1 ];
  18716. var v4 = vertices[ y ][ x + 1 ];
  18717. var n1 = na.clone();
  18718. var n2 = na.clone();
  18719. var n3 = nb.clone();
  18720. var n4 = nb.clone();
  18721. var uv1 = uvs[ y ][ x ].clone();
  18722. var uv2 = uvs[ y + 1 ][ x ].clone();
  18723. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18724. var uv4 = uvs[ y ][ x + 1 ].clone();
  18725. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18726. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18727. }
  18728. }
  18729. // top cap
  18730. if ( !openEnded && radiusTop > 0 ) {
  18731. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18732. for ( x = 0; x < segmentsX; x ++ ) {
  18733. var v1 = vertices[ 0 ][ x ];
  18734. var v2 = vertices[ 0 ][ x + 1 ];
  18735. var v3 = this.vertices.length - 1;
  18736. var n1 = new THREE.Vector3( 0, 1, 0 );
  18737. var n2 = new THREE.Vector3( 0, 1, 0 );
  18738. var n3 = new THREE.Vector3( 0, 1, 0 );
  18739. var uv1 = uvs[ 0 ][ x ].clone();
  18740. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18741. var uv3 = new THREE.UV( uv2.u, 0 );
  18742. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18743. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18744. }
  18745. }
  18746. // bottom cap
  18747. if ( !openEnded && radiusBottom > 0 ) {
  18748. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18749. for ( x = 0; x < segmentsX; x ++ ) {
  18750. var v1 = vertices[ y ][ x + 1 ];
  18751. var v2 = vertices[ y ][ x ];
  18752. var v3 = this.vertices.length - 1;
  18753. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18754. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18755. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18756. var uv1 = uvs[ y ][ x + 1 ].clone();
  18757. var uv2 = uvs[ y ][ x ].clone();
  18758. var uv3 = new THREE.UV( uv2.u, 1 );
  18759. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18760. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18761. }
  18762. }
  18763. this.computeCentroids();
  18764. this.computeFaceNormals();
  18765. }
  18766. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18767. /**
  18768. * @author zz85 / http://www.lab4games.net/zz85/blog
  18769. *
  18770. * Creates extruded geometry from a path shape.
  18771. *
  18772. * parameters = {
  18773. *
  18774. * size: <float>, // size of the text
  18775. * height: <float>, // thickness to extrude text
  18776. * curveSegments: <int>, // number of points on the curves
  18777. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18778. * amount: <int>, // Amount
  18779. *
  18780. * bevelEnabled: <bool>, // turn on bevel
  18781. * bevelThickness: <float>, // how deep into text bevel goes
  18782. * bevelSize: <float>, // how far from text outline is bevel
  18783. * bevelSegments: <int>, // number of bevel layers
  18784. *
  18785. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18786. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18787. *
  18788. * material: <int> // material index for front and back faces
  18789. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18790. * uvGenerator: <Object> // object that provides UV generator functions
  18791. *
  18792. * }
  18793. **/
  18794. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18795. if ( typeof( shapes ) === "undefined" ) {
  18796. shapes = [];
  18797. return;
  18798. }
  18799. THREE.Geometry.call( this );
  18800. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18801. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18802. this.addShapeList( shapes, options );
  18803. this.computeCentroids();
  18804. this.computeFaceNormals();
  18805. // can't really use automatic vertex normals
  18806. // as then front and back sides get smoothed too
  18807. // should do separate smoothing just for sides
  18808. //this.computeVertexNormals();
  18809. //console.log( "took", ( Date.now() - startTime ) );
  18810. };
  18811. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18812. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18813. var sl = shapes.length;
  18814. for ( var s = 0; s < sl; s ++ ) {
  18815. var shape = shapes[ s ];
  18816. this.addShape( shape, options );
  18817. }
  18818. };
  18819. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18820. var amount = options.amount !== undefined ? options.amount : 100;
  18821. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18822. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18823. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18824. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18825. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18826. var steps = options.steps !== undefined ? options.steps : 1;
  18827. var extrudePath = options.extrudePath;
  18828. var extrudePts, extrudeByPath = false;
  18829. var material = options.material;
  18830. var extrudeMaterial = options.extrudeMaterial;
  18831. // Use default WorldUVGenerator if no UV generators are specified.
  18832. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18833. var shapebb = this.shapebb;
  18834. //shapebb = shape.getBoundingBox();
  18835. var splineTube, binormal, normal, position2;
  18836. if ( extrudePath ) {
  18837. extrudePts = extrudePath.getSpacedPoints( steps );
  18838. extrudeByPath = true;
  18839. bevelEnabled = false; // bevels not supported for path extrusion
  18840. // SETUP TNB variables
  18841. // Reuse TNB from TubeGeomtry for now.
  18842. // TODO1 - have a .isClosed in spline?
  18843. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18844. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18845. binormal = new THREE.Vector3();
  18846. normal = new THREE.Vector3();
  18847. position2 = new THREE.Vector3();
  18848. }
  18849. // Safeguards if bevels are not enabled
  18850. if ( ! bevelEnabled ) {
  18851. bevelSegments = 0;
  18852. bevelThickness = 0;
  18853. bevelSize = 0;
  18854. }
  18855. // Variables initalization
  18856. var ahole, h, hl; // looping of holes
  18857. var scope = this;
  18858. var bevelPoints = [];
  18859. var shapesOffset = this.vertices.length;
  18860. var shapePoints = shape.extractPoints();
  18861. var vertices = shapePoints.shape;
  18862. var holes = shapePoints.holes;
  18863. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18864. if ( reverse ) {
  18865. vertices = vertices.reverse();
  18866. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18867. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18868. ahole = holes[ h ];
  18869. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18870. holes[ h ] = ahole.reverse();
  18871. }
  18872. }
  18873. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18874. }
  18875. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18876. /* Vertices */
  18877. var contour = vertices; // vertices has all points but contour has only points of circumference
  18878. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18879. ahole = holes[ h ];
  18880. vertices = vertices.concat( ahole );
  18881. }
  18882. function scalePt2 ( pt, vec, size ) {
  18883. if ( !vec ) console.log( "die" );
  18884. return vec.clone().multiplyScalar( size ).addSelf( pt );
  18885. }
  18886. var b, bs, t, z,
  18887. vert, vlen = vertices.length,
  18888. face, flen = faces.length,
  18889. cont, clen = contour.length;
  18890. // Find directions for point movement
  18891. var RAD_TO_DEGREES = 180 / Math.PI;
  18892. function getBevelVec( pt_i, pt_j, pt_k ) {
  18893. // Algorithm 2
  18894. return getBevelVec2( pt_i, pt_j, pt_k );
  18895. }
  18896. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18897. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18898. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18899. if ( anglea > angleb ) {
  18900. angleb += Math.PI * 2;
  18901. }
  18902. var anglec = ( anglea + angleb ) / 2;
  18903. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18904. var x = - Math.cos( anglec );
  18905. var y = - Math.sin( anglec );
  18906. var vec = new THREE.Vector2( x, y ); //.normalize();
  18907. return vec;
  18908. }
  18909. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18910. var a = THREE.ExtrudeGeometry.__v1,
  18911. b = THREE.ExtrudeGeometry.__v2,
  18912. v_hat = THREE.ExtrudeGeometry.__v3,
  18913. w_hat = THREE.ExtrudeGeometry.__v4,
  18914. p = THREE.ExtrudeGeometry.__v5,
  18915. q = THREE.ExtrudeGeometry.__v6,
  18916. v, w,
  18917. v_dot_w_hat, q_sub_p_dot_w_hat,
  18918. s, intersection;
  18919. // good reading for line-line intersection
  18920. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18921. // define a as vector j->i
  18922. // define b as vectot k->i
  18923. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18924. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18925. // get unit vectors
  18926. v = a.normalize();
  18927. w = b.normalize();
  18928. // normals from pt i
  18929. v_hat.set( -v.y, v.x );
  18930. w_hat.set( w.y, -w.x );
  18931. // pts from i
  18932. p.copy( pt_i ).addSelf( v_hat );
  18933. q.copy( pt_i ).addSelf( w_hat );
  18934. if ( p.equals( q ) ) {
  18935. //console.log("Warning: lines are straight");
  18936. return w_hat.clone();
  18937. }
  18938. // Points from j, k. helps prevents points cross overover most of the time
  18939. p.copy( pt_j ).addSelf( v_hat );
  18940. q.copy( pt_k ).addSelf( w_hat );
  18941. v_dot_w_hat = v.dot( w_hat );
  18942. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  18943. // We should not reach these conditions
  18944. if ( v_dot_w_hat === 0 ) {
  18945. console.log( "Either infinite or no solutions!" );
  18946. if ( q_sub_p_dot_w_hat === 0 ) {
  18947. console.log( "Its finite solutions." );
  18948. } else {
  18949. console.log( "Too bad, no solutions." );
  18950. }
  18951. }
  18952. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18953. if ( s < 0 ) {
  18954. // in case of emergecy, revert to algorithm 1.
  18955. return getBevelVec1( pt_i, pt_j, pt_k );
  18956. }
  18957. intersection = v.multiplyScalar( s ).addSelf( p );
  18958. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18959. }
  18960. var contourMovements = [];
  18961. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18962. if ( j === il ) j = 0;
  18963. if ( k === il ) k = 0;
  18964. // (j)---(i)---(k)
  18965. // console.log('i,j,k', i, j , k)
  18966. var pt_i = contour[ i ];
  18967. var pt_j = contour[ j ];
  18968. var pt_k = contour[ k ];
  18969. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18970. }
  18971. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18972. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18973. ahole = holes[ h ];
  18974. oneHoleMovements = [];
  18975. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18976. if ( j === il ) j = 0;
  18977. if ( k === il ) k = 0;
  18978. // (j)---(i)---(k)
  18979. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18980. }
  18981. holesMovements.push( oneHoleMovements );
  18982. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18983. }
  18984. // Loop bevelSegments, 1 for the front, 1 for the back
  18985. for ( b = 0; b < bevelSegments; b ++ ) {
  18986. //for ( b = bevelSegments; b > 0; b -- ) {
  18987. t = b / bevelSegments;
  18988. z = bevelThickness * ( 1 - t );
  18989. //z = bevelThickness * t;
  18990. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18991. //bs = bevelSize * t ; // linear
  18992. // contract shape
  18993. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18994. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18995. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18996. v( vert.x, vert.y, - z );
  18997. }
  18998. // expand holes
  18999. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19000. ahole = holes[ h ];
  19001. oneHoleMovements = holesMovements[ h ];
  19002. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19003. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19004. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19005. v( vert.x, vert.y, -z );
  19006. }
  19007. }
  19008. }
  19009. bs = bevelSize;
  19010. // Back facing vertices
  19011. for ( i = 0; i < vlen; i ++ ) {
  19012. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19013. if ( !extrudeByPath ) {
  19014. v( vert.x, vert.y, 0 );
  19015. } else {
  19016. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19017. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19018. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19019. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  19020. v( position2.x, position2.y, position2.z );
  19021. }
  19022. }
  19023. // Add stepped vertices...
  19024. // Including front facing vertices
  19025. var s;
  19026. for ( s = 1; s <= steps; s ++ ) {
  19027. for ( i = 0; i < vlen; i ++ ) {
  19028. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19029. if ( !extrudeByPath ) {
  19030. v( vert.x, vert.y, amount / steps * s );
  19031. } else {
  19032. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19033. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19034. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19035. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  19036. v( position2.x, position2.y, position2.z );
  19037. }
  19038. }
  19039. }
  19040. // Add bevel segments planes
  19041. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19042. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19043. t = b / bevelSegments;
  19044. z = bevelThickness * ( 1 - t );
  19045. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19046. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19047. // contract shape
  19048. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19049. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19050. v( vert.x, vert.y, amount + z );
  19051. }
  19052. // expand holes
  19053. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19054. ahole = holes[ h ];
  19055. oneHoleMovements = holesMovements[ h ];
  19056. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19057. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19058. if ( !extrudeByPath ) {
  19059. v( vert.x, vert.y, amount + z );
  19060. } else {
  19061. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19062. }
  19063. }
  19064. }
  19065. }
  19066. /* Faces */
  19067. // Top and bottom faces
  19068. buildLidFaces();
  19069. // Sides faces
  19070. buildSideFaces();
  19071. ///// Internal functions
  19072. function buildLidFaces() {
  19073. if ( bevelEnabled ) {
  19074. var layer = 0 ; // steps + 1
  19075. var offset = vlen * layer;
  19076. // Bottom faces
  19077. for ( i = 0; i < flen; i ++ ) {
  19078. face = faces[ i ];
  19079. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19080. }
  19081. layer = steps + bevelSegments * 2;
  19082. offset = vlen * layer;
  19083. // Top faces
  19084. for ( i = 0; i < flen; i ++ ) {
  19085. face = faces[ i ];
  19086. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19087. }
  19088. } else {
  19089. // Bottom faces
  19090. for ( i = 0; i < flen; i++ ) {
  19091. face = faces[ i ];
  19092. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19093. }
  19094. // Top faces
  19095. for ( i = 0; i < flen; i ++ ) {
  19096. face = faces[ i ];
  19097. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19098. }
  19099. }
  19100. }
  19101. // Create faces for the z-sides of the shape
  19102. function buildSideFaces() {
  19103. var layeroffset = 0;
  19104. sidewalls( contour, layeroffset );
  19105. layeroffset += contour.length;
  19106. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19107. ahole = holes[ h ];
  19108. sidewalls( ahole, layeroffset );
  19109. //, true
  19110. layeroffset += ahole.length;
  19111. }
  19112. }
  19113. function sidewalls( contour, layeroffset ) {
  19114. var j, k;
  19115. i = contour.length;
  19116. while ( --i >= 0 ) {
  19117. j = i;
  19118. k = i - 1;
  19119. if ( k < 0 ) k = contour.length - 1;
  19120. //console.log('b', i,j, i-1, k,vertices.length);
  19121. var s = 0, sl = steps + bevelSegments * 2;
  19122. for ( s = 0; s < sl; s ++ ) {
  19123. var slen1 = vlen * s;
  19124. var slen2 = vlen * ( s + 1 );
  19125. var a = layeroffset + j + slen1,
  19126. b = layeroffset + k + slen1,
  19127. c = layeroffset + k + slen2,
  19128. d = layeroffset + j + slen2;
  19129. f4( a, b, c, d, contour, s, sl, j, k );
  19130. }
  19131. }
  19132. }
  19133. function v( x, y, z ) {
  19134. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19135. }
  19136. function f3( a, b, c, isBottom ) {
  19137. a += shapesOffset;
  19138. b += shapesOffset;
  19139. c += shapesOffset;
  19140. // normal, color, material
  19141. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19142. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19143. scope.faceVertexUvs[ 0 ].push( uvs );
  19144. }
  19145. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19146. a += shapesOffset;
  19147. b += shapesOffset;
  19148. c += shapesOffset;
  19149. d += shapesOffset;
  19150. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19151. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19152. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19153. scope.faceVertexUvs[ 0 ].push( uvs );
  19154. }
  19155. };
  19156. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19157. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19158. var ax = geometry.vertices[ indexA ].x,
  19159. ay = geometry.vertices[ indexA ].y,
  19160. bx = geometry.vertices[ indexB ].x,
  19161. by = geometry.vertices[ indexB ].y,
  19162. cx = geometry.vertices[ indexC ].x,
  19163. cy = geometry.vertices[ indexC ].y;
  19164. return [
  19165. new THREE.UV( ax, ay ),
  19166. new THREE.UV( bx, by ),
  19167. new THREE.UV( cx, cy )
  19168. ];
  19169. },
  19170. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19171. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19172. },
  19173. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19174. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19175. contourIndex1, contourIndex2 ) {
  19176. var ax = geometry.vertices[ indexA ].x,
  19177. ay = geometry.vertices[ indexA ].y,
  19178. az = geometry.vertices[ indexA ].z,
  19179. bx = geometry.vertices[ indexB ].x,
  19180. by = geometry.vertices[ indexB ].y,
  19181. bz = geometry.vertices[ indexB ].z,
  19182. cx = geometry.vertices[ indexC ].x,
  19183. cy = geometry.vertices[ indexC ].y,
  19184. cz = geometry.vertices[ indexC ].z,
  19185. dx = geometry.vertices[ indexD ].x,
  19186. dy = geometry.vertices[ indexD ].y,
  19187. dz = geometry.vertices[ indexD ].z;
  19188. if ( Math.abs( ay - by ) < 0.01 ) {
  19189. return [
  19190. new THREE.UV( ax, 1 - az ),
  19191. new THREE.UV( bx, 1 - bz ),
  19192. new THREE.UV( cx, 1 - cz ),
  19193. new THREE.UV( dx, 1 - dz )
  19194. ];
  19195. } else {
  19196. return [
  19197. new THREE.UV( ay, 1 - az ),
  19198. new THREE.UV( by, 1 - bz ),
  19199. new THREE.UV( cy, 1 - cz ),
  19200. new THREE.UV( dy, 1 - dz )
  19201. ];
  19202. }
  19203. }
  19204. };
  19205. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19206. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19207. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19208. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19209. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19210. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19211. /**
  19212. * @author jonobr1 / http://jonobr1.com
  19213. *
  19214. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19215. * ExtrudeGeometry.
  19216. *
  19217. * parameters = {
  19218. *
  19219. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19220. *
  19221. * material: <int> // material index for front and back faces
  19222. * uvGenerator: <Object> // object that provides UV generator functions
  19223. *
  19224. * }
  19225. **/
  19226. THREE.ShapeGeometry = function ( shapes, options ) {
  19227. THREE.Geometry.call( this );
  19228. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19229. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19230. this.addShapeList( shapes, options );
  19231. this.computeCentroids();
  19232. this.computeFaceNormals();
  19233. };
  19234. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19235. /**
  19236. * Add an array of shapes to THREE.ShapeGeometry.
  19237. */
  19238. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19239. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19240. this.addShape( shapes[ i ], options );
  19241. }
  19242. return this;
  19243. };
  19244. /**
  19245. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19246. */
  19247. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19248. if ( options === undefined ) options = {};
  19249. var material = options.material;
  19250. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19251. var shapebb = this.shapebb;
  19252. //
  19253. var i, l, hole, s;
  19254. var shapesOffset = this.vertices.length;
  19255. var shapePoints = shape.extractPoints();
  19256. var vertices = shapePoints.shape;
  19257. var holes = shapePoints.holes;
  19258. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19259. if ( reverse ) {
  19260. vertices = vertices.reverse();
  19261. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19262. for ( i = 0, l = holes.length; i < l; i++ ) {
  19263. hole = holes[ i ];
  19264. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19265. holes[ i ] = hole.reverse();
  19266. }
  19267. }
  19268. reverse = false;
  19269. }
  19270. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19271. // Vertices
  19272. var contour = vertices;
  19273. for ( i = 0, l = holes.length; i < l; i++ ) {
  19274. hole = holes[ i ];
  19275. vertices = vertices.concat( hole );
  19276. }
  19277. //
  19278. var vert, vlen = vertices.length;
  19279. var face, flen = faces.length;
  19280. var cont, clen = contour.length;
  19281. for ( i = 0; i < vlen; i++ ) {
  19282. vert = vertices[ i ];
  19283. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19284. }
  19285. for ( i = 0; i < flen; i++ ) {
  19286. face = faces[ i ];
  19287. var a = face[ 0 ] + shapesOffset;
  19288. var b = face[ 1 ] + shapesOffset;
  19289. var c = face[ 2 ] + shapesOffset;
  19290. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19291. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19292. }
  19293. };
  19294. /**
  19295. * @author astrodud / http://astrodud.isgreat.org/
  19296. * @author zz85 / https://github.com/zz85
  19297. */
  19298. THREE.LatheGeometry = function ( points, steps, angle ) {
  19299. THREE.Geometry.call( this );
  19300. var _steps = steps || 12;
  19301. var _angle = angle || 2 * Math.PI;
  19302. var _newV = [];
  19303. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  19304. for ( var j = 0; j < points.length; j ++ ) {
  19305. _newV[ j ] = points[ j ].clone();
  19306. this.vertices.push( _newV[ j ] );
  19307. }
  19308. var i, il = _steps + 1;
  19309. for ( i = 0; i < il; i ++ ) {
  19310. for ( var j = 0; j < _newV.length; j ++ ) {
  19311. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  19312. this.vertices.push( _newV[ j ] );
  19313. }
  19314. }
  19315. for ( i = 0; i < _steps; i ++ ) {
  19316. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  19317. var a = i * kl + k;
  19318. var b = ( ( i + 1 ) % il ) * kl + k;
  19319. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  19320. var d = i * kl + ( k + 1 ) % kl;
  19321. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19322. this.faceVertexUvs[ 0 ].push( [
  19323. new THREE.UV( 1 - i / _steps, k / kl ),
  19324. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  19325. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  19326. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  19327. ] );
  19328. }
  19329. }
  19330. this.computeCentroids();
  19331. this.computeFaceNormals();
  19332. this.computeVertexNormals();
  19333. };
  19334. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19335. /**
  19336. * @author mrdoob / http://mrdoob.com/
  19337. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19338. */
  19339. THREE.PlaneGeometry = function ( width, height, segmentsWidth, segmentsheight ) {
  19340. THREE.Geometry.call( this );
  19341. var ix, iz,
  19342. width_half = width / 2,
  19343. height_half = height / 2,
  19344. gridX = segmentsWidth || 1,
  19345. gridZ = segmentsheight || 1,
  19346. gridX1 = gridX + 1,
  19347. gridZ1 = gridZ + 1,
  19348. segment_width = width / gridX,
  19349. segment_height = height / gridZ,
  19350. normal = new THREE.Vector3( 0, 0, 1 );
  19351. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19352. for ( ix = 0; ix < gridX1; ix ++ ) {
  19353. var x = ix * segment_width - width_half;
  19354. var y = iz * segment_height - height_half;
  19355. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19356. }
  19357. }
  19358. for ( iz = 0; iz < gridZ; iz ++ ) {
  19359. for ( ix = 0; ix < gridX; ix ++ ) {
  19360. var a = ix + gridX1 * iz;
  19361. var b = ix + gridX1 * ( iz + 1 );
  19362. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19363. var d = ( ix + 1 ) + gridX1 * iz;
  19364. var face = new THREE.Face4( a, b, c, d );
  19365. face.normal.copy( normal );
  19366. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19367. this.faces.push( face );
  19368. this.faceVertexUvs[ 0 ].push( [
  19369. new THREE.UV( ix / gridX, 1 - iz / gridZ ),
  19370. new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19371. new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19372. new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19373. ] );
  19374. }
  19375. }
  19376. this.computeCentroids();
  19377. };
  19378. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19379. /**
  19380. * @author mrdoob / http://mrdoob.com/
  19381. */
  19382. THREE.SphereGeometry = function ( radius, segmentsWidth, segmentsHeight, phiStart, phiLength, thetaStart, thetaLength ) {
  19383. THREE.Geometry.call( this );
  19384. radius = radius || 50;
  19385. phiStart = phiStart !== undefined ? phiStart : 0;
  19386. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19387. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19388. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19389. var segmentsX = Math.max( 3, Math.floor( segmentsWidth ) || 8 );
  19390. var segmentsY = Math.max( 2, Math.floor( segmentsHeight ) || 6 );
  19391. var x, y, vertices = [], uvs = [];
  19392. for ( y = 0; y <= segmentsY; y ++ ) {
  19393. var verticesRow = [];
  19394. var uvsRow = [];
  19395. for ( x = 0; x <= segmentsX; x ++ ) {
  19396. var u = x / segmentsX;
  19397. var v = y / segmentsY;
  19398. var vertex = new THREE.Vector3();
  19399. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19400. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19401. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19402. this.vertices.push( vertex );
  19403. verticesRow.push( this.vertices.length - 1 );
  19404. uvsRow.push( new THREE.UV( u, 1 - v ) );
  19405. }
  19406. vertices.push( verticesRow );
  19407. uvs.push( uvsRow );
  19408. }
  19409. for ( y = 0; y < segmentsY; y ++ ) {
  19410. for ( x = 0; x < segmentsX; x ++ ) {
  19411. var v1 = vertices[ y ][ x + 1 ];
  19412. var v2 = vertices[ y ][ x ];
  19413. var v3 = vertices[ y + 1 ][ x ];
  19414. var v4 = vertices[ y + 1 ][ x + 1 ];
  19415. var n1 = this.vertices[ v1 ].clone().normalize();
  19416. var n2 = this.vertices[ v2 ].clone().normalize();
  19417. var n3 = this.vertices[ v3 ].clone().normalize();
  19418. var n4 = this.vertices[ v4 ].clone().normalize();
  19419. var uv1 = uvs[ y ][ x + 1 ].clone();
  19420. var uv2 = uvs[ y ][ x ].clone();
  19421. var uv3 = uvs[ y + 1 ][ x ].clone();
  19422. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19423. if ( Math.abs( this.vertices[ v1 ].y ) == radius ) {
  19424. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19425. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19426. } else if ( Math.abs( this.vertices[ v3 ].y ) == radius ) {
  19427. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19428. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19429. } else {
  19430. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19431. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19432. }
  19433. }
  19434. }
  19435. this.computeCentroids();
  19436. this.computeFaceNormals();
  19437. this.boundingSphere = { radius: radius };
  19438. };
  19439. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19440. /**
  19441. * @author zz85 / http://www.lab4games.net/zz85/blog
  19442. * @author alteredq / http://alteredqualia.com/
  19443. *
  19444. * For creating 3D text geometry in three.js
  19445. *
  19446. * Text = 3D Text
  19447. *
  19448. * parameters = {
  19449. * size: <float>, // size of the text
  19450. * height: <float>, // thickness to extrude text
  19451. * curveSegments: <int>, // number of points on the curves
  19452. *
  19453. * font: <string>, // font name
  19454. * weight: <string>, // font weight (normal, bold)
  19455. * style: <string>, // font style (normal, italics)
  19456. *
  19457. * bevelEnabled: <bool>, // turn on bevel
  19458. * bevelThickness: <float>, // how deep into text bevel goes
  19459. * bevelSize: <float>, // how far from text outline is bevel
  19460. * }
  19461. *
  19462. */
  19463. /* Usage Examples
  19464. // TextGeometry wrapper
  19465. var text3d = new TextGeometry( text, options );
  19466. // Complete manner
  19467. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19468. var text3d = new ExtrudeGeometry( textShapes, options );
  19469. */
  19470. THREE.TextGeometry = function ( text, parameters ) {
  19471. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19472. // translate parameters to ExtrudeGeometry API
  19473. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19474. // defaults
  19475. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19476. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19477. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19478. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19479. };
  19480. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19481. /**
  19482. * @author oosmoxiecode
  19483. * @author mrdoob / http://mrdoob.com/
  19484. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19485. */
  19486. THREE.TorusGeometry = function ( radius, tube, segmentsR, segmentsT, arc ) {
  19487. THREE.Geometry.call( this );
  19488. var scope = this;
  19489. this.radius = radius || 100;
  19490. this.tube = tube || 40;
  19491. this.segmentsR = segmentsR || 8;
  19492. this.segmentsT = segmentsT || 6;
  19493. this.arc = arc || Math.PI * 2;
  19494. var center = new THREE.Vector3(), uvs = [], normals = [];
  19495. for ( var j = 0; j <= this.segmentsR; j ++ ) {
  19496. for ( var i = 0; i <= this.segmentsT; i ++ ) {
  19497. var u = i / this.segmentsT * this.arc;
  19498. var v = j / this.segmentsR * Math.PI * 2;
  19499. center.x = this.radius * Math.cos( u );
  19500. center.y = this.radius * Math.sin( u );
  19501. var vertex = new THREE.Vector3();
  19502. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19503. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19504. vertex.z = this.tube * Math.sin( v );
  19505. this.vertices.push( vertex );
  19506. uvs.push( new THREE.UV( i / this.segmentsT, j / this.segmentsR ) );
  19507. normals.push( vertex.clone().subSelf( center ).normalize() );
  19508. }
  19509. }
  19510. for ( var j = 1; j <= this.segmentsR; j ++ ) {
  19511. for ( var i = 1; i <= this.segmentsT; i ++ ) {
  19512. var a = ( this.segmentsT + 1 ) * j + i - 1;
  19513. var b = ( this.segmentsT + 1 ) * ( j - 1 ) + i - 1;
  19514. var c = ( this.segmentsT + 1 ) * ( j - 1 ) + i;
  19515. var d = ( this.segmentsT + 1 ) * j + i;
  19516. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19517. face.normal.addSelf( normals[ a ] );
  19518. face.normal.addSelf( normals[ b ] );
  19519. face.normal.addSelf( normals[ c ] );
  19520. face.normal.addSelf( normals[ d ] );
  19521. face.normal.normalize();
  19522. this.faces.push( face );
  19523. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19524. }
  19525. }
  19526. this.computeCentroids();
  19527. };
  19528. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19529. /**
  19530. * @author oosmoxiecode
  19531. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19532. */
  19533. THREE.TorusKnotGeometry = function ( radius, tube, segmentsR, segmentsT, p, q, heightScale ) {
  19534. THREE.Geometry.call( this );
  19535. var scope = this;
  19536. this.radius = radius || 200;
  19537. this.tube = tube || 40;
  19538. this.segmentsR = segmentsR || 64;
  19539. this.segmentsT = segmentsT || 8;
  19540. this.p = p || 2;
  19541. this.q = q || 3;
  19542. this.heightScale = heightScale || 1;
  19543. this.grid = new Array(this.segmentsR);
  19544. var tang = new THREE.Vector3();
  19545. var n = new THREE.Vector3();
  19546. var bitan = new THREE.Vector3();
  19547. for ( var i = 0; i < this.segmentsR; ++ i ) {
  19548. this.grid[ i ] = new Array( this.segmentsT );
  19549. for ( var j = 0; j < this.segmentsT; ++ j ) {
  19550. var u = i / this.segmentsR * 2 * this.p * Math.PI;
  19551. var v = j / this.segmentsT * 2 * Math.PI;
  19552. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19553. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19554. var cx, cy;
  19555. tang.sub( p2, p1 );
  19556. n.add( p2, p1 );
  19557. bitan.cross( tang, n );
  19558. n.cross( bitan, tang );
  19559. bitan.normalize();
  19560. n.normalize();
  19561. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19562. cy = this.tube * Math.sin( v );
  19563. p1.x += cx * n.x + cy * bitan.x;
  19564. p1.y += cx * n.y + cy * bitan.y;
  19565. p1.z += cx * n.z + cy * bitan.z;
  19566. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19567. }
  19568. }
  19569. for ( var i = 0; i < this.segmentsR; ++ i ) {
  19570. for ( var j = 0; j < this.segmentsT; ++ j ) {
  19571. var ip = ( i + 1 ) % this.segmentsR;
  19572. var jp = ( j + 1 ) % this.segmentsT;
  19573. var a = this.grid[ i ][ j ];
  19574. var b = this.grid[ ip ][ j ];
  19575. var c = this.grid[ ip ][ jp ];
  19576. var d = this.grid[ i ][ jp ];
  19577. var uva = new THREE.UV( i / this.segmentsR, j / this.segmentsT );
  19578. var uvb = new THREE.UV( ( i + 1 ) / this.segmentsR, j / this.segmentsT );
  19579. var uvc = new THREE.UV( ( i + 1 ) / this.segmentsR, ( j + 1 ) / this.segmentsT );
  19580. var uvd = new THREE.UV( i / this.segmentsR, ( j + 1 ) / this.segmentsT );
  19581. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19582. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19583. }
  19584. }
  19585. this.computeCentroids();
  19586. this.computeFaceNormals();
  19587. this.computeVertexNormals();
  19588. function vert( x, y, z ) {
  19589. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19590. }
  19591. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19592. var cu = Math.cos( u );
  19593. var cv = Math.cos( v );
  19594. var su = Math.sin( u );
  19595. var quOverP = in_q / in_p * u;
  19596. var cs = Math.cos( quOverP );
  19597. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19598. var ty = radius * ( 2 + cs ) * su * 0.5;
  19599. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19600. return new THREE.Vector3( tx, ty, tz );
  19601. }
  19602. };
  19603. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19604. /**
  19605. * @author WestLangley / https://github.com/WestLangley
  19606. * @author zz85 / https://github.com/zz85
  19607. * @author miningold / https://github.com/miningold
  19608. *
  19609. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19610. *
  19611. * Creates a tube which extrudes along a 3d spline
  19612. *
  19613. * Uses parallel transport frames as described in
  19614. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19615. */
  19616. THREE.TubeGeometry = function( path, segments, radius, segmentsRadius, closed, debug ) {
  19617. THREE.Geometry.call( this );
  19618. this.path = path;
  19619. this.segments = segments || 64;
  19620. this.radius = radius || 1;
  19621. this.segmentsRadius = segmentsRadius || 8;
  19622. this.closed = closed || false;
  19623. if ( debug ) this.debug = new THREE.Object3D();
  19624. this.grid = [];
  19625. var scope = this,
  19626. tangent,
  19627. normal,
  19628. binormal,
  19629. numpoints = this.segments + 1,
  19630. x, y, z,
  19631. tx, ty, tz,
  19632. u, v,
  19633. cx, cy,
  19634. pos, pos2 = new THREE.Vector3(),
  19635. i, j,
  19636. ip, jp,
  19637. a, b, c, d,
  19638. uva, uvb, uvc, uvd;
  19639. var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
  19640. tangents = frames.tangents,
  19641. normals = frames.normals,
  19642. binormals = frames.binormals;
  19643. // proxy internals
  19644. this.tangents = tangents;
  19645. this.normals = normals;
  19646. this.binormals = binormals;
  19647. function vert( x, y, z ) {
  19648. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19649. }
  19650. // consruct the grid
  19651. for ( i = 0; i < numpoints; i++ ) {
  19652. this.grid[ i ] = [];
  19653. u = i / ( numpoints - 1 );
  19654. pos = path.getPointAt( u );
  19655. tangent = tangents[ i ];
  19656. normal = normals[ i ];
  19657. binormal = binormals[ i ];
  19658. if ( this.debug ) {
  19659. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19660. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19661. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19662. }
  19663. for ( j = 0; j < this.segmentsRadius; j++ ) {
  19664. v = j / this.segmentsRadius * 2 * Math.PI;
  19665. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19666. cy = this.radius * Math.sin( v );
  19667. pos2.copy( pos );
  19668. pos2.x += cx * normal.x + cy * binormal.x;
  19669. pos2.y += cx * normal.y + cy * binormal.y;
  19670. pos2.z += cx * normal.z + cy * binormal.z;
  19671. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19672. }
  19673. }
  19674. // construct the mesh
  19675. for ( i = 0; i < this.segments; i++ ) {
  19676. for ( j = 0; j < this.segmentsRadius; j++ ) {
  19677. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  19678. jp = (j + 1) % this.segmentsRadius;
  19679. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19680. b = this.grid[ ip ][ j ];
  19681. c = this.grid[ ip ][ jp ];
  19682. d = this.grid[ i ][ jp ];
  19683. uva = new THREE.UV( i / this.segments, j / this.segmentsRadius );
  19684. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.segmentsRadius );
  19685. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.segmentsRadius );
  19686. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.segmentsRadius );
  19687. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19688. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19689. }
  19690. }
  19691. this.computeCentroids();
  19692. this.computeFaceNormals();
  19693. this.computeVertexNormals();
  19694. };
  19695. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19696. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19697. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19698. var
  19699. tangent = new THREE.Vector3(),
  19700. normal = new THREE.Vector3(),
  19701. binormal = new THREE.Vector3(),
  19702. tangents = [],
  19703. normals = [],
  19704. binormals = [],
  19705. vec = new THREE.Vector3(),
  19706. mat = new THREE.Matrix4(),
  19707. numpoints = segments + 1,
  19708. theta,
  19709. epsilon = 0.0001,
  19710. smallest,
  19711. tx, ty, tz,
  19712. i, u, v;
  19713. // expose internals
  19714. this.tangents = tangents;
  19715. this.normals = normals;
  19716. this.binormals = binormals;
  19717. // compute the tangent vectors for each segment on the path
  19718. for ( i = 0; i < numpoints; i++ ) {
  19719. u = i / ( numpoints - 1 );
  19720. tangents[ i ] = path.getTangentAt( u );
  19721. tangents[ i ].normalize();
  19722. }
  19723. initialNormal3();
  19724. function initialNormal1(lastBinormal) {
  19725. // fixed start binormal. Has dangers of 0 vectors
  19726. normals[ 0 ] = new THREE.Vector3();
  19727. binormals[ 0 ] = new THREE.Vector3();
  19728. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19729. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  19730. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  19731. }
  19732. function initialNormal2() {
  19733. // This uses the Frenet-Serret formula for deriving binormal
  19734. var t2 = path.getTangentAt( epsilon );
  19735. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  19736. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  19737. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19738. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  19739. }
  19740. function initialNormal3() {
  19741. // select an initial normal vector perpenicular to the first tangent vector,
  19742. // and in the direction of the smallest tangent xyz component
  19743. normals[ 0 ] = new THREE.Vector3();
  19744. binormals[ 0 ] = new THREE.Vector3();
  19745. smallest = Number.MAX_VALUE;
  19746. tx = Math.abs( tangents[ 0 ].x );
  19747. ty = Math.abs( tangents[ 0 ].y );
  19748. tz = Math.abs( tangents[ 0 ].z );
  19749. if ( tx <= smallest ) {
  19750. smallest = tx;
  19751. normal.set( 1, 0, 0 );
  19752. }
  19753. if ( ty <= smallest ) {
  19754. smallest = ty;
  19755. normal.set( 0, 1, 0 );
  19756. }
  19757. if ( tz <= smallest ) {
  19758. normal.set( 0, 0, 1 );
  19759. }
  19760. vec.cross( tangents[ 0 ], normal ).normalize();
  19761. normals[ 0 ].cross( tangents[ 0 ], vec );
  19762. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  19763. }
  19764. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19765. for ( i = 1; i < numpoints; i++ ) {
  19766. normals[ i ] = normals[ i-1 ].clone();
  19767. binormals[ i ] = binormals[ i-1 ].clone();
  19768. vec.cross( tangents[ i-1 ], tangents[ i ] );
  19769. if ( vec.length() > epsilon ) {
  19770. vec.normalize();
  19771. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19772. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  19773. }
  19774. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19775. }
  19776. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19777. if ( closed ) {
  19778. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19779. theta /= ( numpoints - 1 );
  19780. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19781. theta = -theta;
  19782. }
  19783. for ( i = 1; i < numpoints; i++ ) {
  19784. // twist a little...
  19785. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  19786. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19787. }
  19788. }
  19789. };
  19790. /**
  19791. * @author clockworkgeek / https://github.com/clockworkgeek
  19792. * @author timothypratley / https://github.com/timothypratley
  19793. */
  19794. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19795. THREE.Geometry.call( this );
  19796. radius = radius || 1;
  19797. detail = detail || 0;
  19798. var that = this;
  19799. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19800. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19801. }
  19802. var midpoints = [], p = this.vertices;
  19803. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19804. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19805. }
  19806. this.mergeVertices();
  19807. // Apply radius
  19808. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19809. this.vertices[ i ].multiplyScalar( radius );
  19810. }
  19811. // Project vector onto sphere's surface
  19812. function prepare( vector ) {
  19813. var vertex = vector.normalize().clone();
  19814. vertex.index = that.vertices.push( vertex ) - 1;
  19815. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19816. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19817. var v = inclination( vector ) / Math.PI + 0.5;
  19818. vertex.uv = new THREE.UV( u, 1 - v );
  19819. return vertex;
  19820. }
  19821. // Approximate a curved face with recursively sub-divided triangles.
  19822. function make( v1, v2, v3, detail ) {
  19823. if ( detail < 1 ) {
  19824. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19825. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  19826. face.normal = face.centroid.clone().normalize();
  19827. that.faces.push( face );
  19828. var azi = azimuth( face.centroid );
  19829. that.faceVertexUvs[ 0 ].push( [
  19830. correctUV( v1.uv, v1, azi ),
  19831. correctUV( v2.uv, v2, azi ),
  19832. correctUV( v3.uv, v3, azi )
  19833. ] );
  19834. } else {
  19835. detail -= 1;
  19836. // split triangle into 4 smaller triangles
  19837. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19838. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19839. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19840. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19841. }
  19842. }
  19843. function midpoint( v1, v2 ) {
  19844. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19845. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19846. var mid = midpoints[ v1.index ][ v2.index ];
  19847. if ( mid === undefined ) {
  19848. // generate mean point and project to surface with prepare()
  19849. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19850. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  19851. );
  19852. }
  19853. return mid;
  19854. }
  19855. // Angle around the Y axis, counter-clockwise when looking from above.
  19856. function azimuth( vector ) {
  19857. return Math.atan2( vector.z, -vector.x );
  19858. }
  19859. // Angle above the XZ plane.
  19860. function inclination( vector ) {
  19861. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19862. }
  19863. // Texture fixing helper. Spheres have some odd behaviours.
  19864. function correctUV( uv, vector, azimuth ) {
  19865. if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
  19866. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  19867. return uv;
  19868. }
  19869. this.computeCentroids();
  19870. this.boundingSphere = { radius: radius };
  19871. };
  19872. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19873. /**
  19874. * @author timothypratley / https://github.com/timothypratley
  19875. */
  19876. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19877. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19878. var vertices = [
  19879. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19880. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19881. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19882. ];
  19883. var faces = [
  19884. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19885. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19886. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19887. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19888. ];
  19889. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19890. };
  19891. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19892. /**
  19893. * @author timothypratley / https://github.com/timothypratley
  19894. */
  19895. THREE.OctahedronGeometry = function ( radius, detail ) {
  19896. var vertices = [
  19897. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19898. ];
  19899. var faces = [
  19900. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19901. ];
  19902. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19903. };
  19904. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19905. /**
  19906. * @author timothypratley / https://github.com/timothypratley
  19907. */
  19908. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19909. var vertices = [
  19910. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19911. ];
  19912. var faces = [
  19913. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19914. ];
  19915. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19916. };
  19917. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19918. /**
  19919. * @author zz85 / https://github.com/zz85
  19920. * Parametric Surfaces Geometry
  19921. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19922. *
  19923. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19924. *
  19925. */
  19926. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19927. THREE.Geometry.call( this );
  19928. var verts = this.vertices;
  19929. var faces = this.faces;
  19930. var uvs = this.faceVertexUvs[ 0 ];
  19931. useTris = (useTris === undefined) ? false : useTris;
  19932. var i, il, j, p;
  19933. var u, v;
  19934. var stackCount = stacks + 1;
  19935. var sliceCount = slices + 1;
  19936. for ( i = 0; i <= stacks; i ++ ) {
  19937. v = i / stacks;
  19938. for ( j = 0; j <= slices; j ++ ) {
  19939. u = j / slices;
  19940. p = func( u, v );
  19941. verts.push( p );
  19942. }
  19943. }
  19944. var a, b, c, d;
  19945. var uva, uvb, uvc, uvd;
  19946. for ( i = 0; i < stacks; i ++ ) {
  19947. for ( j = 0; j < slices; j ++ ) {
  19948. a = i * sliceCount + j;
  19949. b = i * sliceCount + j + 1;
  19950. c = (i + 1) * sliceCount + j;
  19951. d = (i + 1) * sliceCount + j + 1;
  19952. uva = new THREE.UV( j / slices, i / stacks );
  19953. uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
  19954. uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
  19955. uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19956. if ( useTris ) {
  19957. faces.push( new THREE.Face3( a, b, c ) );
  19958. faces.push( new THREE.Face3( b, d, c ) );
  19959. uvs.push( [ uva, uvb, uvc ] );
  19960. uvs.push( [ uvb, uvd, uvc ] );
  19961. } else {
  19962. faces.push( new THREE.Face4( a, b, d, c ) );
  19963. uvs.push( [ uva, uvb, uvd, uvc ] );
  19964. }
  19965. }
  19966. }
  19967. // console.log(this);
  19968. // magic bullet
  19969. // var diff = this.mergeVertices();
  19970. // console.log('removed ', diff, ' vertices by merging');
  19971. this.computeCentroids();
  19972. this.computeFaceNormals();
  19973. this.computeVertexNormals();
  19974. };
  19975. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19976. /**
  19977. * @author qiao / https://github.com/qiao
  19978. * @fileoverview This is a convex hull generator using the incremental method.
  19979. * The complexity is O(n^2) where n is the number of vertices.
  19980. * O(nlogn) algorithms do exist, but they are much more complicated.
  19981. *
  19982. * Benchmark:
  19983. *
  19984. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19985. *
  19986. * Num Vertices Time(ms)
  19987. *
  19988. * 10 1
  19989. * 20 3
  19990. * 30 19
  19991. * 40 48
  19992. * 50 107
  19993. */
  19994. THREE.ConvexGeometry = function( vertices ) {
  19995. THREE.Geometry.call( this );
  19996. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19997. for ( var i = 3; i < vertices.length; i++ ) {
  19998. addPoint( i );
  19999. }
  20000. function addPoint( vertexId ) {
  20001. var vertex = vertices[ vertexId ].clone();
  20002. var mag = vertex.length();
  20003. vertex.x += mag * randomOffset();
  20004. vertex.y += mag * randomOffset();
  20005. vertex.z += mag * randomOffset();
  20006. var hole = [];
  20007. for ( var f = 0; f < faces.length; ) {
  20008. var face = faces[ f ];
  20009. // for each face, if the vertex can see it,
  20010. // then we try to add the face's edges into the hole.
  20011. if ( visible( face, vertex ) ) {
  20012. for ( var e = 0; e < 3; e++ ) {
  20013. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  20014. var boundary = true;
  20015. // remove duplicated edges.
  20016. for ( var h = 0; h < hole.length; h++ ) {
  20017. if ( equalEdge( hole[ h ], edge ) ) {
  20018. hole[ h ] = hole[ hole.length - 1 ];
  20019. hole.pop();
  20020. boundary = false;
  20021. break;
  20022. }
  20023. }
  20024. if ( boundary ) {
  20025. hole.push( edge );
  20026. }
  20027. }
  20028. // remove faces[ f ]
  20029. faces[ f ] = faces[ faces.length - 1 ];
  20030. faces.pop();
  20031. } else { // not visible
  20032. f++;
  20033. }
  20034. }
  20035. // construct the new faces formed by the edges of the hole and the vertex
  20036. for ( var h = 0; h < hole.length; h++ ) {
  20037. faces.push( [
  20038. hole[ h ][ 0 ],
  20039. hole[ h ][ 1 ],
  20040. vertexId
  20041. ] );
  20042. }
  20043. }
  20044. /**
  20045. * Whether the face is visible from the vertex
  20046. */
  20047. function visible( face, vertex ) {
  20048. var va = vertices[ face[ 0 ] ];
  20049. var vb = vertices[ face[ 1 ] ];
  20050. var vc = vertices[ face[ 2 ] ];
  20051. var n = normal( va, vb, vc );
  20052. // distance from face to origin
  20053. var dist = n.dot( va );
  20054. return n.dot( vertex ) >= dist;
  20055. }
  20056. /**
  20057. * Face normal
  20058. */
  20059. function normal( va, vb, vc ) {
  20060. var cb = new THREE.Vector3();
  20061. var ab = new THREE.Vector3();
  20062. cb.sub( vc, vb );
  20063. ab.sub( va, vb );
  20064. cb.crossSelf( ab );
  20065. if ( !cb.isZero() ) {
  20066. cb.normalize();
  20067. }
  20068. return cb;
  20069. }
  20070. /**
  20071. * Detect whether two edges are equal.
  20072. * Note that when constructing the convex hull, two same edges can only
  20073. * be of the negative direction.
  20074. */
  20075. function equalEdge( ea, eb ) {
  20076. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20077. }
  20078. /**
  20079. * Create a random offset between -1e-6 and 1e-6.
  20080. */
  20081. function randomOffset() {
  20082. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20083. }
  20084. /**
  20085. * XXX: Not sure if this is the correct approach. Need someone to review.
  20086. */
  20087. function vertexUv( vertex ) {
  20088. var mag = vertex.length();
  20089. return new THREE.UV( vertex.x / mag, vertex.y / mag );
  20090. }
  20091. // Push vertices into `this.vertices`, skipping those inside the hull
  20092. var id = 0;
  20093. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20094. for ( var i = 0; i < faces.length; i++ ) {
  20095. var face = faces[ i ];
  20096. for ( var j = 0; j < 3; j++ ) {
  20097. if ( newId[ face[ j ] ] === undefined ) {
  20098. newId[ face[ j ] ] = id++;
  20099. this.vertices.push( vertices[ face[ j ] ] );
  20100. }
  20101. face[ j ] = newId[ face[ j ] ];
  20102. }
  20103. }
  20104. // Convert faces into instances of THREE.Face3
  20105. for ( var i = 0; i < faces.length; i++ ) {
  20106. this.faces.push( new THREE.Face3(
  20107. faces[ i ][ 0 ],
  20108. faces[ i ][ 1 ],
  20109. faces[ i ][ 2 ]
  20110. ) );
  20111. }
  20112. // Compute UVs
  20113. for ( var i = 0; i < this.faces.length; i++ ) {
  20114. var face = this.faces[ i ];
  20115. this.faceVertexUvs[ 0 ].push( [
  20116. vertexUv( this.vertices[ face.a ] ),
  20117. vertexUv( this.vertices[ face.b ] ),
  20118. vertexUv( this.vertices[ face.c ])
  20119. ] );
  20120. }
  20121. this.computeCentroids();
  20122. this.computeFaceNormals();
  20123. this.computeVertexNormals();
  20124. };
  20125. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20126. /**
  20127. * @author sroucheray / http://sroucheray.org/
  20128. * @author mrdoob / http://mrdoob.com/
  20129. */
  20130. THREE.AxisHelper = function ( size ) {
  20131. var geometry = new THREE.Geometry();
  20132. geometry.vertices.push(
  20133. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  20134. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  20135. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  20136. );
  20137. geometry.colors.push(
  20138. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20139. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20140. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20141. );
  20142. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20143. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20144. };
  20145. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20146. /**
  20147. * @author WestLangley / http://github.com/WestLangley
  20148. * @author zz85 / https://github.com/zz85
  20149. *
  20150. * Creates an arrow for visualizing directions
  20151. *
  20152. * Parameters:
  20153. * dir - Vector3
  20154. * origin - Vector3
  20155. * length - Number
  20156. * hex - color in hex value
  20157. */
  20158. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20159. THREE.Object3D.call( this );
  20160. if ( hex === undefined ) hex = 0xffff00;
  20161. if ( length === undefined ) length = 20;
  20162. var lineGeometry = new THREE.Geometry();
  20163. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20164. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20165. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20166. this.add( this.line );
  20167. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20168. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20169. this.cone.position.set( 0, 1, 0 );
  20170. this.add( this.cone );
  20171. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  20172. this.setDirection( dir );
  20173. this.setLength( length );
  20174. };
  20175. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20176. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  20177. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  20178. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  20179. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  20180. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  20181. };
  20182. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20183. this.scale.set( length, length, length );
  20184. };
  20185. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20186. this.line.material.color.setHex( hex );
  20187. this.cone.material.color.setHex( hex );
  20188. };
  20189. /**
  20190. * @author alteredq / http://alteredqualia.com/
  20191. *
  20192. * - shows frustum, line of sight and up of the camera
  20193. * - suitable for fast updates
  20194. * - based on frustum visualization in lightgl.js shadowmap example
  20195. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20196. */
  20197. THREE.CameraHelper = function ( camera ) {
  20198. THREE.Line.call( this );
  20199. var scope = this;
  20200. this.geometry = new THREE.Geometry();
  20201. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20202. this.type = THREE.LinePieces;
  20203. this.matrixWorld = camera.matrixWorld;
  20204. this.matrixAutoUpdate = false;
  20205. this.pointMap = {};
  20206. // colors
  20207. var hexFrustum = 0xffaa00;
  20208. var hexCone = 0xff0000;
  20209. var hexUp = 0x00aaff;
  20210. var hexTarget = 0xffffff;
  20211. var hexCross = 0x333333;
  20212. // near
  20213. addLine( "n1", "n2", hexFrustum );
  20214. addLine( "n2", "n4", hexFrustum );
  20215. addLine( "n4", "n3", hexFrustum );
  20216. addLine( "n3", "n1", hexFrustum );
  20217. // far
  20218. addLine( "f1", "f2", hexFrustum );
  20219. addLine( "f2", "f4", hexFrustum );
  20220. addLine( "f4", "f3", hexFrustum );
  20221. addLine( "f3", "f1", hexFrustum );
  20222. // sides
  20223. addLine( "n1", "f1", hexFrustum );
  20224. addLine( "n2", "f2", hexFrustum );
  20225. addLine( "n3", "f3", hexFrustum );
  20226. addLine( "n4", "f4", hexFrustum );
  20227. // cone
  20228. addLine( "p", "n1", hexCone );
  20229. addLine( "p", "n2", hexCone );
  20230. addLine( "p", "n3", hexCone );
  20231. addLine( "p", "n4", hexCone );
  20232. // up
  20233. addLine( "u1", "u2", hexUp );
  20234. addLine( "u2", "u3", hexUp );
  20235. addLine( "u3", "u1", hexUp );
  20236. // target
  20237. addLine( "c", "t", hexTarget );
  20238. addLine( "p", "c", hexCross );
  20239. // cross
  20240. addLine( "cn1", "cn2", hexCross );
  20241. addLine( "cn3", "cn4", hexCross );
  20242. addLine( "cf1", "cf2", hexCross );
  20243. addLine( "cf3", "cf4", hexCross );
  20244. this.camera = camera;
  20245. function addLine( a, b, hex ) {
  20246. addPoint( a, hex );
  20247. addPoint( b, hex );
  20248. }
  20249. function addPoint( id, hex ) {
  20250. scope.geometry.vertices.push( new THREE.Vector3() );
  20251. scope.geometry.colors.push( new THREE.Color( hex ) );
  20252. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  20253. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  20254. }
  20255. this.update( camera );
  20256. };
  20257. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20258. THREE.CameraHelper.prototype.update = function () {
  20259. var scope = this;
  20260. var w = 1, h = 1;
  20261. // we need just camera projection matrix
  20262. // world matrix must be identity
  20263. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  20264. // center / target
  20265. setPoint( "c", 0, 0, -1 );
  20266. setPoint( "t", 0, 0, 1 );
  20267. // near
  20268. setPoint( "n1", -w, -h, -1 );
  20269. setPoint( "n2", w, -h, -1 );
  20270. setPoint( "n3", -w, h, -1 );
  20271. setPoint( "n4", w, h, -1 );
  20272. // far
  20273. setPoint( "f1", -w, -h, 1 );
  20274. setPoint( "f2", w, -h, 1 );
  20275. setPoint( "f3", -w, h, 1 );
  20276. setPoint( "f4", w, h, 1 );
  20277. // up
  20278. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20279. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20280. setPoint( "u3", 0, h * 2, -1 );
  20281. // cross
  20282. setPoint( "cf1", -w, 0, 1 );
  20283. setPoint( "cf2", w, 0, 1 );
  20284. setPoint( "cf3", 0, -h, 1 );
  20285. setPoint( "cf4", 0, h, 1 );
  20286. setPoint( "cn1", -w, 0, -1 );
  20287. setPoint( "cn2", w, 0, -1 );
  20288. setPoint( "cn3", 0, -h, -1 );
  20289. setPoint( "cn4", 0, h, -1 );
  20290. function setPoint( point, x, y, z ) {
  20291. THREE.CameraHelper.__v.set( x, y, z );
  20292. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  20293. var points = scope.pointMap[ point ];
  20294. if ( points !== undefined ) {
  20295. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20296. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  20297. }
  20298. }
  20299. }
  20300. this.geometry.verticesNeedUpdate = true;
  20301. };
  20302. THREE.CameraHelper.__projector = new THREE.Projector();
  20303. THREE.CameraHelper.__v = new THREE.Vector3();
  20304. THREE.CameraHelper.__c = new THREE.Camera();
  20305. /*
  20306. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  20307. *
  20308. * Subdivision Geometry Modifier
  20309. * using Catmull-Clark Subdivision Surfaces
  20310. * for creating smooth geometry meshes
  20311. *
  20312. * Note: a modifier modifies vertices and faces of geometry,
  20313. * so use THREE.GeometryUtils.clone() if orignal geoemtry needs to be retained
  20314. *
  20315. * Readings:
  20316. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  20317. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  20318. * http://xrt.wikidot.com/blog:31
  20319. * "Subdivision Surfaces in Character Animation"
  20320. *
  20321. * (on boundary edges)
  20322. * http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  20323. * https://graphics.stanford.edu/wikis/cs148-09-summer/Assignment3Description
  20324. *
  20325. * Supports:
  20326. * Closed and Open geometries.
  20327. *
  20328. * TODO:
  20329. * crease vertex and "semi-sharp" features
  20330. * selective subdivision
  20331. */
  20332. THREE.SubdivisionModifier = function( subdivisions ) {
  20333. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  20334. // Settings
  20335. this.useOldVertexColors = false;
  20336. this.supportUVs = true;
  20337. this.debug = false;
  20338. };
  20339. // Applies the "modify" pattern
  20340. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  20341. var repeats = this.subdivisions;
  20342. while ( repeats-- > 0 ) {
  20343. this.smooth( geometry );
  20344. }
  20345. };
  20346. /// REFACTORING THIS OUT
  20347. function orderedKey( a, b ) {
  20348. return Math.min( a, b ) + "_" + Math.max( a, b );
  20349. }
  20350. var G = {
  20351. // Returns a hashmap - of { edge_key: face_index }
  20352. computeEdgeFaces: function ( geometry ) {
  20353. var i, il, v1, v2, j, k,
  20354. face, faceIndices, faceIndex,
  20355. edge,
  20356. hash,
  20357. edgeFaceMap = {};
  20358. function mapEdgeHash( hash, i ) {
  20359. if ( edgeFaceMap[ hash ] === undefined ) {
  20360. edgeFaceMap[ hash ] = [];
  20361. }
  20362. edgeFaceMap[ hash ].push( i );
  20363. }
  20364. // construct vertex -> face map
  20365. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  20366. face = geometry.faces[ i ];
  20367. if ( face instanceof THREE.Face3 ) {
  20368. hash = orderedKey( face.a, face.b );
  20369. mapEdgeHash( hash, i );
  20370. hash = orderedKey( face.b, face.c );
  20371. mapEdgeHash( hash, i );
  20372. hash = orderedKey( face.c, face.a );
  20373. mapEdgeHash( hash, i );
  20374. } else if ( face instanceof THREE.Face4 ) {
  20375. hash = orderedKey( face.a, face.b );
  20376. mapEdgeHash( hash, i );
  20377. hash = orderedKey( face.b, face.c );
  20378. mapEdgeHash( hash, i );
  20379. hash = orderedKey( face.c, face.d );
  20380. mapEdgeHash( hash, i );
  20381. hash = orderedKey( face.d, face.a );
  20382. mapEdgeHash( hash, i );
  20383. }
  20384. }
  20385. // extract faces
  20386. // var edges = [];
  20387. //
  20388. // var numOfEdges = 0;
  20389. // for (i in edgeFaceMap) {
  20390. // numOfEdges++;
  20391. //
  20392. // edge = edgeFaceMap[i];
  20393. // edges.push(edge);
  20394. //
  20395. // }
  20396. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  20397. return edgeFaceMap;
  20398. }
  20399. }
  20400. /////////////////////////////
  20401. // Performs an iteration of Catmull-Clark Subdivision
  20402. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  20403. //debug( 'running smooth' );
  20404. // New set of vertices, faces and uvs
  20405. var newVertices = [], newFaces = [], newUVs = [];
  20406. function v( x, y, z ) {
  20407. newVertices.push( new THREE.Vector3( x, y, z ) );
  20408. }
  20409. var scope = this;
  20410. function assert() {
  20411. if (scope.debug && console && console.assert) console.assert.apply(console, arguments);
  20412. }
  20413. function debug() {
  20414. if (scope.debug) console.log.apply(console, arguments);
  20415. }
  20416. function warn() {
  20417. if (console)
  20418. console.log.apply(console, arguments);
  20419. }
  20420. function f4( a, b, c, d, oldFace, orders, facei ) {
  20421. // TODO move vertex selection over here!
  20422. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  20423. if (scope.useOldVertexColors) {
  20424. newFace.vertexColors = [];
  20425. var color, tmpColor, order;
  20426. for (var i=0;i<4;i++) {
  20427. order = orders[i];
  20428. color = new THREE.Color(),
  20429. color.setRGB(0,0,0);
  20430. for (var j=0, jl=0; j<order.length;j++) {
  20431. tmpColor = oldFace.vertexColors[order[j]-1];
  20432. color.r += tmpColor.r;
  20433. color.g += tmpColor.g;
  20434. color.b += tmpColor.b;
  20435. }
  20436. color.r /= order.length;
  20437. color.g /= order.length;
  20438. color.b /= order.length;
  20439. newFace.vertexColors[i] = color;
  20440. }
  20441. }
  20442. newFaces.push( newFace );
  20443. if (scope.supportUVs) {
  20444. var aUv = [
  20445. getUV(a, ''),
  20446. getUV(b, facei),
  20447. getUV(c, facei),
  20448. getUV(d, facei)
  20449. ];
  20450. if (!aUv[0]) debug('a :( ', a+':'+facei);
  20451. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  20452. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  20453. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  20454. else
  20455. newUVs.push( aUv );
  20456. }
  20457. }
  20458. var originalPoints = oldGeometry.vertices;
  20459. var originalFaces = oldGeometry.faces;
  20460. var originalVerticesLength = originalPoints.length;
  20461. var newPoints = originalPoints.concat(); // New set of vertices to work on
  20462. var facePoints = [], // these are new points on exisiting faces
  20463. edgePoints = {}; // these are new points on exisiting edges
  20464. var sharpEdges = {}, sharpVertices = []; // Mark edges and vertices to prevent smoothening on them
  20465. // TODO: handle this correctly.
  20466. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  20467. function debugCoreStuff() {
  20468. console.log('facePoints', facePoints, 'edgePoints', edgePoints);
  20469. console.log('edgeFaceMap', edgeFaceMap, 'vertexEdgeMap', vertexEdgeMap);
  20470. }
  20471. function getUV(vertexNo, oldFaceNo) {
  20472. var j,jl;
  20473. var key = vertexNo+':'+oldFaceNo;
  20474. var theUV = uvForVertices[key];
  20475. if (!theUV) {
  20476. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  20477. debug('face pt');
  20478. } else {
  20479. debug('edge pt');
  20480. }
  20481. warn('warning, UV not found for', key);
  20482. return null;
  20483. }
  20484. return theUV;
  20485. // Original faces -> Vertex Nos.
  20486. // new Facepoint -> Vertex Nos.
  20487. // edge Points
  20488. }
  20489. function addUV(vertexNo, oldFaceNo, value) {
  20490. var key = vertexNo+':'+oldFaceNo;
  20491. if (!(key in uvForVertices)) {
  20492. uvForVertices[key] = value;
  20493. } else {
  20494. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  20495. }
  20496. }
  20497. // Step 1
  20498. // For each face, add a face point
  20499. // Set each face point to be the centroid of all original points for the respective face.
  20500. // debug(oldGeometry);
  20501. var i, il, j, jl, face;
  20502. // For Uvs
  20503. var uvs = oldGeometry.faceVertexUvs[0];
  20504. var abcd = 'abcd', vertice;
  20505. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  20506. if (scope.supportUVs)
  20507. for (i=0, il = uvs.length; i<il; i++ ) {
  20508. for (j=0,jl=uvs[i].length;j<jl;j++) {
  20509. vertice = originalFaces[i][abcd.charAt(j)];
  20510. addUV(vertice, i, uvs[i][j]);
  20511. }
  20512. }
  20513. if (uvs.length == 0) scope.supportUVs = false;
  20514. // Additional UVs check, if we index original
  20515. var uvCount = 0;
  20516. for (var u in uvForVertices) {
  20517. uvCount++;
  20518. }
  20519. if (!uvCount) {
  20520. scope.supportUVs = false;
  20521. debug('no uvs');
  20522. }
  20523. var avgUv ;
  20524. for (i=0, il = originalFaces.length; i<il ;i++) {
  20525. face = originalFaces[ i ];
  20526. facePoints.push( face.centroid );
  20527. newPoints.push( face.centroid );
  20528. if (!scope.supportUVs) continue;
  20529. // Prepare subdivided uv
  20530. avgUv = new THREE.UV();
  20531. if ( face instanceof THREE.Face3 ) {
  20532. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  20533. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  20534. avgUv.u /= 3;
  20535. avgUv.v /= 3;
  20536. } else if ( face instanceof THREE.Face4 ) {
  20537. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  20538. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  20539. avgUv.u /= 4;
  20540. avgUv.v /= 4;
  20541. }
  20542. addUV(originalVerticesLength + i, '', avgUv);
  20543. }
  20544. // Step 2
  20545. // For each edge, add an edge point.
  20546. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  20547. var edgeFaceMap = G.computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index eg { edge_key: [face_index, face_index2 ]}
  20548. var edge, faceIndexA, faceIndexB, avg;
  20549. // debug('edgeFaceMap', edgeFaceMap);
  20550. var edgeCount = 0;
  20551. var edgeVertex, edgeVertexA, edgeVertexB;
  20552. ////
  20553. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  20554. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  20555. function addVertexEdgeMap(vertex, edge) {
  20556. if (vertexEdgeMap[vertex]===undefined) {
  20557. vertexEdgeMap[vertex] = [];
  20558. }
  20559. vertexEdgeMap[vertex].push(edge);
  20560. }
  20561. function addVertexFaceMap(vertex, face, edge) {
  20562. if (vertexFaceMap[vertex]===undefined) {
  20563. vertexFaceMap[vertex] = {};
  20564. }
  20565. vertexFaceMap[vertex][face] = edge;
  20566. // vertexFaceMap[vertex][face] = null;
  20567. }
  20568. // Prepares vertexEdgeMap and vertexFaceMap
  20569. for (i in edgeFaceMap) { // This is for every edge
  20570. edge = edgeFaceMap[i];
  20571. edgeVertex = i.split('_');
  20572. edgeVertexA = edgeVertex[0];
  20573. edgeVertexB = edgeVertex[1];
  20574. // Maps an edgeVertex to connecting edges
  20575. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  20576. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  20577. for (j=0,jl=edge.length;j<jl;j++) {
  20578. face = edge[j];
  20579. addVertexFaceMap(edgeVertexA, face, i);
  20580. addVertexFaceMap(edgeVertexB, face, i);
  20581. }
  20582. // {edge vertex: { face1: edge_key, face2: edge_key.. } }
  20583. // this thing is fishy right now.
  20584. if (edge.length < 2) {
  20585. // edge is "sharp";
  20586. sharpEdges[i] = true;
  20587. sharpVertices[edgeVertexA] = true;
  20588. sharpVertices[edgeVertexB] = true;
  20589. }
  20590. }
  20591. for (i in edgeFaceMap) {
  20592. edge = edgeFaceMap[i];
  20593. faceIndexA = edge[0]; // face index a
  20594. faceIndexB = edge[1]; // face index b
  20595. edgeVertex = i.split('_');
  20596. edgeVertexA = edgeVertex[0];
  20597. edgeVertexB = edgeVertex[1];
  20598. avg = new THREE.Vector3();
  20599. //debug(i, faceIndexB,facePoints[faceIndexB]);
  20600. assert(edge.length > 0, 'an edge without faces?!');
  20601. if (edge.length==1) {
  20602. avg.addSelf(originalPoints[edgeVertexA]);
  20603. avg.addSelf(originalPoints[edgeVertexB]);
  20604. avg.multiplyScalar(0.5);
  20605. sharpVertices[newPoints.length] = true;
  20606. } else {
  20607. avg.addSelf(facePoints[faceIndexA]);
  20608. avg.addSelf(facePoints[faceIndexB]);
  20609. avg.addSelf(originalPoints[edgeVertexA]);
  20610. avg.addSelf(originalPoints[edgeVertexB]);
  20611. avg.multiplyScalar(0.25);
  20612. }
  20613. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  20614. newPoints.push( avg );
  20615. edgeCount ++;
  20616. if (!scope.supportUVs) {
  20617. continue;
  20618. }
  20619. // Prepare subdivided uv
  20620. avgUv = new THREE.UV();
  20621. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  20622. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  20623. avgUv.u /= 2;
  20624. avgUv.v /= 2;
  20625. addUV(edgePoints[i], faceIndexA, avgUv);
  20626. if (edge.length>=2) {
  20627. assert(edge.length == 2, 'did we plan for more than 2 edges?');
  20628. avgUv = new THREE.UV();
  20629. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  20630. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  20631. avgUv.u /= 2;
  20632. avgUv.v /= 2;
  20633. addUV(edgePoints[i], faceIndexB, avgUv);
  20634. }
  20635. }
  20636. debug('-- Step 2 done');
  20637. // Step 3
  20638. // For each face point, add an edge for every edge of the face,
  20639. // connecting the face point to each edge point for the face.
  20640. debugCoreStuff();
  20641. var facePt, currentVerticeIndex;
  20642. var hashAB, hashBC, hashCD, hashDA, hashCA;
  20643. var abc123 = ['123', '12', '2', '23'];
  20644. var bca123 = ['123', '23', '3', '31'];
  20645. var cab123 = ['123', '31', '1', '12'];
  20646. var abc1234 = ['1234', '12', '2', '23'];
  20647. var bcd1234 = ['1234', '23', '3', '34'];
  20648. var cda1234 = ['1234', '34', '4', '41'];
  20649. var dab1234 = ['1234', '41', '1', '12'];
  20650. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  20651. facePt = facePoints[i];
  20652. face = originalFaces[i];
  20653. currentVerticeIndex = originalVerticesLength+ i;
  20654. if ( face instanceof THREE.Face3 ) {
  20655. // create 3 face4s
  20656. hashAB = orderedKey( face.a, face.b );
  20657. hashBC = orderedKey( face.b, face.c );
  20658. hashCA = orderedKey( face.c, face.a );
  20659. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  20660. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  20661. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  20662. } else if ( face instanceof THREE.Face4 ) {
  20663. // create 4 face4s
  20664. hashAB = orderedKey( face.a, face.b );
  20665. hashBC = orderedKey( face.b, face.c );
  20666. hashCD = orderedKey( face.c, face.d );
  20667. hashDA = orderedKey( face.d, face.a );
  20668. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  20669. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  20670. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  20671. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  20672. } else {
  20673. debug('face should be a face!', face);
  20674. }
  20675. }
  20676. newVertices = newPoints;
  20677. // Step 4
  20678. // For each original point P,
  20679. // take the average F of all n face points for faces touching P,
  20680. // and take the average R of all n edge midpoints for edges touching P,
  20681. // where each edge midpoint is the average of its two endpoint vertices.
  20682. // Move each original point to the point
  20683. var F = new THREE.Vector3();
  20684. var R = new THREE.Vector3();
  20685. var n;
  20686. for (i=0, il = originalPoints.length; i<il; i++) {
  20687. // (F + 2R + (n-3)P) / n
  20688. if (vertexEdgeMap[i]===undefined) continue;
  20689. F.set(0,0,0);
  20690. R.set(0,0,0);
  20691. var newPos = new THREE.Vector3(0,0,0);
  20692. var f = 0; // this counts number of faces, original vertex is connected to (also known as valance?)
  20693. for (j in vertexFaceMap[i]) {
  20694. F.addSelf(facePoints[j]);
  20695. f++;
  20696. }
  20697. var sharpEdgeCount = 0;
  20698. n = vertexEdgeMap[i].length; // given a vertex, return its connecting edges
  20699. // Are we on the border?
  20700. var boundary_case = f != n;
  20701. // if (boundary_case) {
  20702. // console.error('moo', 'o', i, 'faces touched', f, 'edges', n, n == 2);
  20703. // }
  20704. for (j=0;j<n;j++) {
  20705. if (
  20706. sharpEdges[
  20707. orderedKey(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  20708. ]) {
  20709. sharpEdgeCount++;
  20710. }
  20711. }
  20712. // if ( sharpEdgeCount==2 ) {
  20713. // continue;
  20714. // // Do not move vertex if there's 2 connecting sharp edges.
  20715. // }
  20716. /*
  20717. if (sharpEdgeCount>2) {
  20718. // TODO
  20719. }
  20720. */
  20721. F.divideScalar(f);
  20722. var boundary_edges = 0;
  20723. if (boundary_case) {
  20724. var bb_edge;
  20725. for (j=0; j<n;j++) {
  20726. edge = vertexEdgeMap[i][j];
  20727. bb_edge = edgeFaceMap[orderedKey(edge[0], edge[1])].length == 1
  20728. if (bb_edge) {
  20729. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20730. R.addSelf(midPt);
  20731. boundary_edges++;
  20732. }
  20733. }
  20734. R.divideScalar(4);
  20735. // console.log(j + ' --- ' + n + ' --- ' + boundary_edges);
  20736. assert(boundary_edges == 2, 'should have only 2 boundary edges');
  20737. } else {
  20738. for (j=0; j<n;j++) {
  20739. edge = vertexEdgeMap[i][j];
  20740. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20741. R.addSelf(midPt);
  20742. }
  20743. R.divideScalar(n);
  20744. }
  20745. // Sum the formula
  20746. newPos.addSelf(originalPoints[i]);
  20747. if (boundary_case) {
  20748. newPos.divideScalar(2);
  20749. newPos.addSelf(R);
  20750. } else {
  20751. newPos.multiplyScalar(n - 3);
  20752. newPos.addSelf(F);
  20753. newPos.addSelf(R.multiplyScalar(2));
  20754. newPos.divideScalar(n);
  20755. }
  20756. newVertices[i] = newPos;
  20757. }
  20758. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  20759. newGeometry.vertices = newVertices;
  20760. newGeometry.faces = newFaces;
  20761. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  20762. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  20763. newGeometry.computeCentroids();
  20764. newGeometry.computeFaceNormals();
  20765. newGeometry.computeVertexNormals();
  20766. };/**
  20767. * @author alteredq / http://alteredqualia.com/
  20768. */
  20769. THREE.ImmediateRenderObject = function ( ) {
  20770. THREE.Object3D.call( this );
  20771. this.render = function ( renderCallback ) { };
  20772. };
  20773. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20774. /**
  20775. * @author mikael emtinger / http://gomo.se/
  20776. * @author alteredq / http://alteredqualia.com/
  20777. */
  20778. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20779. THREE.Object3D.call( this );
  20780. this.lensFlares = [];
  20781. this.positionScreen = new THREE.Vector3();
  20782. this.customUpdateCallback = undefined;
  20783. if( texture !== undefined ) {
  20784. this.add( texture, size, distance, blending, color );
  20785. }
  20786. };
  20787. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20788. /*
  20789. * Add: adds another flare
  20790. */
  20791. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20792. if( size === undefined ) size = -1;
  20793. if( distance === undefined ) distance = 0;
  20794. if( opacity === undefined ) opacity = 1;
  20795. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20796. if( blending === undefined ) blending = THREE.NormalBlending;
  20797. distance = Math.min( distance, Math.max( 0, distance ) );
  20798. this.lensFlares.push( { texture: texture, // THREE.Texture
  20799. size: size, // size in pixels (-1 = use texture.width)
  20800. distance: distance, // distance (0-1) from light source (0=at light source)
  20801. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20802. scale: 1, // scale
  20803. rotation: 1, // rotation
  20804. opacity: opacity, // opacity
  20805. color: color, // color
  20806. blending: blending } ); // blending
  20807. };
  20808. /*
  20809. * Update lens flares update positions on all flares based on the screen position
  20810. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20811. */
  20812. THREE.LensFlare.prototype.updateLensFlares = function () {
  20813. var f, fl = this.lensFlares.length;
  20814. var flare;
  20815. var vecX = -this.positionScreen.x * 2;
  20816. var vecY = -this.positionScreen.y * 2;
  20817. for( f = 0; f < fl; f ++ ) {
  20818. flare = this.lensFlares[ f ];
  20819. flare.x = this.positionScreen.x + vecX * flare.distance;
  20820. flare.y = this.positionScreen.y + vecY * flare.distance;
  20821. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20822. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20823. }
  20824. };
  20825. /**
  20826. * @author alteredq / http://alteredqualia.com/
  20827. */
  20828. THREE.MorphBlendMesh = function( geometry, material ) {
  20829. THREE.Mesh.call( this, geometry, material );
  20830. this.animationsMap = {};
  20831. this.animationsList = [];
  20832. // prepare default animation
  20833. // (all frames played together in 1 second)
  20834. var numFrames = this.geometry.morphTargets.length;
  20835. var name = "__default";
  20836. var startFrame = 0;
  20837. var endFrame = numFrames - 1;
  20838. var fps = numFrames / 1;
  20839. this.createAnimation( name, startFrame, endFrame, fps );
  20840. this.setAnimationWeight( name, 1 );
  20841. };
  20842. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20843. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20844. var animation = {
  20845. startFrame: start,
  20846. endFrame: end,
  20847. length: end - start + 1,
  20848. fps: fps,
  20849. duration: ( end - start ) / fps,
  20850. lastFrame: 0,
  20851. currentFrame: 0,
  20852. active: false,
  20853. time: 0,
  20854. direction: 1,
  20855. weight: 1,
  20856. directionBackwards: false,
  20857. mirroredLoop: false
  20858. };
  20859. this.animationsMap[ name ] = animation;
  20860. this.animationsList.push( animation );
  20861. };
  20862. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20863. var pattern = /([a-z]+)(\d+)/;
  20864. var firstAnimation, frameRanges = {};
  20865. var geometry = this.geometry;
  20866. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20867. var morph = geometry.morphTargets[ i ];
  20868. var chunks = morph.name.match( pattern );
  20869. if ( chunks && chunks.length > 1 ) {
  20870. var name = chunks[ 1 ];
  20871. var num = chunks[ 2 ];
  20872. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20873. var range = frameRanges[ name ];
  20874. if ( i < range.start ) range.start = i;
  20875. if ( i > range.end ) range.end = i;
  20876. if ( ! firstAnimation ) firstAnimation = name;
  20877. }
  20878. }
  20879. for ( var name in frameRanges ) {
  20880. var range = frameRanges[ name ];
  20881. this.createAnimation( name, range.start, range.end, fps );
  20882. }
  20883. this.firstAnimation = firstAnimation;
  20884. };
  20885. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20886. var animation = this.animationsMap[ name ];
  20887. if ( animation ) {
  20888. animation.direction = 1;
  20889. animation.directionBackwards = false;
  20890. }
  20891. };
  20892. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20893. var animation = this.animationsMap[ name ];
  20894. if ( animation ) {
  20895. animation.direction = -1;
  20896. animation.directionBackwards = true;
  20897. }
  20898. };
  20899. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20900. var animation = this.animationsMap[ name ];
  20901. if ( animation ) {
  20902. animation.fps = fps;
  20903. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20904. }
  20905. };
  20906. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20907. var animation = this.animationsMap[ name ];
  20908. if ( animation ) {
  20909. animation.duration = duration;
  20910. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20911. }
  20912. };
  20913. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20914. var animation = this.animationsMap[ name ];
  20915. if ( animation ) {
  20916. animation.weight = weight;
  20917. }
  20918. };
  20919. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20920. var animation = this.animationsMap[ name ];
  20921. if ( animation ) {
  20922. animation.time = time;
  20923. }
  20924. };
  20925. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20926. var time = 0;
  20927. var animation = this.animationsMap[ name ];
  20928. if ( animation ) {
  20929. time = animation.time;
  20930. }
  20931. return time;
  20932. };
  20933. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20934. var duration = -1;
  20935. var animation = this.animationsMap[ name ];
  20936. if ( animation ) {
  20937. duration = animation.duration;
  20938. }
  20939. return duration;
  20940. };
  20941. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20942. var animation = this.animationsMap[ name ];
  20943. if ( animation ) {
  20944. animation.time = 0;
  20945. animation.active = true;
  20946. } else {
  20947. console.warn( "animation[" + name + "] undefined" );
  20948. }
  20949. };
  20950. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20951. var animation = this.animationsMap[ name ];
  20952. if ( animation ) {
  20953. animation.active = false;
  20954. }
  20955. };
  20956. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20957. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20958. var animation = this.animationsList[ i ];
  20959. if ( ! animation.active ) continue;
  20960. var frameTime = animation.duration / animation.length;
  20961. animation.time += animation.direction * delta;
  20962. if ( animation.mirroredLoop ) {
  20963. if ( animation.time > animation.duration || animation.time < 0 ) {
  20964. animation.direction *= -1;
  20965. if ( animation.time > animation.duration ) {
  20966. animation.time = animation.duration;
  20967. animation.directionBackwards = true;
  20968. }
  20969. if ( animation.time < 0 ) {
  20970. animation.time = 0;
  20971. animation.directionBackwards = false;
  20972. }
  20973. }
  20974. } else {
  20975. animation.time = animation.time % animation.duration;
  20976. if ( animation.time < 0 ) animation.time += animation.duration;
  20977. }
  20978. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20979. var weight = animation.weight;
  20980. if ( keyframe !== animation.currentFrame ) {
  20981. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20982. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20983. this.morphTargetInfluences[ keyframe ] = 0;
  20984. animation.lastFrame = animation.currentFrame;
  20985. animation.currentFrame = keyframe;
  20986. }
  20987. var mix = ( animation.time % frameTime ) / frameTime;
  20988. if ( animation.directionBackwards ) mix = 1 - mix;
  20989. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20990. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20991. }
  20992. };
  20993. /**
  20994. * @author mikael emtinger / http://gomo.se/
  20995. * @author alteredq / http://alteredqualia.com/
  20996. */
  20997. THREE.LensFlarePlugin = function ( ) {
  20998. var _gl, _renderer, _lensFlare = {};
  20999. this.init = function ( renderer ) {
  21000. _gl = renderer.context;
  21001. _renderer = renderer;
  21002. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21003. _lensFlare.faces = new Uint16Array( 6 );
  21004. var i = 0;
  21005. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21006. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21007. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21008. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21009. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21010. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21011. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21012. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21013. i = 0;
  21014. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21015. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21016. // buffers
  21017. _lensFlare.vertexBuffer = _gl.createBuffer();
  21018. _lensFlare.elementBuffer = _gl.createBuffer();
  21019. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21020. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21021. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21022. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21023. // textures
  21024. _lensFlare.tempTexture = _gl.createTexture();
  21025. _lensFlare.occlusionTexture = _gl.createTexture();
  21026. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21027. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21028. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21029. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21030. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21031. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21032. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21033. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21034. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21035. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21036. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21037. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21038. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21039. _lensFlare.hasVertexTexture = false;
  21040. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  21041. } else {
  21042. _lensFlare.hasVertexTexture = true;
  21043. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  21044. }
  21045. _lensFlare.attributes = {};
  21046. _lensFlare.uniforms = {};
  21047. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21048. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21049. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21050. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21051. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21052. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21053. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21054. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21055. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21056. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21057. _lensFlare.attributesEnabled = false;
  21058. };
  21059. /*
  21060. * Render lens flares
  21061. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21062. * reads these back and calculates occlusion.
  21063. * Then _lensFlare.update_lensFlares() is called to re-position and
  21064. * update transparency of flares. Then they are rendered.
  21065. *
  21066. */
  21067. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21068. var flares = scene.__webglFlares,
  21069. nFlares = flares.length;
  21070. if ( ! nFlares ) return;
  21071. var tempPosition = new THREE.Vector3();
  21072. var invAspect = viewportHeight / viewportWidth,
  21073. halfViewportWidth = viewportWidth * 0.5,
  21074. halfViewportHeight = viewportHeight * 0.5;
  21075. var size = 16 / viewportHeight,
  21076. scale = new THREE.Vector2( size * invAspect, size );
  21077. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21078. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21079. var uniforms = _lensFlare.uniforms,
  21080. attributes = _lensFlare.attributes;
  21081. // set _lensFlare program and reset blending
  21082. _gl.useProgram( _lensFlare.program );
  21083. if ( ! _lensFlare.attributesEnabled ) {
  21084. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21085. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21086. _lensFlare.attributesEnabled = true;
  21087. }
  21088. // loop through all lens flares to update their occlusion and positions
  21089. // setup gl and common used attribs/unforms
  21090. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21091. _gl.uniform1i( uniforms.map, 1 );
  21092. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21093. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21094. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21095. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21096. _gl.disable( _gl.CULL_FACE );
  21097. _gl.depthMask( false );
  21098. var i, j, jl, flare, sprite;
  21099. for ( i = 0; i < nFlares; i ++ ) {
  21100. size = 16 / viewportHeight;
  21101. scale.set( size * invAspect, size );
  21102. // calc object screen position
  21103. flare = flares[ i ];
  21104. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21105. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  21106. camera.projectionMatrix.multiplyVector3( tempPosition );
  21107. // setup arrays for gl programs
  21108. screenPosition.copy( tempPosition )
  21109. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21110. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21111. // screen cull
  21112. if ( _lensFlare.hasVertexTexture || (
  21113. screenPositionPixels.x > 0 &&
  21114. screenPositionPixels.x < viewportWidth &&
  21115. screenPositionPixels.y > 0 &&
  21116. screenPositionPixels.y < viewportHeight ) ) {
  21117. // save current RGB to temp texture
  21118. _gl.activeTexture( _gl.TEXTURE1 );
  21119. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21120. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21121. // render pink quad
  21122. _gl.uniform1i( uniforms.renderType, 0 );
  21123. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21124. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21125. _gl.disable( _gl.BLEND );
  21126. _gl.enable( _gl.DEPTH_TEST );
  21127. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21128. // copy result to occlusionMap
  21129. _gl.activeTexture( _gl.TEXTURE0 );
  21130. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21131. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21132. // restore graphics
  21133. _gl.uniform1i( uniforms.renderType, 1 );
  21134. _gl.disable( _gl.DEPTH_TEST );
  21135. _gl.activeTexture( _gl.TEXTURE1 );
  21136. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21137. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21138. // update object positions
  21139. flare.positionScreen.copy( screenPosition )
  21140. if ( flare.customUpdateCallback ) {
  21141. flare.customUpdateCallback( flare );
  21142. } else {
  21143. flare.updateLensFlares();
  21144. }
  21145. // render flares
  21146. _gl.uniform1i( uniforms.renderType, 2 );
  21147. _gl.enable( _gl.BLEND );
  21148. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21149. sprite = flare.lensFlares[ j ];
  21150. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21151. screenPosition.x = sprite.x;
  21152. screenPosition.y = sprite.y;
  21153. screenPosition.z = sprite.z;
  21154. size = sprite.size * sprite.scale / viewportHeight;
  21155. scale.x = size * invAspect;
  21156. scale.y = size;
  21157. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21158. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21159. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21160. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21161. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21162. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21163. _renderer.setTexture( sprite.texture, 1 );
  21164. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21165. }
  21166. }
  21167. }
  21168. }
  21169. // restore gl
  21170. _gl.enable( _gl.CULL_FACE );
  21171. _gl.enable( _gl.DEPTH_TEST );
  21172. _gl.depthMask( true );
  21173. };
  21174. function createProgram ( shader ) {
  21175. var program = _gl.createProgram();
  21176. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21177. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21178. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21179. _gl.shaderSource( vertexShader, shader.vertexShader );
  21180. _gl.compileShader( fragmentShader );
  21181. _gl.compileShader( vertexShader );
  21182. _gl.attachShader( program, fragmentShader );
  21183. _gl.attachShader( program, vertexShader );
  21184. _gl.linkProgram( program );
  21185. return program;
  21186. };
  21187. };/**
  21188. * @author alteredq / http://alteredqualia.com/
  21189. */
  21190. THREE.ShadowMapPlugin = function ( ) {
  21191. var _gl,
  21192. _renderer,
  21193. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21194. _frustum = new THREE.Frustum(),
  21195. _projScreenMatrix = new THREE.Matrix4(),
  21196. _min = new THREE.Vector3(),
  21197. _max = new THREE.Vector3();
  21198. this.init = function ( renderer ) {
  21199. _gl = renderer.context;
  21200. _renderer = renderer;
  21201. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21202. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21203. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21204. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21205. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21206. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21207. _depthMaterial._shadowPass = true;
  21208. _depthMaterialMorph._shadowPass = true;
  21209. _depthMaterialSkin._shadowPass = true;
  21210. _depthMaterialMorphSkin._shadowPass = true;
  21211. };
  21212. this.render = function ( scene, camera ) {
  21213. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21214. this.update( scene, camera );
  21215. };
  21216. this.update = function ( scene, camera ) {
  21217. var i, il, j, jl, n,
  21218. shadowMap, shadowMatrix, shadowCamera,
  21219. program, buffer, material,
  21220. webglObject, object, light,
  21221. renderList,
  21222. lights = [],
  21223. k = 0,
  21224. fog = null;
  21225. // set GL state for depth map
  21226. _gl.clearColor( 1, 1, 1, 1 );
  21227. _gl.disable( _gl.BLEND );
  21228. _gl.enable( _gl.CULL_FACE );
  21229. _gl.frontFace( _gl.CCW );
  21230. if ( _renderer.shadowMapCullFrontFaces ) {
  21231. _gl.cullFace( _gl.FRONT );
  21232. } else {
  21233. _gl.cullFace( _gl.BACK );
  21234. }
  21235. _renderer.setDepthTest( true );
  21236. // preprocess lights
  21237. // - skip lights that are not casting shadows
  21238. // - create virtual lights for cascaded shadow maps
  21239. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21240. light = scene.__lights[ i ];
  21241. if ( ! light.castShadow ) continue;
  21242. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21243. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21244. var virtualLight;
  21245. if ( ! light.shadowCascadeArray[ n ] ) {
  21246. virtualLight = createVirtualLight( light, n );
  21247. virtualLight.originalCamera = camera;
  21248. var gyro = new THREE.Gyroscope();
  21249. gyro.position = light.shadowCascadeOffset;
  21250. gyro.add( virtualLight );
  21251. gyro.add( virtualLight.target );
  21252. camera.add( gyro );
  21253. light.shadowCascadeArray[ n ] = virtualLight;
  21254. console.log( "Created virtualLight", virtualLight );
  21255. } else {
  21256. virtualLight = light.shadowCascadeArray[ n ];
  21257. }
  21258. updateVirtualLight( light, n );
  21259. lights[ k ] = virtualLight;
  21260. k ++;
  21261. }
  21262. } else {
  21263. lights[ k ] = light;
  21264. k ++;
  21265. }
  21266. }
  21267. // render depth map
  21268. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21269. light = lights[ i ];
  21270. if ( ! light.shadowMap ) {
  21271. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  21272. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21273. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21274. light.shadowMatrix = new THREE.Matrix4();
  21275. }
  21276. if ( ! light.shadowCamera ) {
  21277. if ( light instanceof THREE.SpotLight ) {
  21278. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21279. } else if ( light instanceof THREE.DirectionalLight ) {
  21280. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21281. } else {
  21282. console.error( "Unsupported light type for shadow" );
  21283. continue;
  21284. }
  21285. scene.add( light.shadowCamera );
  21286. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21287. }
  21288. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21289. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21290. light.shadowCamera.add( light.cameraHelper );
  21291. }
  21292. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21293. updateShadowCamera( camera, light );
  21294. }
  21295. shadowMap = light.shadowMap;
  21296. shadowMatrix = light.shadowMatrix;
  21297. shadowCamera = light.shadowCamera;
  21298. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  21299. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  21300. shadowCamera.updateMatrixWorld();
  21301. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21302. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21303. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21304. // compute shadow matrix
  21305. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21306. 0.0, 0.5, 0.0, 0.5,
  21307. 0.0, 0.0, 0.5, 0.5,
  21308. 0.0, 0.0, 0.0, 1.0 );
  21309. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  21310. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  21311. // update camera matrices and frustum
  21312. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  21313. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  21314. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  21315. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  21316. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21317. _frustum.setFromMatrix( _projScreenMatrix );
  21318. // render shadow map
  21319. _renderer.setRenderTarget( shadowMap );
  21320. _renderer.clear();
  21321. // set object matrices & frustum culling
  21322. renderList = scene.__webglObjects;
  21323. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21324. webglObject = renderList[ j ];
  21325. object = webglObject.object;
  21326. webglObject.render = false;
  21327. if ( object.visible && object.castShadow ) {
  21328. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21329. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21330. webglObject.render = true;
  21331. }
  21332. }
  21333. }
  21334. // render regular objects
  21335. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21336. webglObject = renderList[ j ];
  21337. if ( webglObject.render ) {
  21338. object = webglObject.object;
  21339. buffer = webglObject.buffer;
  21340. // culling is overriden globally for all objects
  21341. // while rendering depth map
  21342. if ( object.customDepthMaterial ) {
  21343. material = object.customDepthMaterial;
  21344. } else if ( object instanceof THREE.SkinnedMesh ) {
  21345. material = object.geometry.morphTargets.length ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21346. } else if ( object.geometry.morphTargets.length ) {
  21347. material = _depthMaterialMorph;
  21348. } else {
  21349. material = _depthMaterial;
  21350. }
  21351. if ( buffer instanceof THREE.BufferGeometry ) {
  21352. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21353. } else {
  21354. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21355. }
  21356. }
  21357. }
  21358. // set matrices and render immediate objects
  21359. renderList = scene.__webglObjectsImmediate;
  21360. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21361. webglObject = renderList[ j ];
  21362. object = webglObject.object;
  21363. if ( object.visible && object.castShadow ) {
  21364. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21365. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21366. }
  21367. }
  21368. }
  21369. // restore GL state
  21370. var clearColor = _renderer.getClearColor(),
  21371. clearAlpha = _renderer.getClearAlpha();
  21372. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21373. _gl.enable( _gl.BLEND );
  21374. if ( _renderer.shadowMapCullFrontFaces ) {
  21375. _gl.cullFace( _gl.BACK );
  21376. }
  21377. };
  21378. function createVirtualLight( light, cascade ) {
  21379. var virtualLight = new THREE.DirectionalLight();
  21380. virtualLight.isVirtual = true;
  21381. virtualLight.onlyShadow = true;
  21382. virtualLight.castShadow = true;
  21383. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21384. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21385. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21386. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21387. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21388. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21389. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21390. virtualLight.shadowDarkness = light.shadowDarkness;
  21391. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21392. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21393. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21394. virtualLight.pointsWorld = [];
  21395. virtualLight.pointsFrustum = [];
  21396. var pointsWorld = virtualLight.pointsWorld,
  21397. pointsFrustum = virtualLight.pointsFrustum;
  21398. for ( var i = 0; i < 8; i ++ ) {
  21399. pointsWorld[ i ] = new THREE.Vector3();
  21400. pointsFrustum[ i ] = new THREE.Vector3();
  21401. }
  21402. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21403. var farZ = light.shadowCascadeFarZ[ cascade ];
  21404. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21405. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21406. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21407. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21408. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21409. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21410. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21411. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21412. return virtualLight;
  21413. }
  21414. // Synchronize virtual light with the original light
  21415. function updateVirtualLight( light, cascade ) {
  21416. var virtualLight = light.shadowCascadeArray[ cascade ];
  21417. virtualLight.position.copy( light.position );
  21418. virtualLight.target.position.copy( light.target.position );
  21419. virtualLight.lookAt( virtualLight.target );
  21420. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21421. virtualLight.shadowDarkness = light.shadowDarkness;
  21422. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21423. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21424. var farZ = light.shadowCascadeFarZ[ cascade ];
  21425. var pointsFrustum = virtualLight.pointsFrustum;
  21426. pointsFrustum[ 0 ].z = nearZ;
  21427. pointsFrustum[ 1 ].z = nearZ;
  21428. pointsFrustum[ 2 ].z = nearZ;
  21429. pointsFrustum[ 3 ].z = nearZ;
  21430. pointsFrustum[ 4 ].z = farZ;
  21431. pointsFrustum[ 5 ].z = farZ;
  21432. pointsFrustum[ 6 ].z = farZ;
  21433. pointsFrustum[ 7 ].z = farZ;
  21434. }
  21435. // Fit shadow camera's ortho frustum to camera frustum
  21436. function updateShadowCamera( camera, light ) {
  21437. var shadowCamera = light.shadowCamera,
  21438. pointsFrustum = light.pointsFrustum,
  21439. pointsWorld = light.pointsWorld;
  21440. _min.set( Infinity, Infinity, Infinity );
  21441. _max.set( -Infinity, -Infinity, -Infinity );
  21442. for ( var i = 0; i < 8; i ++ ) {
  21443. var p = pointsWorld[ i ];
  21444. p.copy( pointsFrustum[ i ] );
  21445. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21446. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  21447. if ( p.x < _min.x ) _min.x = p.x;
  21448. if ( p.x > _max.x ) _max.x = p.x;
  21449. if ( p.y < _min.y ) _min.y = p.y;
  21450. if ( p.y > _max.y ) _max.y = p.y;
  21451. if ( p.z < _min.z ) _min.z = p.z;
  21452. if ( p.z > _max.z ) _max.z = p.z;
  21453. }
  21454. shadowCamera.left = _min.x;
  21455. shadowCamera.right = _max.x;
  21456. shadowCamera.top = _max.y;
  21457. shadowCamera.bottom = _min.y;
  21458. // can't really fit near/far
  21459. //shadowCamera.near = _min.z;
  21460. //shadowCamera.far = _max.z;
  21461. shadowCamera.updateProjectionMatrix();
  21462. }
  21463. };
  21464. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21465. /**
  21466. * @author mikael emtinger / http://gomo.se/
  21467. * @author alteredq / http://alteredqualia.com/
  21468. */
  21469. THREE.SpritePlugin = function ( ) {
  21470. var _gl, _renderer, _sprite = {};
  21471. this.init = function ( renderer ) {
  21472. _gl = renderer.context;
  21473. _renderer = renderer;
  21474. _sprite.vertices = new Float32Array( 8 + 8 );
  21475. _sprite.faces = new Uint16Array( 6 );
  21476. var i = 0;
  21477. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21478. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21479. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21480. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21481. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21482. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21483. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21484. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21485. i = 0;
  21486. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21487. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21488. _sprite.vertexBuffer = _gl.createBuffer();
  21489. _sprite.elementBuffer = _gl.createBuffer();
  21490. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21491. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21492. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21493. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21494. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  21495. _sprite.attributes = {};
  21496. _sprite.uniforms = {};
  21497. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21498. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21499. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21500. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21501. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21502. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21503. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21504. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21505. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21506. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21507. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21508. _sprite.uniforms.affectedByDistance = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
  21509. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21510. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21511. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21512. _sprite.attributesEnabled = false;
  21513. };
  21514. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21515. var sprites = scene.__webglSprites,
  21516. nSprites = sprites.length;
  21517. if ( ! nSprites ) return;
  21518. var attributes = _sprite.attributes,
  21519. uniforms = _sprite.uniforms;
  21520. var invAspect = viewportHeight / viewportWidth;
  21521. var halfViewportWidth = viewportWidth * 0.5,
  21522. halfViewportHeight = viewportHeight * 0.5;
  21523. var mergeWith3D = true;
  21524. // setup gl
  21525. _gl.useProgram( _sprite.program );
  21526. if ( ! _sprite.attributesEnabled ) {
  21527. _gl.enableVertexAttribArray( attributes.position );
  21528. _gl.enableVertexAttribArray( attributes.uv );
  21529. _sprite.attributesEnabled = true;
  21530. }
  21531. _gl.disable( _gl.CULL_FACE );
  21532. _gl.enable( _gl.BLEND );
  21533. _gl.depthMask( true );
  21534. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21535. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21536. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21537. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21538. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  21539. _gl.activeTexture( _gl.TEXTURE0 );
  21540. _gl.uniform1i( uniforms.map, 0 );
  21541. // update positions and sort
  21542. var i, sprite, screenPosition, size, scale = [];
  21543. for( i = 0; i < nSprites; i ++ ) {
  21544. sprite = sprites[ i ];
  21545. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  21546. if( ! sprite.useScreenCoordinates ) {
  21547. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  21548. sprite.z = - sprite._modelViewMatrix.elements[14];
  21549. } else {
  21550. sprite.z = - sprite.position.z;
  21551. }
  21552. }
  21553. sprites.sort( painterSort );
  21554. // render all sprites
  21555. for( i = 0; i < nSprites; i ++ ) {
  21556. sprite = sprites[ i ];
  21557. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  21558. if ( sprite.map && sprite.map.image && sprite.map.image.width ) {
  21559. if ( sprite.useScreenCoordinates ) {
  21560. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21561. _gl.uniform3f( uniforms.screenPosition, ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  21562. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  21563. Math.max( 0, Math.min( 1, sprite.position.z ) ) );
  21564. } else {
  21565. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21566. _gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
  21567. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21568. }
  21569. size = sprite.map.image.width / ( sprite.scaleByViewport ? viewportHeight : 1 );
  21570. scale[ 0 ] = size * invAspect * sprite.scale.x;
  21571. scale[ 1 ] = size * sprite.scale.y;
  21572. _gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
  21573. _gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
  21574. _gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );
  21575. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21576. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21577. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21578. _gl.uniform2fv( uniforms.scale, scale );
  21579. if ( sprite.mergeWith3D && !mergeWith3D ) {
  21580. _gl.enable( _gl.DEPTH_TEST );
  21581. mergeWith3D = true;
  21582. } else if ( ! sprite.mergeWith3D && mergeWith3D ) {
  21583. _gl.disable( _gl.DEPTH_TEST );
  21584. mergeWith3D = false;
  21585. }
  21586. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21587. _renderer.setTexture( sprite.map, 0 );
  21588. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21589. }
  21590. }
  21591. // restore gl
  21592. _gl.enable( _gl.CULL_FACE );
  21593. _gl.enable( _gl.DEPTH_TEST );
  21594. _gl.depthMask( true );
  21595. };
  21596. function createProgram ( shader ) {
  21597. var program = _gl.createProgram();
  21598. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21599. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21600. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21601. _gl.shaderSource( vertexShader, shader.vertexShader );
  21602. _gl.compileShader( fragmentShader );
  21603. _gl.compileShader( vertexShader );
  21604. _gl.attachShader( program, fragmentShader );
  21605. _gl.attachShader( program, vertexShader );
  21606. _gl.linkProgram( program );
  21607. return program;
  21608. };
  21609. function painterSort ( a, b ) {
  21610. return b.z - a.z;
  21611. };
  21612. };/**
  21613. * @author alteredq / http://alteredqualia.com/
  21614. */
  21615. THREE.DepthPassPlugin = function ( ) {
  21616. this.enabled = false;
  21617. this.renderTarget = null;
  21618. var _gl,
  21619. _renderer,
  21620. _depthMaterial, _depthMaterialMorph,
  21621. _frustum = new THREE.Frustum(),
  21622. _projScreenMatrix = new THREE.Matrix4();
  21623. this.init = function ( renderer ) {
  21624. _gl = renderer.context;
  21625. _renderer = renderer;
  21626. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21627. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21628. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21629. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21630. _depthMaterial._shadowPass = true;
  21631. _depthMaterialMorph._shadowPass = true;
  21632. };
  21633. this.render = function ( scene, camera ) {
  21634. if ( ! this.enabled ) return;
  21635. this.update( scene, camera );
  21636. };
  21637. this.update = function ( scene, camera ) {
  21638. var i, il, j, jl, n,
  21639. program, buffer, material,
  21640. webglObject, object, light,
  21641. renderList,
  21642. fog = null;
  21643. // set GL state for depth map
  21644. _gl.clearColor( 1, 1, 1, 1 );
  21645. _gl.disable( _gl.BLEND );
  21646. _renderer.setDepthTest( true );
  21647. // update scene
  21648. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21649. // update camera matrices and frustum
  21650. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  21651. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  21652. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21653. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  21654. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  21655. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21656. _frustum.setFromMatrix( _projScreenMatrix );
  21657. // render depth map
  21658. _renderer.setRenderTarget( this.renderTarget );
  21659. _renderer.clear();
  21660. // set object matrices & frustum culling
  21661. renderList = scene.__webglObjects;
  21662. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21663. webglObject = renderList[ j ];
  21664. object = webglObject.object;
  21665. webglObject.render = false;
  21666. if ( object.visible ) {
  21667. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21668. //object.matrixWorld.flattenToArray( object._modelMatrixArray );
  21669. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  21670. webglObject.render = true;
  21671. }
  21672. }
  21673. }
  21674. // render regular objects
  21675. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21676. webglObject = renderList[ j ];
  21677. if ( webglObject.render ) {
  21678. object = webglObject.object;
  21679. buffer = webglObject.buffer;
  21680. if ( object.material ) _renderer.setMaterialFaces( object.material );
  21681. if ( object.customDepthMaterial ) {
  21682. material = object.customDepthMaterial;
  21683. } else if ( object.geometry.morphTargets.length ) {
  21684. material = _depthMaterialMorph;
  21685. } else {
  21686. material = _depthMaterial;
  21687. }
  21688. if ( buffer instanceof THREE.BufferGeometry ) {
  21689. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21690. } else {
  21691. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21692. }
  21693. }
  21694. }
  21695. // set matrices and render immediate objects
  21696. renderList = scene.__webglObjectsImmediate;
  21697. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21698. webglObject = renderList[ j ];
  21699. object = webglObject.object;
  21700. if ( object.visible && object.castShadow ) {
  21701. /*
  21702. if ( object.matrixAutoUpdate ) {
  21703. object.matrixWorld.flattenToArray( object._modelMatrixArray );
  21704. }
  21705. */
  21706. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  21707. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21708. }
  21709. }
  21710. // restore GL state
  21711. var clearColor = _renderer.getClearColor(),
  21712. clearAlpha = _renderer.getClearAlpha();
  21713. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21714. _gl.enable( _gl.BLEND );
  21715. };
  21716. };
  21717. /**
  21718. * @author mikael emtinger / http://gomo.se/
  21719. *
  21720. */
  21721. THREE.ShaderFlares = {
  21722. 'lensFlareVertexTexture': {
  21723. vertexShader: [
  21724. "uniform vec3 screenPosition;",
  21725. "uniform vec2 scale;",
  21726. "uniform float rotation;",
  21727. "uniform int renderType;",
  21728. "uniform sampler2D occlusionMap;",
  21729. "attribute vec2 position;",
  21730. "attribute vec2 uv;",
  21731. "varying vec2 vUV;",
  21732. "varying float vVisibility;",
  21733. "void main() {",
  21734. "vUV = uv;",
  21735. "vec2 pos = position;",
  21736. "if( renderType == 2 ) {",
  21737. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21738. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21739. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21740. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21741. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21742. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21743. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21744. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21745. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21746. "vVisibility = ( visibility.r / 9.0 ) *",
  21747. "( 1.0 - visibility.g / 9.0 ) *",
  21748. "( visibility.b / 9.0 ) *",
  21749. "( 1.0 - visibility.a / 9.0 );",
  21750. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21751. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21752. "}",
  21753. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21754. "}"
  21755. ].join( "\n" ),
  21756. fragmentShader: [
  21757. "precision mediump float;",
  21758. "uniform sampler2D map;",
  21759. "uniform float opacity;",
  21760. "uniform int renderType;",
  21761. "uniform vec3 color;",
  21762. "varying vec2 vUV;",
  21763. "varying float vVisibility;",
  21764. "void main() {",
  21765. // pink square
  21766. "if( renderType == 0 ) {",
  21767. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21768. // restore
  21769. "} else if( renderType == 1 ) {",
  21770. "gl_FragColor = texture2D( map, vUV );",
  21771. // flare
  21772. "} else {",
  21773. "vec4 texture = texture2D( map, vUV );",
  21774. "texture.a *= opacity * vVisibility;",
  21775. "gl_FragColor = texture;",
  21776. "gl_FragColor.rgb *= color;",
  21777. "}",
  21778. "}"
  21779. ].join( "\n" )
  21780. },
  21781. 'lensFlare': {
  21782. vertexShader: [
  21783. "uniform vec3 screenPosition;",
  21784. "uniform vec2 scale;",
  21785. "uniform float rotation;",
  21786. "uniform int renderType;",
  21787. "attribute vec2 position;",
  21788. "attribute vec2 uv;",
  21789. "varying vec2 vUV;",
  21790. "void main() {",
  21791. "vUV = uv;",
  21792. "vec2 pos = position;",
  21793. "if( renderType == 2 ) {",
  21794. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21795. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21796. "}",
  21797. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21798. "}"
  21799. ].join( "\n" ),
  21800. fragmentShader: [
  21801. "precision mediump float;",
  21802. "uniform sampler2D map;",
  21803. "uniform sampler2D occlusionMap;",
  21804. "uniform float opacity;",
  21805. "uniform int renderType;",
  21806. "uniform vec3 color;",
  21807. "varying vec2 vUV;",
  21808. "void main() {",
  21809. // pink square
  21810. "if( renderType == 0 ) {",
  21811. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21812. // restore
  21813. "} else if( renderType == 1 ) {",
  21814. "gl_FragColor = texture2D( map, vUV );",
  21815. // flare
  21816. "} else {",
  21817. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21818. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21819. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21820. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21821. "visibility = ( 1.0 - visibility / 4.0 );",
  21822. "vec4 texture = texture2D( map, vUV );",
  21823. "texture.a *= opacity * visibility;",
  21824. "gl_FragColor = texture;",
  21825. "gl_FragColor.rgb *= color;",
  21826. "}",
  21827. "}"
  21828. ].join( "\n" )
  21829. }
  21830. };
  21831. /**
  21832. * @author mikael emtinger / http://gomo.se/
  21833. *
  21834. */
  21835. THREE.ShaderSprite = {
  21836. 'sprite': {
  21837. vertexShader: [
  21838. "uniform int useScreenCoordinates;",
  21839. "uniform int affectedByDistance;",
  21840. "uniform vec3 screenPosition;",
  21841. "uniform mat4 modelViewMatrix;",
  21842. "uniform mat4 projectionMatrix;",
  21843. "uniform float rotation;",
  21844. "uniform vec2 scale;",
  21845. "uniform vec2 alignment;",
  21846. "uniform vec2 uvOffset;",
  21847. "uniform vec2 uvScale;",
  21848. "attribute vec2 position;",
  21849. "attribute vec2 uv;",
  21850. "varying vec2 vUV;",
  21851. "void main() {",
  21852. "vUV = uvOffset + uv * uvScale;",
  21853. "vec2 alignedPosition = position + alignment;",
  21854. "vec2 rotatedPosition;",
  21855. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21856. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21857. "vec4 finalPosition;",
  21858. "if( useScreenCoordinates != 0 ) {",
  21859. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21860. "} else {",
  21861. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21862. "finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",
  21863. "}",
  21864. "gl_Position = finalPosition;",
  21865. "}"
  21866. ].join( "\n" ),
  21867. fragmentShader: [
  21868. "precision mediump float;",
  21869. "uniform vec3 color;",
  21870. "uniform sampler2D map;",
  21871. "uniform float opacity;",
  21872. "varying vec2 vUV;",
  21873. "void main() {",
  21874. "vec4 texture = texture2D( map, vUV );",
  21875. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21876. "}"
  21877. ].join( "\n" )
  21878. }
  21879. };