three.js 821 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '54dev' };
  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. THREE.AddOperation = 2;
  101. // Mapping modes
  102. THREE.UVMapping = function () {};
  103. THREE.CubeReflectionMapping = function () {};
  104. THREE.CubeRefractionMapping = function () {};
  105. THREE.SphericalReflectionMapping = function () {};
  106. THREE.SphericalRefractionMapping = function () {};
  107. // Wrapping modes
  108. THREE.RepeatWrapping = 1000;
  109. THREE.ClampToEdgeWrapping = 1001;
  110. THREE.MirroredRepeatWrapping = 1002;
  111. // Filters
  112. THREE.NearestFilter = 1003;
  113. THREE.NearestMipMapNearestFilter = 1004;
  114. THREE.NearestMipMapLinearFilter = 1005;
  115. THREE.LinearFilter = 1006;
  116. THREE.LinearMipMapNearestFilter = 1007;
  117. THREE.LinearMipMapLinearFilter = 1008;
  118. // Data types
  119. THREE.UnsignedByteType = 1009;
  120. THREE.ByteType = 1010;
  121. THREE.ShortType = 1011;
  122. THREE.UnsignedShortType = 1012;
  123. THREE.IntType = 1013;
  124. THREE.UnsignedIntType = 1014;
  125. THREE.FloatType = 1015;
  126. // Pixel types
  127. //THREE.UnsignedByteType = 1009;
  128. THREE.UnsignedShort4444Type = 1016;
  129. THREE.UnsignedShort5551Type = 1017;
  130. THREE.UnsignedShort565Type = 1018;
  131. // Pixel formats
  132. THREE.AlphaFormat = 1019;
  133. THREE.RGBFormat = 1020;
  134. THREE.RGBAFormat = 1021;
  135. THREE.LuminanceFormat = 1022;
  136. THREE.LuminanceAlphaFormat = 1023;
  137. // Compressed texture formats
  138. THREE.RGB_S3TC_DXT1_Format = 2001;
  139. THREE.RGBA_S3TC_DXT1_Format = 2002;
  140. THREE.RGBA_S3TC_DXT3_Format = 2003;
  141. THREE.RGBA_S3TC_DXT5_Format = 2004;
  142. /*
  143. // Potential future PVRTC compressed texture formats
  144. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  145. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  146. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  147. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  148. */
  149. /**
  150. * @author alteredq / http://alteredqualia.com/
  151. */
  152. THREE.Clock = function ( autoStart ) {
  153. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  154. this.startTime = 0;
  155. this.oldTime = 0;
  156. this.elapsedTime = 0;
  157. this.running = false;
  158. };
  159. THREE.Clock.prototype.start = function () {
  160. this.startTime = Date.now();
  161. this.oldTime = this.startTime;
  162. this.running = true;
  163. };
  164. THREE.Clock.prototype.stop = function () {
  165. this.getElapsedTime();
  166. this.running = false;
  167. };
  168. THREE.Clock.prototype.getElapsedTime = function () {
  169. this.getDelta();
  170. return this.elapsedTime;
  171. };
  172. THREE.Clock.prototype.getDelta = function () {
  173. var diff = 0;
  174. if ( this.autoStart && ! this.running ) {
  175. this.start();
  176. }
  177. if ( this.running ) {
  178. var newTime = Date.now();
  179. diff = 0.001 * ( newTime - this.oldTime );
  180. this.oldTime = newTime;
  181. this.elapsedTime += diff;
  182. }
  183. return diff;
  184. };/**
  185. * @author mrdoob / http://mrdoob.com/
  186. */
  187. THREE.Color = function ( hex ) {
  188. if ( hex !== undefined ) this.setHex( hex );
  189. return this;
  190. };
  191. THREE.Color.prototype = {
  192. constructor: THREE.Color,
  193. r: 1, g: 1, b: 1,
  194. copy: function ( color ) {
  195. this.r = color.r;
  196. this.g = color.g;
  197. this.b = color.b;
  198. return this;
  199. },
  200. copyGammaToLinear: function ( color ) {
  201. this.r = color.r * color.r;
  202. this.g = color.g * color.g;
  203. this.b = color.b * color.b;
  204. return this;
  205. },
  206. copyLinearToGamma: function ( color ) {
  207. this.r = Math.sqrt( color.r );
  208. this.g = Math.sqrt( color.g );
  209. this.b = Math.sqrt( color.b );
  210. return this;
  211. },
  212. convertGammaToLinear: function () {
  213. var r = this.r, g = this.g, b = this.b;
  214. this.r = r * r;
  215. this.g = g * g;
  216. this.b = b * b;
  217. return this;
  218. },
  219. convertLinearToGamma: function () {
  220. this.r = Math.sqrt( this.r );
  221. this.g = Math.sqrt( this.g );
  222. this.b = Math.sqrt( this.b );
  223. return this;
  224. },
  225. setRGB: function ( r, g, b ) {
  226. this.r = r;
  227. this.g = g;
  228. this.b = b;
  229. return this;
  230. },
  231. setHSV: function ( h, s, v ) {
  232. // based on MochiKit implementation by Bob Ippolito
  233. // h,s,v ranges are < 0.0 - 1.0 >
  234. var i, f, p, q, t;
  235. if ( v === 0 ) {
  236. this.r = this.g = this.b = 0;
  237. } else {
  238. i = Math.floor( h * 6 );
  239. f = ( h * 6 ) - i;
  240. p = v * ( 1 - s );
  241. q = v * ( 1 - ( s * f ) );
  242. t = v * ( 1 - ( s * ( 1 - f ) ) );
  243. if ( i === 0 ) {
  244. this.r = v;
  245. this.g = t;
  246. this.b = p;
  247. } else if ( i === 1 ) {
  248. this.r = q;
  249. this.g = v;
  250. this.b = p;
  251. } else if ( i === 2 ) {
  252. this.r = p;
  253. this.g = v;
  254. this.b = t;
  255. } else if ( i === 3 ) {
  256. this.r = p;
  257. this.g = q;
  258. this.b = v;
  259. } else if ( i === 4 ) {
  260. this.r = t;
  261. this.g = p;
  262. this.b = v;
  263. } else if ( i === 5 ) {
  264. this.r = v;
  265. this.g = p;
  266. this.b = q;
  267. }
  268. }
  269. return this;
  270. },
  271. getHex: function () {
  272. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  273. },
  274. setHex: function ( hex ) {
  275. hex = Math.floor( hex );
  276. this.r = ( hex >> 16 & 255 ) / 255;
  277. this.g = ( hex >> 8 & 255 ) / 255;
  278. this.b = ( hex & 255 ) / 255;
  279. return this;
  280. },
  281. getHexString: function () {
  282. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  283. },
  284. getContextStyle: function () {
  285. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  286. },
  287. setContextStyle: function ( style ) {
  288. var color = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/i.exec( style );
  289. this.r = parseInt( color[ 1 ], 10 ) / 255;
  290. this.g = parseInt( color[ 2 ], 10 ) / 255;
  291. this.b = parseInt( color[ 3 ], 10 ) / 255;
  292. return this;
  293. },
  294. getHSV: function ( hsv ) {
  295. // based on MochiKit implementation by Bob Ippolito
  296. // h,s,v ranges are < 0.0 - 1.0 >
  297. var r = this.r;
  298. var g = this.g;
  299. var b = this.b;
  300. var max = Math.max( Math.max( r, g ), b );
  301. var min = Math.min( Math.min( r, g ), b );
  302. var hue;
  303. var saturation;
  304. var value = max;
  305. if ( min === max ) {
  306. hue = 0;
  307. saturation = 0;
  308. } else {
  309. var delta = ( max - min );
  310. saturation = delta / max;
  311. if ( r === max ) {
  312. hue = ( g - b ) / delta;
  313. } else if ( g === max ) {
  314. hue = 2 + ( ( b - r ) / delta );
  315. } else {
  316. hue = 4 + ( ( r - g ) / delta );
  317. }
  318. hue /= 6;
  319. if ( hue < 0 ) {
  320. hue += 1;
  321. }
  322. if ( hue > 1 ) {
  323. hue -= 1;
  324. }
  325. }
  326. if ( hsv === undefined ) {
  327. hsv = { h: 0, s: 0, v: 0 };
  328. }
  329. hsv.h = hue;
  330. hsv.s = saturation;
  331. hsv.v = value;
  332. return hsv;
  333. },
  334. lerpSelf: function ( color, alpha ) {
  335. this.r += ( color.r - this.r ) * alpha;
  336. this.g += ( color.g - this.g ) * alpha;
  337. this.b += ( color.b - this.b ) * alpha;
  338. return this;
  339. },
  340. clone: function () {
  341. return new THREE.Color().setRGB( this.r, this.g, this.b );
  342. }
  343. };
  344. /**
  345. * @author mrdoob / http://mrdoob.com/
  346. * @author philogb / http://blog.thejit.org/
  347. * @author egraether / http://egraether.com/
  348. * @author zz85 / http://www.lab4games.net/zz85/blog
  349. */
  350. THREE.Vector2 = function ( x, y ) {
  351. this.x = x || 0;
  352. this.y = y || 0;
  353. };
  354. THREE.Vector2.prototype = {
  355. constructor: THREE.Vector2,
  356. set: function ( x, y ) {
  357. this.x = x;
  358. this.y = y;
  359. return this;
  360. },
  361. copy: function ( v ) {
  362. this.x = v.x;
  363. this.y = v.y;
  364. return this;
  365. },
  366. add: function ( a, b ) {
  367. this.x = a.x + b.x;
  368. this.y = a.y + b.y;
  369. return this;
  370. },
  371. addSelf: function ( v ) {
  372. this.x += v.x;
  373. this.y += v.y;
  374. return this;
  375. },
  376. sub: function ( a, b ) {
  377. this.x = a.x - b.x;
  378. this.y = a.y - b.y;
  379. return this;
  380. },
  381. subSelf: function ( v ) {
  382. this.x -= v.x;
  383. this.y -= v.y;
  384. return this;
  385. },
  386. multiplyScalar: function ( s ) {
  387. this.x *= s;
  388. this.y *= s;
  389. return this;
  390. },
  391. divideScalar: function ( s ) {
  392. if ( s ) {
  393. this.x /= s;
  394. this.y /= s;
  395. } else {
  396. this.set( 0, 0 );
  397. }
  398. return this;
  399. },
  400. negate: function() {
  401. return this.multiplyScalar( - 1 );
  402. },
  403. dot: function ( v ) {
  404. return this.x * v.x + this.y * v.y;
  405. },
  406. lengthSq: function () {
  407. return this.x * this.x + this.y * this.y;
  408. },
  409. length: function () {
  410. return Math.sqrt( this.lengthSq() );
  411. },
  412. normalize: function () {
  413. return this.divideScalar( this.length() );
  414. },
  415. distanceTo: function ( v ) {
  416. return Math.sqrt( this.distanceToSquared( v ) );
  417. },
  418. distanceToSquared: function ( v ) {
  419. var dx = this.x - v.x, dy = this.y - v.y;
  420. return dx * dx + dy * dy;
  421. },
  422. setLength: function ( l ) {
  423. return this.normalize().multiplyScalar( l );
  424. },
  425. lerpSelf: function ( v, alpha ) {
  426. this.x += ( v.x - this.x ) * alpha;
  427. this.y += ( v.y - this.y ) * alpha;
  428. return this;
  429. },
  430. equals: function( v ) {
  431. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  432. },
  433. clone: function () {
  434. return new THREE.Vector2( this.x, this.y );
  435. }
  436. };
  437. /**
  438. * @author mrdoob / http://mrdoob.com/
  439. * @author kile / http://kile.stravaganza.org/
  440. * @author philogb / http://blog.thejit.org/
  441. * @author mikael emtinger / http://gomo.se/
  442. * @author egraether / http://egraether.com/
  443. * @author WestLangley / http://github.com/WestLangley
  444. */
  445. THREE.Vector3 = function ( x, y, z ) {
  446. this.x = x || 0;
  447. this.y = y || 0;
  448. this.z = z || 0;
  449. };
  450. THREE.Vector3.prototype = {
  451. constructor: THREE.Vector3,
  452. set: function ( x, y, z ) {
  453. this.x = x;
  454. this.y = y;
  455. this.z = z;
  456. return this;
  457. },
  458. setX: function ( x ) {
  459. this.x = x;
  460. return this;
  461. },
  462. setY: function ( y ) {
  463. this.y = y;
  464. return this;
  465. },
  466. setZ: function ( z ) {
  467. this.z = z;
  468. return this;
  469. },
  470. copy: function ( v ) {
  471. this.x = v.x;
  472. this.y = v.y;
  473. this.z = v.z;
  474. return this;
  475. },
  476. add: function ( a, b ) {
  477. this.x = a.x + b.x;
  478. this.y = a.y + b.y;
  479. this.z = a.z + b.z;
  480. return this;
  481. },
  482. addSelf: function ( v ) {
  483. this.x += v.x;
  484. this.y += v.y;
  485. this.z += v.z;
  486. return this;
  487. },
  488. addScalar: function ( s ) {
  489. this.x += s;
  490. this.y += s;
  491. this.z += s;
  492. return this;
  493. },
  494. sub: function ( a, b ) {
  495. this.x = a.x - b.x;
  496. this.y = a.y - b.y;
  497. this.z = a.z - b.z;
  498. return this;
  499. },
  500. subSelf: function ( v ) {
  501. this.x -= v.x;
  502. this.y -= v.y;
  503. this.z -= v.z;
  504. return this;
  505. },
  506. multiply: function ( a, b ) {
  507. this.x = a.x * b.x;
  508. this.y = a.y * b.y;
  509. this.z = a.z * b.z;
  510. return this;
  511. },
  512. multiplySelf: function ( v ) {
  513. this.x *= v.x;
  514. this.y *= v.y;
  515. this.z *= v.z;
  516. return this;
  517. },
  518. multiplyScalar: function ( s ) {
  519. this.x *= s;
  520. this.y *= s;
  521. this.z *= s;
  522. return this;
  523. },
  524. divideSelf: function ( v ) {
  525. this.x /= v.x;
  526. this.y /= v.y;
  527. this.z /= v.z;
  528. return this;
  529. },
  530. divideScalar: function ( s ) {
  531. if ( s ) {
  532. this.x /= s;
  533. this.y /= s;
  534. this.z /= s;
  535. } else {
  536. this.x = 0;
  537. this.y = 0;
  538. this.z = 0;
  539. }
  540. return this;
  541. },
  542. negate: function() {
  543. return this.multiplyScalar( - 1 );
  544. },
  545. dot: function ( v ) {
  546. return this.x * v.x + this.y * v.y + this.z * v.z;
  547. },
  548. lengthSq: function () {
  549. return this.x * this.x + this.y * this.y + this.z * this.z;
  550. },
  551. length: function () {
  552. return Math.sqrt( this.lengthSq() );
  553. },
  554. lengthManhattan: function () {
  555. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  556. },
  557. normalize: function () {
  558. return this.divideScalar( this.length() );
  559. },
  560. setLength: function ( l ) {
  561. return this.normalize().multiplyScalar( l );
  562. },
  563. lerpSelf: function ( v, alpha ) {
  564. this.x += ( v.x - this.x ) * alpha;
  565. this.y += ( v.y - this.y ) * alpha;
  566. this.z += ( v.z - this.z ) * alpha;
  567. return this;
  568. },
  569. cross: function ( a, b ) {
  570. this.x = a.y * b.z - a.z * b.y;
  571. this.y = a.z * b.x - a.x * b.z;
  572. this.z = a.x * b.y - a.y * b.x;
  573. return this;
  574. },
  575. crossSelf: function ( v ) {
  576. var x = this.x, y = this.y, z = this.z;
  577. this.x = y * v.z - z * v.y;
  578. this.y = z * v.x - x * v.z;
  579. this.z = x * v.y - y * v.x;
  580. return this;
  581. },
  582. angleTo: function ( v ) {
  583. return Math.acos( this.dot( v ) / this.length() / v.length() );
  584. },
  585. distanceTo: function ( v ) {
  586. return Math.sqrt( this.distanceToSquared( v ) );
  587. },
  588. distanceToSquared: function ( v ) {
  589. return new THREE.Vector3().sub( this, v ).lengthSq();
  590. },
  591. getPositionFromMatrix: function ( m ) {
  592. this.x = m.elements[12];
  593. this.y = m.elements[13];
  594. this.z = m.elements[14];
  595. return this;
  596. },
  597. setEulerFromRotationMatrix: function ( m, order ) {
  598. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  599. // clamp, to handle numerical problems
  600. function clamp( x ) {
  601. return Math.min( Math.max( x, -1 ), 1 );
  602. }
  603. var te = m.elements;
  604. var m11 = te[0], m12 = te[4], m13 = te[8];
  605. var m21 = te[1], m22 = te[5], m23 = te[9];
  606. var m31 = te[2], m32 = te[6], m33 = te[10];
  607. if ( order === undefined || order === 'XYZ' ) {
  608. this.y = Math.asin( clamp( m13 ) );
  609. if ( Math.abs( m13 ) < 0.99999 ) {
  610. this.x = Math.atan2( - m23, m33 );
  611. this.z = Math.atan2( - m12, m11 );
  612. } else {
  613. this.x = Math.atan2( m32, m22 );
  614. this.z = 0;
  615. }
  616. } else if ( order === 'YXZ' ) {
  617. this.x = Math.asin( - clamp( m23 ) );
  618. if ( Math.abs( m23 ) < 0.99999 ) {
  619. this.y = Math.atan2( m13, m33 );
  620. this.z = Math.atan2( m21, m22 );
  621. } else {
  622. this.y = Math.atan2( - m31, m11 );
  623. this.z = 0;
  624. }
  625. } else if ( order === 'ZXY' ) {
  626. this.x = Math.asin( clamp( m32 ) );
  627. if ( Math.abs( m32 ) < 0.99999 ) {
  628. this.y = Math.atan2( - m31, m33 );
  629. this.z = Math.atan2( - m12, m22 );
  630. } else {
  631. this.y = 0;
  632. this.z = Math.atan2( m21, m11 );
  633. }
  634. } else if ( order === 'ZYX' ) {
  635. this.y = Math.asin( - clamp( m31 ) );
  636. if ( Math.abs( m31 ) < 0.99999 ) {
  637. this.x = Math.atan2( m32, m33 );
  638. this.z = Math.atan2( m21, m11 );
  639. } else {
  640. this.x = 0;
  641. this.z = Math.atan2( - m12, m22 );
  642. }
  643. } else if ( order === 'YZX' ) {
  644. this.z = Math.asin( clamp( m21 ) );
  645. if ( Math.abs( m21 ) < 0.99999 ) {
  646. this.x = Math.atan2( - m23, m22 );
  647. this.y = Math.atan2( - m31, m11 );
  648. } else {
  649. this.x = 0;
  650. this.y = Math.atan2( m13, m33 );
  651. }
  652. } else if ( order === 'XZY' ) {
  653. this.z = Math.asin( - clamp( m12 ) );
  654. if ( Math.abs( m12 ) < 0.99999 ) {
  655. this.x = Math.atan2( m32, m22 );
  656. this.y = Math.atan2( m13, m11 );
  657. } else {
  658. this.x = Math.atan2( - m23, m33 );
  659. this.y = 0;
  660. }
  661. }
  662. return this;
  663. },
  664. setEulerFromQuaternion: function ( q, order ) {
  665. // q is assumed to be normalized
  666. // clamp, to handle numerical problems
  667. function clamp( x ) {
  668. return Math.min( Math.max( x, -1 ), 1 );
  669. }
  670. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  671. var sqx = q.x * q.x;
  672. var sqy = q.y * q.y;
  673. var sqz = q.z * q.z;
  674. var sqw = q.w * q.w;
  675. if ( order === undefined || order === 'XYZ' ) {
  676. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  677. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  678. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  679. } else if ( order === 'YXZ' ) {
  680. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  681. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  682. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  683. } else if ( order === 'ZXY' ) {
  684. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  685. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  686. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  687. } else if ( order === 'ZYX' ) {
  688. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  689. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  690. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  691. } else if ( order === 'YZX' ) {
  692. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  693. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  694. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  695. } else if ( order === 'XZY' ) {
  696. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  697. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  698. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  699. }
  700. return this;
  701. },
  702. getScaleFromMatrix: function ( m ) {
  703. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  704. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  705. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  706. this.x = sx;
  707. this.y = sy;
  708. this.z = sz;
  709. return this;
  710. },
  711. equals: function ( v ) {
  712. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  713. },
  714. clone: function () {
  715. return new THREE.Vector3( this.x, this.y, this.z );
  716. }
  717. };
  718. /**
  719. * @author supereggbert / http://www.paulbrunt.co.uk/
  720. * @author philogb / http://blog.thejit.org/
  721. * @author mikael emtinger / http://gomo.se/
  722. * @author egraether / http://egraether.com/
  723. * @author WestLangley / http://github.com/WestLangley
  724. */
  725. THREE.Vector4 = function ( x, y, z, w ) {
  726. this.x = x || 0;
  727. this.y = y || 0;
  728. this.z = z || 0;
  729. this.w = ( w !== undefined ) ? w : 1;
  730. };
  731. THREE.Vector4.prototype = {
  732. constructor: THREE.Vector4,
  733. set: function ( x, y, z, w ) {
  734. this.x = x;
  735. this.y = y;
  736. this.z = z;
  737. this.w = w;
  738. return this;
  739. },
  740. copy: function ( v ) {
  741. this.x = v.x;
  742. this.y = v.y;
  743. this.z = v.z;
  744. this.w = ( v.w !== undefined ) ? v.w : 1;
  745. return this;
  746. },
  747. add: function ( a, b ) {
  748. this.x = a.x + b.x;
  749. this.y = a.y + b.y;
  750. this.z = a.z + b.z;
  751. this.w = a.w + b.w;
  752. return this;
  753. },
  754. addSelf: function ( v ) {
  755. this.x += v.x;
  756. this.y += v.y;
  757. this.z += v.z;
  758. this.w += v.w;
  759. return this;
  760. },
  761. sub: function ( a, b ) {
  762. this.x = a.x - b.x;
  763. this.y = a.y - b.y;
  764. this.z = a.z - b.z;
  765. this.w = a.w - b.w;
  766. return this;
  767. },
  768. subSelf: function ( v ) {
  769. this.x -= v.x;
  770. this.y -= v.y;
  771. this.z -= v.z;
  772. this.w -= v.w;
  773. return this;
  774. },
  775. multiplyScalar: function ( s ) {
  776. this.x *= s;
  777. this.y *= s;
  778. this.z *= s;
  779. this.w *= s;
  780. return this;
  781. },
  782. divideScalar: function ( s ) {
  783. if ( s ) {
  784. this.x /= s;
  785. this.y /= s;
  786. this.z /= s;
  787. this.w /= s;
  788. } else {
  789. this.x = 0;
  790. this.y = 0;
  791. this.z = 0;
  792. this.w = 1;
  793. }
  794. return this;
  795. },
  796. negate: function() {
  797. return this.multiplyScalar( -1 );
  798. },
  799. dot: function ( v ) {
  800. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  801. },
  802. lengthSq: function () {
  803. return this.dot( this );
  804. },
  805. length: function () {
  806. return Math.sqrt( this.lengthSq() );
  807. },
  808. lengthManhattan: function () {
  809. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  810. },
  811. normalize: function () {
  812. return this.divideScalar( this.length() );
  813. },
  814. setLength: function ( l ) {
  815. return this.normalize().multiplyScalar( l );
  816. },
  817. lerpSelf: function ( v, alpha ) {
  818. this.x += ( v.x - this.x ) * alpha;
  819. this.y += ( v.y - this.y ) * alpha;
  820. this.z += ( v.z - this.z ) * alpha;
  821. this.w += ( v.w - this.w ) * alpha;
  822. return this;
  823. },
  824. clone: function () {
  825. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  826. },
  827. setAxisAngleFromQuaternion: function ( q ) {
  828. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  829. // q is assumed to be normalized
  830. this.w = 2 * Math.acos( q.w );
  831. var s = Math.sqrt( 1 - q.w * q.w );
  832. if ( s < 0.0001 ) {
  833. this.x = 1;
  834. this.y = 0;
  835. this.z = 0;
  836. } else {
  837. this.x = q.x / s;
  838. this.y = q.y / s;
  839. this.z = q.z / s;
  840. }
  841. return this;
  842. },
  843. setAxisAngleFromRotationMatrix: function ( m ) {
  844. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  845. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  846. var angle, x, y, z, // variables for result
  847. epsilon = 0.01, // margin to allow for rounding errors
  848. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  849. te = m.elements,
  850. m11 = te[0], m12 = te[4], m13 = te[8],
  851. m21 = te[1], m22 = te[5], m23 = te[9],
  852. m31 = te[2], m32 = te[6], m33 = te[10];
  853. if ( ( Math.abs( m12 - m21 ) < epsilon )
  854. && ( Math.abs( m13 - m31 ) < epsilon )
  855. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  856. // singularity found
  857. // first check for identity matrix which must have +1 for all terms
  858. // in leading diagonal and zero in other terms
  859. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  860. && ( Math.abs( m13 + m31 ) < epsilon2 )
  861. && ( Math.abs( m23 + m32 ) < epsilon2 )
  862. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  863. // this singularity is identity matrix so angle = 0
  864. this.set( 1, 0, 0, 0 );
  865. return this; // zero angle, arbitrary axis
  866. }
  867. // otherwise this singularity is angle = 180
  868. angle = Math.PI;
  869. var xx = ( m11 + 1 ) / 2;
  870. var yy = ( m22 + 1 ) / 2;
  871. var zz = ( m33 + 1 ) / 2;
  872. var xy = ( m12 + m21 ) / 4;
  873. var xz = ( m13 + m31 ) / 4;
  874. var yz = ( m23 + m32 ) / 4;
  875. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  876. if ( xx < epsilon ) {
  877. x = 0;
  878. y = 0.707106781;
  879. z = 0.707106781;
  880. } else {
  881. x = Math.sqrt( xx );
  882. y = xy / x;
  883. z = xz / x;
  884. }
  885. } else if ( yy > zz ) { // m22 is the largest diagonal term
  886. if ( yy < epsilon ) {
  887. x = 0.707106781;
  888. y = 0;
  889. z = 0.707106781;
  890. } else {
  891. y = Math.sqrt( yy );
  892. x = xy / y;
  893. z = yz / y;
  894. }
  895. } else { // m33 is the largest diagonal term so base result on this
  896. if ( zz < epsilon ) {
  897. x = 0.707106781;
  898. y = 0.707106781;
  899. z = 0;
  900. } else {
  901. z = Math.sqrt( zz );
  902. x = xz / z;
  903. y = yz / z;
  904. }
  905. }
  906. this.set( x, y, z, angle );
  907. return this; // return 180 deg rotation
  908. }
  909. // as we have reached here there are no singularities so we can handle normally
  910. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  911. + ( m13 - m31 ) * ( m13 - m31 )
  912. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  913. if ( Math.abs( s ) < 0.001 ) s = 1;
  914. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  915. // caught by singularity test above, but I've left it in just in case
  916. this.x = ( m32 - m23 ) / s;
  917. this.y = ( m13 - m31 ) / s;
  918. this.z = ( m21 - m12 ) / s;
  919. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  920. return this;
  921. }
  922. };
  923. /**
  924. * @author alteredq / http://alteredqualia.com/
  925. * @author WestLangley / http://github.com/WestLangley
  926. */
  927. THREE.Matrix3 = function () {
  928. this.elements = new Float32Array(9);
  929. };
  930. THREE.Matrix3.prototype = {
  931. constructor: THREE.Matrix3,
  932. multiplyVector3: function ( v ) {
  933. var te = this.elements;
  934. var vx = v.x, vy = v.y, vz = v.z;
  935. v.x = te[0] * vx + te[3] * vy + te[6] * vz;
  936. v.y = te[1] * vx + te[4] * vy + te[7] * vz;
  937. v.z = te[2] * vx + te[5] * vy + te[8] * vz;
  938. return v;
  939. },
  940. multiplyVector3Array: function ( a ) {
  941. var tmp = THREE.Matrix3.__v1;
  942. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  943. tmp.x = a[ i ];
  944. tmp.y = a[ i + 1 ];
  945. tmp.z = a[ i + 2 ];
  946. this.multiplyVector3( tmp );
  947. a[ i ] = tmp.x;
  948. a[ i + 1 ] = tmp.y;
  949. a[ i + 2 ] = tmp.z;
  950. }
  951. return a;
  952. },
  953. getInverse: function ( matrix ) {
  954. // input: THREE.Matrix4
  955. // ( based on http://code.google.com/p/webgl-mjs/ )
  956. var me = matrix.elements;
  957. var a11 = me[10] * me[5] - me[6] * me[9];
  958. var a21 = - me[10] * me[1] + me[2] * me[9];
  959. var a31 = me[6] * me[1] - me[2] * me[5];
  960. var a12 = - me[10] * me[4] + me[6] * me[8];
  961. var a22 = me[10] * me[0] - me[2] * me[8];
  962. var a32 = - me[6] * me[0] + me[2] * me[4];
  963. var a13 = me[9] * me[4] - me[5] * me[8];
  964. var a23 = - me[9] * me[0] + me[1] * me[8];
  965. var a33 = me[5] * me[0] - me[1] * me[4];
  966. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  967. // no inverse
  968. if ( det === 0 ) {
  969. console.warn( "Matrix3.getInverse(): determinant == 0" );
  970. }
  971. var idet = 1.0 / det;
  972. var m = this.elements;
  973. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  974. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  975. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  976. return this;
  977. },
  978. transpose: function () {
  979. var tmp, m = this.elements;
  980. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  981. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  982. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  983. return this;
  984. },
  985. transposeIntoArray: function ( r ) {
  986. var m = this.m;
  987. r[ 0 ] = m[ 0 ];
  988. r[ 1 ] = m[ 3 ];
  989. r[ 2 ] = m[ 6 ];
  990. r[ 3 ] = m[ 1 ];
  991. r[ 4 ] = m[ 4 ];
  992. r[ 5 ] = m[ 7 ];
  993. r[ 6 ] = m[ 2 ];
  994. r[ 7 ] = m[ 5 ];
  995. r[ 8 ] = m[ 8 ];
  996. return this;
  997. }
  998. };
  999. THREE.Matrix3.__v1 = new THREE.Vector3();/**
  1000. * @author mrdoob / http://mrdoob.com/
  1001. * @author supereggbert / http://www.paulbrunt.co.uk/
  1002. * @author philogb / http://blog.thejit.org/
  1003. * @author jordi_ros / http://plattsoft.com
  1004. * @author D1plo1d / http://github.com/D1plo1d
  1005. * @author alteredq / http://alteredqualia.com/
  1006. * @author mikael emtinger / http://gomo.se/
  1007. * @author timknip / http://www.floorplanner.com/
  1008. */
  1009. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1010. this.elements = new Float32Array( 16 );
  1011. this.set(
  1012. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  1013. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  1014. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  1015. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  1016. );
  1017. };
  1018. THREE.Matrix4.prototype = {
  1019. constructor: THREE.Matrix4,
  1020. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1021. var te = this.elements;
  1022. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  1023. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1024. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1025. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1026. return this;
  1027. },
  1028. identity: function () {
  1029. this.set(
  1030. 1, 0, 0, 0,
  1031. 0, 1, 0, 0,
  1032. 0, 0, 1, 0,
  1033. 0, 0, 0, 1
  1034. );
  1035. return this;
  1036. },
  1037. copy: function ( m ) {
  1038. var me = m.elements;
  1039. this.set(
  1040. me[0], me[4], me[8], me[12],
  1041. me[1], me[5], me[9], me[13],
  1042. me[2], me[6], me[10], me[14],
  1043. me[3], me[7], me[11], me[15]
  1044. );
  1045. return this;
  1046. },
  1047. lookAt: function ( eye, target, up ) {
  1048. var te = this.elements;
  1049. var x = THREE.Matrix4.__v1;
  1050. var y = THREE.Matrix4.__v2;
  1051. var z = THREE.Matrix4.__v3;
  1052. z.sub( eye, target ).normalize();
  1053. if ( z.length() === 0 ) {
  1054. z.z = 1;
  1055. }
  1056. x.cross( up, z ).normalize();
  1057. if ( x.length() === 0 ) {
  1058. z.x += 0.0001;
  1059. x.cross( up, z ).normalize();
  1060. }
  1061. y.cross( z, x );
  1062. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1063. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1064. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1065. return this;
  1066. },
  1067. multiply: function ( a, b ) {
  1068. var ae = a.elements;
  1069. var be = b.elements;
  1070. var te = this.elements;
  1071. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1072. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1073. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1074. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1075. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1076. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1077. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1078. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1079. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1080. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1081. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1082. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1083. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1084. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1085. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1086. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1087. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1088. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1089. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1090. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1091. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1092. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1093. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1094. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1095. return this;
  1096. },
  1097. multiplySelf: function ( m ) {
  1098. return this.multiply( this, m );
  1099. },
  1100. multiplyToArray: function ( a, b, r ) {
  1101. var te = this.elements;
  1102. this.multiply( a, b );
  1103. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1104. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1105. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1106. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1107. return this;
  1108. },
  1109. multiplyScalar: function ( s ) {
  1110. var te = this.elements;
  1111. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1112. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1113. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1114. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1115. return this;
  1116. },
  1117. multiplyVector3: function ( v ) {
  1118. var te = this.elements;
  1119. var vx = v.x, vy = v.y, vz = v.z;
  1120. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1121. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1122. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1123. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1124. return v;
  1125. },
  1126. multiplyVector4: function ( v ) {
  1127. var te = this.elements;
  1128. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1129. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1130. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1131. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1132. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1133. return v;
  1134. },
  1135. multiplyVector3Array: function ( a ) {
  1136. var tmp = THREE.Matrix4.__v1;
  1137. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1138. tmp.x = a[ i ];
  1139. tmp.y = a[ i + 1 ];
  1140. tmp.z = a[ i + 2 ];
  1141. this.multiplyVector3( tmp );
  1142. a[ i ] = tmp.x;
  1143. a[ i + 1 ] = tmp.y;
  1144. a[ i + 2 ] = tmp.z;
  1145. }
  1146. return a;
  1147. },
  1148. rotateAxis: function ( v ) {
  1149. var te = this.elements;
  1150. var vx = v.x, vy = v.y, vz = v.z;
  1151. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1152. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1153. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1154. v.normalize();
  1155. return v;
  1156. },
  1157. crossVector: function ( a ) {
  1158. var te = this.elements;
  1159. var v = new THREE.Vector4();
  1160. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1161. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1162. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1163. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1164. return v;
  1165. },
  1166. determinant: function () {
  1167. var te = this.elements;
  1168. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1169. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1170. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1171. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1172. //TODO: make this more efficient
  1173. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1174. return (
  1175. n14 * n23 * n32 * n41-
  1176. n13 * n24 * n32 * n41-
  1177. n14 * n22 * n33 * n41+
  1178. n12 * n24 * n33 * n41+
  1179. n13 * n22 * n34 * n41-
  1180. n12 * n23 * n34 * n41-
  1181. n14 * n23 * n31 * n42+
  1182. n13 * n24 * n31 * n42+
  1183. n14 * n21 * n33 * n42-
  1184. n11 * n24 * n33 * n42-
  1185. n13 * n21 * n34 * n42+
  1186. n11 * n23 * n34 * n42+
  1187. n14 * n22 * n31 * n43-
  1188. n12 * n24 * n31 * n43-
  1189. n14 * n21 * n32 * n43+
  1190. n11 * n24 * n32 * n43+
  1191. n12 * n21 * n34 * n43-
  1192. n11 * n22 * n34 * n43-
  1193. n13 * n22 * n31 * n44+
  1194. n12 * n23 * n31 * n44+
  1195. n13 * n21 * n32 * n44-
  1196. n11 * n23 * n32 * n44-
  1197. n12 * n21 * n33 * n44+
  1198. n11 * n22 * n33 * n44
  1199. );
  1200. },
  1201. transpose: function () {
  1202. var te = this.elements;
  1203. var tmp;
  1204. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1205. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1206. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1207. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1208. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1209. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1210. return this;
  1211. },
  1212. flattenToArray: function ( flat ) {
  1213. var te = this.elements;
  1214. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1215. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1216. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1217. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1218. return flat;
  1219. },
  1220. flattenToArrayOffset: function( flat, offset ) {
  1221. var te = this.elements;
  1222. flat[ offset ] = te[0];
  1223. flat[ offset + 1 ] = te[1];
  1224. flat[ offset + 2 ] = te[2];
  1225. flat[ offset + 3 ] = te[3];
  1226. flat[ offset + 4 ] = te[4];
  1227. flat[ offset + 5 ] = te[5];
  1228. flat[ offset + 6 ] = te[6];
  1229. flat[ offset + 7 ] = te[7];
  1230. flat[ offset + 8 ] = te[8];
  1231. flat[ offset + 9 ] = te[9];
  1232. flat[ offset + 10 ] = te[10];
  1233. flat[ offset + 11 ] = te[11];
  1234. flat[ offset + 12 ] = te[12];
  1235. flat[ offset + 13 ] = te[13];
  1236. flat[ offset + 14 ] = te[14];
  1237. flat[ offset + 15 ] = te[15];
  1238. return flat;
  1239. },
  1240. getPosition: function () {
  1241. var te = this.elements;
  1242. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1243. },
  1244. setPosition: function ( v ) {
  1245. var te = this.elements;
  1246. te[12] = v.x;
  1247. te[13] = v.y;
  1248. te[14] = v.z;
  1249. return this;
  1250. },
  1251. getColumnX: function () {
  1252. var te = this.elements;
  1253. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1254. },
  1255. getColumnY: function () {
  1256. var te = this.elements;
  1257. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1258. },
  1259. getColumnZ: function() {
  1260. var te = this.elements;
  1261. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1262. },
  1263. getInverse: function ( m ) {
  1264. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1265. var te = this.elements;
  1266. var me = m.elements;
  1267. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1268. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1269. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1270. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1271. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1272. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1273. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1274. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1275. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1276. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1277. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1278. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1279. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1280. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1281. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1282. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1283. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1284. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1285. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1286. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1287. this.multiplyScalar( 1 / m.determinant() );
  1288. return this;
  1289. },
  1290. setRotationFromEuler: function ( v, order ) {
  1291. var te = this.elements;
  1292. var x = v.x, y = v.y, z = v.z;
  1293. var a = Math.cos( x ), b = Math.sin( x );
  1294. var c = Math.cos( y ), d = Math.sin( y );
  1295. var e = Math.cos( z ), f = Math.sin( z );
  1296. if ( order === undefined || order === 'XYZ' ) {
  1297. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1298. te[0] = c * e;
  1299. te[4] = - c * f;
  1300. te[8] = d;
  1301. te[1] = af + be * d;
  1302. te[5] = ae - bf * d;
  1303. te[9] = - b * c;
  1304. te[2] = bf - ae * d;
  1305. te[6] = be + af * d;
  1306. te[10] = a * c;
  1307. } else if ( order === 'YXZ' ) {
  1308. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1309. te[0] = ce + df * b;
  1310. te[4] = de * b - cf;
  1311. te[8] = a * d;
  1312. te[1] = a * f;
  1313. te[5] = a * e;
  1314. te[9] = - b;
  1315. te[2] = cf * b - de;
  1316. te[6] = df + ce * b;
  1317. te[10] = a * c;
  1318. } else if ( order === 'ZXY' ) {
  1319. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1320. te[0] = ce - df * b;
  1321. te[4] = - a * f;
  1322. te[8] = de + cf * b;
  1323. te[1] = cf + de * b;
  1324. te[5] = a * e;
  1325. te[9] = df - ce * b;
  1326. te[2] = - a * d;
  1327. te[6] = b;
  1328. te[10] = a * c;
  1329. } else if ( order === 'ZYX' ) {
  1330. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1331. te[0] = c * e;
  1332. te[4] = be * d - af;
  1333. te[8] = ae * d + bf;
  1334. te[1] = c * f;
  1335. te[5] = bf * d + ae;
  1336. te[9] = af * d - be;
  1337. te[2] = - d;
  1338. te[6] = b * c;
  1339. te[10] = a * c;
  1340. } else if ( order === 'YZX' ) {
  1341. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1342. te[0] = c * e;
  1343. te[4] = bd - ac * f;
  1344. te[8] = bc * f + ad;
  1345. te[1] = f;
  1346. te[5] = a * e;
  1347. te[9] = - b * e;
  1348. te[2] = - d * e;
  1349. te[6] = ad * f + bc;
  1350. te[10] = ac - bd * f;
  1351. } else if ( order === 'XZY' ) {
  1352. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1353. te[0] = c * e;
  1354. te[4] = - f;
  1355. te[8] = d * e;
  1356. te[1] = ac * f + bd;
  1357. te[5] = a * e;
  1358. te[9] = ad * f - bc;
  1359. te[2] = bc * f - ad;
  1360. te[6] = b * e;
  1361. te[10] = bd * f + ac;
  1362. }
  1363. return this;
  1364. },
  1365. setRotationFromQuaternion: function ( q ) {
  1366. var te = this.elements;
  1367. var x = q.x, y = q.y, z = q.z, w = q.w;
  1368. var x2 = x + x, y2 = y + y, z2 = z + z;
  1369. var xx = x * x2, xy = x * y2, xz = x * z2;
  1370. var yy = y * y2, yz = y * z2, zz = z * z2;
  1371. var wx = w * x2, wy = w * y2, wz = w * z2;
  1372. te[0] = 1 - ( yy + zz );
  1373. te[4] = xy - wz;
  1374. te[8] = xz + wy;
  1375. te[1] = xy + wz;
  1376. te[5] = 1 - ( xx + zz );
  1377. te[9] = yz - wx;
  1378. te[2] = xz - wy;
  1379. te[6] = yz + wx;
  1380. te[10] = 1 - ( xx + yy );
  1381. return this;
  1382. },
  1383. compose: function ( translation, rotation, scale ) {
  1384. var te = this.elements;
  1385. var mRotation = THREE.Matrix4.__m1;
  1386. var mScale = THREE.Matrix4.__m2;
  1387. mRotation.identity();
  1388. mRotation.setRotationFromQuaternion( rotation );
  1389. mScale.makeScale( scale.x, scale.y, scale.z );
  1390. this.multiply( mRotation, mScale );
  1391. te[12] = translation.x;
  1392. te[13] = translation.y;
  1393. te[14] = translation.z;
  1394. return this;
  1395. },
  1396. decompose: function ( translation, rotation, scale ) {
  1397. var te = this.elements;
  1398. // grab the axis vectors
  1399. var x = THREE.Matrix4.__v1;
  1400. var y = THREE.Matrix4.__v2;
  1401. var z = THREE.Matrix4.__v3;
  1402. x.set( te[0], te[1], te[2] );
  1403. y.set( te[4], te[5], te[6] );
  1404. z.set( te[8], te[9], te[10] );
  1405. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1406. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1407. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1408. scale.x = x.length();
  1409. scale.y = y.length();
  1410. scale.z = z.length();
  1411. translation.x = te[12];
  1412. translation.y = te[13];
  1413. translation.z = te[14];
  1414. // scale the rotation part
  1415. var matrix = THREE.Matrix4.__m1;
  1416. matrix.copy( this );
  1417. matrix.elements[0] /= scale.x;
  1418. matrix.elements[1] /= scale.x;
  1419. matrix.elements[2] /= scale.x;
  1420. matrix.elements[4] /= scale.y;
  1421. matrix.elements[5] /= scale.y;
  1422. matrix.elements[6] /= scale.y;
  1423. matrix.elements[8] /= scale.z;
  1424. matrix.elements[9] /= scale.z;
  1425. matrix.elements[10] /= scale.z;
  1426. rotation.setFromRotationMatrix( matrix );
  1427. return [ translation, rotation, scale ];
  1428. },
  1429. extractPosition: function ( m ) {
  1430. var te = this.elements;
  1431. var me = m.elements;
  1432. te[12] = me[12];
  1433. te[13] = me[13];
  1434. te[14] = me[14];
  1435. return this;
  1436. },
  1437. extractRotation: function ( m ) {
  1438. var te = this.elements;
  1439. var me = m.elements;
  1440. var vector = THREE.Matrix4.__v1;
  1441. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1442. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1443. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1444. te[0] = me[0] * scaleX;
  1445. te[1] = me[1] * scaleX;
  1446. te[2] = me[2] * scaleX;
  1447. te[4] = me[4] * scaleY;
  1448. te[5] = me[5] * scaleY;
  1449. te[6] = me[6] * scaleY;
  1450. te[8] = me[8] * scaleZ;
  1451. te[9] = me[9] * scaleZ;
  1452. te[10] = me[10] * scaleZ;
  1453. return this;
  1454. },
  1455. //
  1456. translate: function ( v ) {
  1457. var te = this.elements;
  1458. var x = v.x, y = v.y, z = v.z;
  1459. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1460. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1461. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1462. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1463. return this;
  1464. },
  1465. rotateX: function ( angle ) {
  1466. var te = this.elements;
  1467. var m12 = te[4];
  1468. var m22 = te[5];
  1469. var m32 = te[6];
  1470. var m42 = te[7];
  1471. var m13 = te[8];
  1472. var m23 = te[9];
  1473. var m33 = te[10];
  1474. var m43 = te[11];
  1475. var c = Math.cos( angle );
  1476. var s = Math.sin( angle );
  1477. te[4] = c * m12 + s * m13;
  1478. te[5] = c * m22 + s * m23;
  1479. te[6] = c * m32 + s * m33;
  1480. te[7] = c * m42 + s * m43;
  1481. te[8] = c * m13 - s * m12;
  1482. te[9] = c * m23 - s * m22;
  1483. te[10] = c * m33 - s * m32;
  1484. te[11] = c * m43 - s * m42;
  1485. return this;
  1486. },
  1487. rotateY: function ( angle ) {
  1488. var te = this.elements;
  1489. var m11 = te[0];
  1490. var m21 = te[1];
  1491. var m31 = te[2];
  1492. var m41 = te[3];
  1493. var m13 = te[8];
  1494. var m23 = te[9];
  1495. var m33 = te[10];
  1496. var m43 = te[11];
  1497. var c = Math.cos( angle );
  1498. var s = Math.sin( angle );
  1499. te[0] = c * m11 - s * m13;
  1500. te[1] = c * m21 - s * m23;
  1501. te[2] = c * m31 - s * m33;
  1502. te[3] = c * m41 - s * m43;
  1503. te[8] = c * m13 + s * m11;
  1504. te[9] = c * m23 + s * m21;
  1505. te[10] = c * m33 + s * m31;
  1506. te[11] = c * m43 + s * m41;
  1507. return this;
  1508. },
  1509. rotateZ: function ( angle ) {
  1510. var te = this.elements;
  1511. var m11 = te[0];
  1512. var m21 = te[1];
  1513. var m31 = te[2];
  1514. var m41 = te[3];
  1515. var m12 = te[4];
  1516. var m22 = te[5];
  1517. var m32 = te[6];
  1518. var m42 = te[7];
  1519. var c = Math.cos( angle );
  1520. var s = Math.sin( angle );
  1521. te[0] = c * m11 + s * m12;
  1522. te[1] = c * m21 + s * m22;
  1523. te[2] = c * m31 + s * m32;
  1524. te[3] = c * m41 + s * m42;
  1525. te[4] = c * m12 - s * m11;
  1526. te[5] = c * m22 - s * m21;
  1527. te[6] = c * m32 - s * m31;
  1528. te[7] = c * m42 - s * m41;
  1529. return this;
  1530. },
  1531. rotateByAxis: function ( axis, angle ) {
  1532. var te = this.elements;
  1533. // optimize by checking axis
  1534. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1535. return this.rotateX( angle );
  1536. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1537. return this.rotateY( angle );
  1538. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1539. return this.rotateZ( angle );
  1540. }
  1541. var x = axis.x, y = axis.y, z = axis.z;
  1542. var n = Math.sqrt(x * x + y * y + z * z);
  1543. x /= n;
  1544. y /= n;
  1545. z /= n;
  1546. var xx = x * x, yy = y * y, zz = z * z;
  1547. var c = Math.cos( angle );
  1548. var s = Math.sin( angle );
  1549. var oneMinusCosine = 1 - c;
  1550. var xy = x * y * oneMinusCosine;
  1551. var xz = x * z * oneMinusCosine;
  1552. var yz = y * z * oneMinusCosine;
  1553. var xs = x * s;
  1554. var ys = y * s;
  1555. var zs = z * s;
  1556. var r11 = xx + (1 - xx) * c;
  1557. var r21 = xy + zs;
  1558. var r31 = xz - ys;
  1559. var r12 = xy - zs;
  1560. var r22 = yy + (1 - yy) * c;
  1561. var r32 = yz + xs;
  1562. var r13 = xz + ys;
  1563. var r23 = yz - xs;
  1564. var r33 = zz + (1 - zz) * c;
  1565. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1566. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1567. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1568. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1569. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1570. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1571. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1572. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1573. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1574. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1575. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1576. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1577. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1578. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1579. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1580. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1581. return this;
  1582. },
  1583. scale: function ( v ) {
  1584. var te = this.elements;
  1585. var x = v.x, y = v.y, z = v.z;
  1586. te[0] *= x; te[4] *= y; te[8] *= z;
  1587. te[1] *= x; te[5] *= y; te[9] *= z;
  1588. te[2] *= x; te[6] *= y; te[10] *= z;
  1589. te[3] *= x; te[7] *= y; te[11] *= z;
  1590. return this;
  1591. },
  1592. getMaxScaleOnAxis: function () {
  1593. var te = this.elements;
  1594. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  1595. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  1596. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  1597. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  1598. },
  1599. //
  1600. makeTranslation: function ( x, y, z ) {
  1601. this.set(
  1602. 1, 0, 0, x,
  1603. 0, 1, 0, y,
  1604. 0, 0, 1, z,
  1605. 0, 0, 0, 1
  1606. );
  1607. return this;
  1608. },
  1609. makeRotationX: function ( theta ) {
  1610. var c = Math.cos( theta ), s = Math.sin( theta );
  1611. this.set(
  1612. 1, 0, 0, 0,
  1613. 0, c, -s, 0,
  1614. 0, s, c, 0,
  1615. 0, 0, 0, 1
  1616. );
  1617. return this;
  1618. },
  1619. makeRotationY: function ( theta ) {
  1620. var c = Math.cos( theta ), s = Math.sin( theta );
  1621. this.set(
  1622. c, 0, s, 0,
  1623. 0, 1, 0, 0,
  1624. -s, 0, c, 0,
  1625. 0, 0, 0, 1
  1626. );
  1627. return this;
  1628. },
  1629. makeRotationZ: function ( theta ) {
  1630. var c = Math.cos( theta ), s = Math.sin( theta );
  1631. this.set(
  1632. c, -s, 0, 0,
  1633. s, c, 0, 0,
  1634. 0, 0, 1, 0,
  1635. 0, 0, 0, 1
  1636. );
  1637. return this;
  1638. },
  1639. makeRotationAxis: function ( axis, angle ) {
  1640. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1641. var c = Math.cos( angle );
  1642. var s = Math.sin( angle );
  1643. var t = 1 - c;
  1644. var x = axis.x, y = axis.y, z = axis.z;
  1645. var tx = t * x, ty = t * y;
  1646. this.set(
  1647. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1648. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1649. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1650. 0, 0, 0, 1
  1651. );
  1652. return this;
  1653. },
  1654. makeScale: function ( x, y, z ) {
  1655. this.set(
  1656. x, 0, 0, 0,
  1657. 0, y, 0, 0,
  1658. 0, 0, z, 0,
  1659. 0, 0, 0, 1
  1660. );
  1661. return this;
  1662. },
  1663. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1664. var te = this.elements;
  1665. var x = 2 * near / ( right - left );
  1666. var y = 2 * near / ( top - bottom );
  1667. var a = ( right + left ) / ( right - left );
  1668. var b = ( top + bottom ) / ( top - bottom );
  1669. var c = - ( far + near ) / ( far - near );
  1670. var d = - 2 * far * near / ( far - near );
  1671. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1672. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1673. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1674. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1675. return this;
  1676. },
  1677. makePerspective: function ( fov, aspect, near, far ) {
  1678. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1679. var ymin = - ymax;
  1680. var xmin = ymin * aspect;
  1681. var xmax = ymax * aspect;
  1682. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1683. },
  1684. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1685. var te = this.elements;
  1686. var w = right - left;
  1687. var h = top - bottom;
  1688. var p = far - near;
  1689. var x = ( right + left ) / w;
  1690. var y = ( top + bottom ) / h;
  1691. var z = ( far + near ) / p;
  1692. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1693. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1694. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1695. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  1696. return this;
  1697. },
  1698. clone: function () {
  1699. var te = this.elements;
  1700. return new THREE.Matrix4(
  1701. te[0], te[4], te[8], te[12],
  1702. te[1], te[5], te[9], te[13],
  1703. te[2], te[6], te[10], te[14],
  1704. te[3], te[7], te[11], te[15]
  1705. );
  1706. }
  1707. };
  1708. THREE.Matrix4.__v1 = new THREE.Vector3();
  1709. THREE.Matrix4.__v2 = new THREE.Vector3();
  1710. THREE.Matrix4.__v3 = new THREE.Vector3();
  1711. THREE.Matrix4.__m1 = new THREE.Matrix4();
  1712. THREE.Matrix4.__m2 = new THREE.Matrix4();
  1713. /**
  1714. * https://github.com/mrdoob/eventtarget.js/
  1715. */
  1716. THREE.EventTarget = function () {
  1717. var listeners = {};
  1718. this.addEventListener = function ( type, listener ) {
  1719. if ( listeners[ type ] === undefined ) {
  1720. listeners[ type ] = [];
  1721. }
  1722. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1723. listeners[ type ].push( listener );
  1724. }
  1725. };
  1726. this.dispatchEvent = function ( event ) {
  1727. var listenerArray = listeners[ event.type ];
  1728. if ( listenerArray !== undefined ) {
  1729. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  1730. listenerArray[ i ]( event );
  1731. }
  1732. }
  1733. };
  1734. this.removeEventListener = function ( type, listener ) {
  1735. var index = listeners[ type ].indexOf( listener );
  1736. if ( index !== - 1 ) {
  1737. listeners[ type ].splice( index, 1 );
  1738. }
  1739. };
  1740. };
  1741. /**
  1742. * @author mrdoob / http://mrdoob.com/
  1743. * @author alteredq / http://alteredqualia.com/
  1744. */
  1745. THREE.Frustum = function ( ) {
  1746. this.planes = [
  1747. new THREE.Vector4(),
  1748. new THREE.Vector4(),
  1749. new THREE.Vector4(),
  1750. new THREE.Vector4(),
  1751. new THREE.Vector4(),
  1752. new THREE.Vector4()
  1753. ];
  1754. };
  1755. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  1756. var plane;
  1757. var planes = this.planes;
  1758. var me = m.elements;
  1759. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  1760. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  1761. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  1762. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  1763. planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  1764. planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  1765. planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  1766. planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  1767. planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  1768. planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  1769. for ( var i = 0; i < 6; i ++ ) {
  1770. plane = planes[ i ];
  1771. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  1772. }
  1773. };
  1774. THREE.Frustum.prototype.contains = function ( object ) {
  1775. var distance = 0.0;
  1776. var planes = this.planes;
  1777. var matrix = object.matrixWorld;
  1778. var me = matrix.elements;
  1779. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  1780. for ( var i = 0; i < 6; i ++ ) {
  1781. distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
  1782. if ( distance <= radius ) return false;
  1783. }
  1784. return true;
  1785. };
  1786. THREE.Frustum.__v1 = new THREE.Vector3();
  1787. /**
  1788. * @author mrdoob / http://mrdoob.com/
  1789. */
  1790. ( function ( THREE ) {
  1791. THREE.Ray = function ( origin, direction, near, far ) {
  1792. this.origin = origin || new THREE.Vector3();
  1793. this.direction = direction || new THREE.Vector3();
  1794. this.near = near || 0;
  1795. this.far = far || Infinity;
  1796. };
  1797. var originCopy = new THREE.Vector3();
  1798. var localOriginCopy = new THREE.Vector3();
  1799. var localDirectionCopy = new THREE.Vector3();
  1800. var vector = new THREE.Vector3();
  1801. var normal = new THREE.Vector3();
  1802. var intersectPoint = new THREE.Vector3();
  1803. var inverseMatrix = new THREE.Matrix4();
  1804. var descSort = function ( a, b ) {
  1805. return a.distance - b.distance;
  1806. };
  1807. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  1808. var distanceFromIntersection = function ( origin, direction, position ) {
  1809. v0.sub( position, origin );
  1810. var dot = v0.dot( direction );
  1811. var intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  1812. var distance = position.distanceTo( intersect );
  1813. return distance;
  1814. };
  1815. // http://www.blackpawn.com/texts/pointinpoly/default.html
  1816. var pointInFace3 = function ( p, a, b, c ) {
  1817. v0.sub( c, a );
  1818. v1.sub( b, a );
  1819. v2.sub( p, a );
  1820. var dot00 = v0.dot( v0 );
  1821. var dot01 = v0.dot( v1 );
  1822. var dot02 = v0.dot( v2 );
  1823. var dot11 = v1.dot( v1 );
  1824. var dot12 = v1.dot( v2 );
  1825. var invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  1826. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  1827. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  1828. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  1829. };
  1830. var intersectObject = function ( object, ray, intersects ) {
  1831. if ( object instanceof THREE.Particle ) {
  1832. var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1833. if ( distance > object.scale.x ) {
  1834. return intersects;
  1835. }
  1836. intersects.push( {
  1837. distance: distance,
  1838. point: object.position,
  1839. face: null,
  1840. object: object
  1841. } );
  1842. } else if ( object instanceof THREE.Mesh ) {
  1843. // Checking boundingSphere
  1844. var scaledRadius = object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis();
  1845. // Checking distance to ray
  1846. var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1847. if ( distance > scaledRadius) {
  1848. return intersects;
  1849. }
  1850. // Checking faces
  1851. var geometry = object.geometry;
  1852. var vertices = geometry.vertices;
  1853. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  1854. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  1855. var side = object.material.side;
  1856. var a, b, c, d;
  1857. var precision = ray.precision;
  1858. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  1859. originCopy.copy( ray.origin );
  1860. inverseMatrix.getInverse( object.matrixWorld );
  1861. localOriginCopy.copy( originCopy );
  1862. inverseMatrix.multiplyVector3( localOriginCopy );
  1863. localDirectionCopy.copy( ray.direction );
  1864. inverseMatrix.rotateAxis( localDirectionCopy ).normalize();
  1865. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  1866. var face = geometry.faces[ f ];
  1867. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  1868. if ( material === undefined ) continue;
  1869. side = material.side;
  1870. vector.sub( face.centroid, localOriginCopy );
  1871. var normal = face.normal;
  1872. var dot = localDirectionCopy.dot( normal );
  1873. // bail if ray and plane are parallel
  1874. if ( Math.abs( dot ) < precision ) continue;
  1875. // calc distance to plane
  1876. var scalar = normal.dot( vector ) / dot;
  1877. // if negative distance, then plane is behind ray
  1878. if ( scalar < 0 ) continue;
  1879. if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {
  1880. intersectPoint.add( localOriginCopy, localDirectionCopy.multiplyScalar( scalar ) );
  1881. if ( face instanceof THREE.Face3 ) {
  1882. a = vertices[ face.a ];
  1883. b = vertices[ face.b ];
  1884. c = vertices[ face.c ];
  1885. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  1886. var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1887. distance = originCopy.distanceTo( point );
  1888. if ( distance < ray.near || distance > ray.far ) continue;
  1889. intersects.push( {
  1890. distance: distance,
  1891. point: point,
  1892. face: face,
  1893. faceIndex: f,
  1894. object: object
  1895. } );
  1896. }
  1897. } else if ( face instanceof THREE.Face4 ) {
  1898. a = vertices[ face.a ];
  1899. b = vertices[ face.b ];
  1900. c = vertices[ face.c ];
  1901. d = vertices[ face.d ];
  1902. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  1903. var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1904. distance = originCopy.distanceTo( point );
  1905. if ( distance < ray.near || distance > ray.far ) continue;
  1906. intersects.push( {
  1907. distance: distance,
  1908. point: point,
  1909. face: face,
  1910. faceIndex: f,
  1911. object: object
  1912. } );
  1913. }
  1914. }
  1915. }
  1916. }
  1917. }
  1918. };
  1919. var intersectDescendants = function ( object, ray, intersects ) {
  1920. var descendants = object.getDescendants();
  1921. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  1922. intersectObject( descendants[ i ], ray, intersects );
  1923. }
  1924. };
  1925. //
  1926. THREE.Ray.prototype.precision = 0.0001;
  1927. THREE.Ray.prototype.set = function ( origin, direction ) {
  1928. this.origin = origin;
  1929. this.direction = direction;
  1930. };
  1931. THREE.Ray.prototype.intersectObject = function ( object, recursive ) {
  1932. var intersects = [];
  1933. if ( recursive === true ) {
  1934. intersectDescendants( object, this, intersects );
  1935. }
  1936. intersectObject( object, this, intersects );
  1937. intersects.sort( descSort );
  1938. return intersects;
  1939. };
  1940. THREE.Ray.prototype.intersectObjects = function ( objects, recursive ) {
  1941. var intersects = [];
  1942. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  1943. intersectObject( objects[ i ], this, intersects );
  1944. if ( recursive === true ) {
  1945. intersectDescendants( objects[ i ], this, intersects );
  1946. }
  1947. }
  1948. intersects.sort( descSort );
  1949. return intersects;
  1950. };
  1951. }( THREE ) );
  1952. /**
  1953. * @author mrdoob / http://mrdoob.com/
  1954. */
  1955. THREE.Rectangle = function () {
  1956. var _left = 0;
  1957. var _top = 0;
  1958. var _right = 0;
  1959. var _bottom = 0;
  1960. var _width = 0;
  1961. var _height = 0;
  1962. var _isEmpty = true;
  1963. function resize() {
  1964. _width = _right - _left;
  1965. _height = _bottom - _top;
  1966. }
  1967. this.getX = function () {
  1968. return _left;
  1969. };
  1970. this.getY = function () {
  1971. return _top;
  1972. };
  1973. this.getWidth = function () {
  1974. return _width;
  1975. };
  1976. this.getHeight = function () {
  1977. return _height;
  1978. };
  1979. this.getLeft = function() {
  1980. return _left;
  1981. };
  1982. this.getTop = function() {
  1983. return _top;
  1984. };
  1985. this.getRight = function() {
  1986. return _right;
  1987. };
  1988. this.getBottom = function() {
  1989. return _bottom;
  1990. };
  1991. this.set = function ( left, top, right, bottom ) {
  1992. _isEmpty = false;
  1993. _left = left; _top = top;
  1994. _right = right; _bottom = bottom;
  1995. resize();
  1996. };
  1997. this.addPoint = function ( x, y ) {
  1998. if ( _isEmpty === true ) {
  1999. _isEmpty = false;
  2000. _left = x; _top = y;
  2001. _right = x; _bottom = y;
  2002. resize();
  2003. } else {
  2004. _left = _left < x ? _left : x; // Math.min( _left, x );
  2005. _top = _top < y ? _top : y; // Math.min( _top, y );
  2006. _right = _right > x ? _right : x; // Math.max( _right, x );
  2007. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  2008. resize();
  2009. }
  2010. };
  2011. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  2012. if ( _isEmpty === true ) {
  2013. _isEmpty = false;
  2014. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  2015. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  2016. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  2017. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  2018. resize();
  2019. } else {
  2020. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  2021. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  2022. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  2023. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  2024. resize();
  2025. };
  2026. };
  2027. this.addRectangle = function ( r ) {
  2028. if ( _isEmpty === true ) {
  2029. _isEmpty = false;
  2030. _left = r.getLeft(); _top = r.getTop();
  2031. _right = r.getRight(); _bottom = r.getBottom();
  2032. resize();
  2033. } else {
  2034. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  2035. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  2036. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  2037. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  2038. resize();
  2039. }
  2040. };
  2041. this.inflate = function ( v ) {
  2042. _left -= v; _top -= v;
  2043. _right += v; _bottom += v;
  2044. resize();
  2045. };
  2046. this.minSelf = function ( r ) {
  2047. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  2048. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  2049. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  2050. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  2051. resize();
  2052. };
  2053. this.intersects = function ( r ) {
  2054. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  2055. if ( _right < r.getLeft() ) return false;
  2056. if ( _left > r.getRight() ) return false;
  2057. if ( _bottom < r.getTop() ) return false;
  2058. if ( _top > r.getBottom() ) return false;
  2059. return true;
  2060. };
  2061. this.empty = function () {
  2062. _isEmpty = true;
  2063. _left = 0; _top = 0;
  2064. _right = 0; _bottom = 0;
  2065. resize();
  2066. };
  2067. this.isEmpty = function () {
  2068. return _isEmpty;
  2069. };
  2070. };
  2071. /**
  2072. * @author alteredq / http://alteredqualia.com/
  2073. */
  2074. THREE.Math = {
  2075. // Clamp value to range <a, b>
  2076. clamp: function ( x, a, b ) {
  2077. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2078. },
  2079. // Clamp value to range <a, inf)
  2080. clampBottom: function ( x, a ) {
  2081. return x < a ? a : x;
  2082. },
  2083. // Linear mapping from range <a1, a2> to range <b1, b2>
  2084. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2085. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2086. },
  2087. // Random float from <0, 1> with 16 bits of randomness
  2088. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2089. random16: function () {
  2090. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2091. },
  2092. // Random integer from <low, high> interval
  2093. randInt: function ( low, high ) {
  2094. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2095. },
  2096. // Random float from <low, high> interval
  2097. randFloat: function ( low, high ) {
  2098. return low + Math.random() * ( high - low );
  2099. },
  2100. // Random float from <-range/2, range/2> interval
  2101. randFloatSpread: function ( range ) {
  2102. return range * ( 0.5 - Math.random() );
  2103. },
  2104. sign: function ( x ) {
  2105. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2106. }
  2107. };
  2108. /**
  2109. * @author mrdoob / http://mrdoob.com/
  2110. * @author mikael emtinger / http://gomo.se/
  2111. * @author alteredq / http://alteredqualia.com/
  2112. */
  2113. THREE.Object3D = function () {
  2114. THREE.Object3DLibrary.push( this );
  2115. this.id = THREE.Object3DIdCount ++;
  2116. this.name = '';
  2117. this.properties = {};
  2118. this.parent = undefined;
  2119. this.children = [];
  2120. this.up = new THREE.Vector3( 0, 1, 0 );
  2121. this.position = new THREE.Vector3();
  2122. this.rotation = new THREE.Vector3();
  2123. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  2124. this.scale = new THREE.Vector3( 1, 1, 1 );
  2125. this.renderDepth = null;
  2126. this.rotationAutoUpdate = true;
  2127. this.matrix = new THREE.Matrix4();
  2128. this.matrixWorld = new THREE.Matrix4();
  2129. this.matrixRotationWorld = new THREE.Matrix4();
  2130. this.matrixAutoUpdate = true;
  2131. this.matrixWorldNeedsUpdate = true;
  2132. this.quaternion = new THREE.Quaternion();
  2133. this.useQuaternion = false;
  2134. this.boundRadius = 0.0;
  2135. this.boundRadiusScale = 1.0;
  2136. this.visible = true;
  2137. this.castShadow = false;
  2138. this.receiveShadow = false;
  2139. this.frustumCulled = true;
  2140. this._vector = new THREE.Vector3();
  2141. };
  2142. THREE.Object3D.prototype = {
  2143. constructor: THREE.Object3D,
  2144. applyMatrix: function ( matrix ) {
  2145. this.matrix.multiply( matrix, this.matrix );
  2146. this.scale.getScaleFromMatrix( this.matrix );
  2147. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  2148. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  2149. this.position.getPositionFromMatrix( this.matrix );
  2150. },
  2151. translate: function ( distance, axis ) {
  2152. this.matrix.rotateAxis( axis );
  2153. this.position.addSelf( axis.multiplyScalar( distance ) );
  2154. },
  2155. translateX: function ( distance ) {
  2156. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  2157. },
  2158. translateY: function ( distance ) {
  2159. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  2160. },
  2161. translateZ: function ( distance ) {
  2162. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  2163. },
  2164. localToWorld: function ( vector ) {
  2165. return this.matrixWorld.multiplyVector3( vector );
  2166. },
  2167. worldToLocal: function ( vector ) {
  2168. return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
  2169. },
  2170. lookAt: function ( vector ) {
  2171. // TODO: Add hierarchy support.
  2172. this.matrix.lookAt( vector, this.position, this.up );
  2173. if ( this.rotationAutoUpdate ) {
  2174. if ( this.useQuaternion === false ) {
  2175. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  2176. } else {
  2177. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  2178. }
  2179. }
  2180. },
  2181. add: function ( object ) {
  2182. if ( object === this ) {
  2183. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  2184. return;
  2185. }
  2186. if ( object instanceof THREE.Object3D ) {
  2187. if ( object.parent !== undefined ) {
  2188. object.parent.remove( object );
  2189. }
  2190. object.parent = this;
  2191. this.children.push( object );
  2192. // add to scene
  2193. var scene = this;
  2194. while ( scene.parent !== undefined ) {
  2195. scene = scene.parent;
  2196. }
  2197. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2198. scene.__addObject( object );
  2199. }
  2200. }
  2201. },
  2202. remove: function ( object ) {
  2203. var index = this.children.indexOf( object );
  2204. if ( index !== - 1 ) {
  2205. object.parent = undefined;
  2206. this.children.splice( index, 1 );
  2207. // remove from scene
  2208. var scene = this;
  2209. while ( scene.parent !== undefined ) {
  2210. scene = scene.parent;
  2211. }
  2212. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2213. scene.__removeObject( object );
  2214. }
  2215. }
  2216. },
  2217. traverse: function ( callback ) {
  2218. callback( this );
  2219. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2220. this.children[ i ].traverse( callback );
  2221. }
  2222. },
  2223. getChildByName: function ( name, recursive ) {
  2224. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2225. var child = this.children[ i ];
  2226. if ( child.name === name ) {
  2227. return child;
  2228. }
  2229. if ( recursive === true ) {
  2230. child = child.getChildByName( name, recursive );
  2231. if ( child !== undefined ) {
  2232. return child;
  2233. }
  2234. }
  2235. }
  2236. return undefined;
  2237. },
  2238. getDescendants: function ( array ) {
  2239. if ( array === undefined ) array = [];
  2240. Array.prototype.push.apply( array, this.children );
  2241. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2242. this.children[ i ].getDescendants( array );
  2243. }
  2244. return array;
  2245. },
  2246. updateMatrix: function () {
  2247. this.matrix.setPosition( this.position );
  2248. if ( this.useQuaternion === false ) {
  2249. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  2250. } else {
  2251. this.matrix.setRotationFromQuaternion( this.quaternion );
  2252. }
  2253. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  2254. this.matrix.scale( this.scale );
  2255. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  2256. }
  2257. this.matrixWorldNeedsUpdate = true;
  2258. },
  2259. updateMatrixWorld: function ( force ) {
  2260. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  2261. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  2262. if ( this.parent === undefined ) {
  2263. this.matrixWorld.copy( this.matrix );
  2264. } else {
  2265. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2266. }
  2267. this.matrixWorldNeedsUpdate = false;
  2268. force = true;
  2269. }
  2270. // update children
  2271. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2272. this.children[ i ].updateMatrixWorld( force );
  2273. }
  2274. },
  2275. clone: function ( object ) {
  2276. if ( object === undefined ) object = new THREE.Object3D();
  2277. object.name = this.name;
  2278. object.up.copy( this.up );
  2279. object.position.copy( this.position );
  2280. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  2281. object.eulerOrder = this.eulerOrder;
  2282. object.scale.copy( this.scale );
  2283. object.renderDepth = this.renderDepth;
  2284. object.rotationAutoUpdate = this.rotationAutoUpdate;
  2285. object.matrix.copy( this.matrix );
  2286. object.matrixWorld.copy( this.matrixWorld );
  2287. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  2288. object.matrixAutoUpdate = this.matrixAutoUpdate;
  2289. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  2290. object.quaternion.copy( this.quaternion );
  2291. object.useQuaternion = this.useQuaternion;
  2292. object.boundRadius = this.boundRadius;
  2293. object.boundRadiusScale = this.boundRadiusScale;
  2294. object.visible = this.visible;
  2295. object.castShadow = this.castShadow;
  2296. object.receiveShadow = this.receiveShadow;
  2297. object.frustumCulled = this.frustumCulled;
  2298. for ( var i = 0; i < this.children.length; i ++ ) {
  2299. var child = this.children[ i ];
  2300. object.add( child.clone() );
  2301. }
  2302. return object;
  2303. },
  2304. deallocate: function () {
  2305. var index = THREE.Object3DLibrary.indexOf( this );
  2306. if ( index !== -1 ) THREE.Object3DLibrary.splice( index, 1 );
  2307. }
  2308. };
  2309. THREE.Object3D.__m1 = new THREE.Matrix4();
  2310. THREE.Object3D.defaultEulerOrder = 'XYZ',
  2311. THREE.Object3DIdCount = 0;
  2312. THREE.Object3DLibrary = [];
  2313. /**
  2314. * @author mrdoob / http://mrdoob.com/
  2315. * @author supereggbert / http://www.paulbrunt.co.uk/
  2316. * @author julianwa / https://github.com/julianwa
  2317. */
  2318. THREE.Projector = function() {
  2319. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  2320. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  2321. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  2322. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  2323. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  2324. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  2325. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  2326. _vector3 = new THREE.Vector3(),
  2327. _vector4 = new THREE.Vector4(),
  2328. _viewProjectionMatrix = new THREE.Matrix4(),
  2329. _modelViewProjectionMatrix = new THREE.Matrix4(),
  2330. _normalMatrix = new THREE.Matrix3(),
  2331. _frustum = new THREE.Frustum(),
  2332. _clippedVertex1PositionScreen = new THREE.Vector4(),
  2333. _clippedVertex2PositionScreen = new THREE.Vector4(),
  2334. _face3VertexNormals;
  2335. this.projectVector = function ( vector, camera ) {
  2336. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2337. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2338. _viewProjectionMatrix.multiplyVector3( vector );
  2339. return vector;
  2340. };
  2341. this.unprojectVector = function ( vector, camera ) {
  2342. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  2343. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  2344. _viewProjectionMatrix.multiplyVector3( vector );
  2345. return vector;
  2346. };
  2347. this.pickingRay = function ( vector, camera ) {
  2348. var end, ray, t;
  2349. // set two vectors with opposing z values
  2350. vector.z = -1.0;
  2351. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  2352. this.unprojectVector( vector, camera );
  2353. this.unprojectVector( end, camera );
  2354. // find direction from vector to end
  2355. end.subSelf( vector ).normalize();
  2356. return new THREE.Ray( vector, end );
  2357. };
  2358. var projectGraph = function ( root, sortObjects ) {
  2359. _objectCount = 0;
  2360. _renderData.objects.length = 0;
  2361. _renderData.sprites.length = 0;
  2362. _renderData.lights.length = 0;
  2363. var projectObject = function ( parent ) {
  2364. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  2365. var object = parent.children[ c ];
  2366. if ( object.visible === false ) continue;
  2367. if ( object instanceof THREE.Light ) {
  2368. _renderData.lights.push( object );
  2369. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  2370. if ( object.frustumCulled === false || _frustum.contains( object ) === true ) {
  2371. _object = getNextObjectInPool();
  2372. _object.object = object;
  2373. if ( object.renderDepth !== null ) {
  2374. _object.z = object.renderDepth;
  2375. } else {
  2376. _vector3.copy( object.matrixWorld.getPosition() );
  2377. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2378. _object.z = _vector3.z;
  2379. }
  2380. _renderData.objects.push( _object );
  2381. }
  2382. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  2383. _object = getNextObjectInPool();
  2384. _object.object = object;
  2385. // TODO: Find an elegant and performant solution and remove this dupe code.
  2386. if ( object.renderDepth !== null ) {
  2387. _object.z = object.renderDepth;
  2388. } else {
  2389. _vector3.copy( object.matrixWorld.getPosition() );
  2390. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2391. _object.z = _vector3.z;
  2392. }
  2393. _renderData.sprites.push( _object );
  2394. } else {
  2395. _object = getNextObjectInPool();
  2396. _object.object = object;
  2397. if ( object.renderDepth !== null ) {
  2398. _object.z = object.renderDepth;
  2399. } else {
  2400. _vector3.copy( object.matrixWorld.getPosition() );
  2401. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2402. _object.z = _vector3.z;
  2403. }
  2404. _renderData.objects.push( _object );
  2405. }
  2406. projectObject( object );
  2407. }
  2408. };
  2409. projectObject( root );
  2410. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  2411. return _renderData;
  2412. };
  2413. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  2414. var near = camera.near, far = camera.far, visible = false,
  2415. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object, modelMatrix,
  2416. geometry, vertices, vertex, vertexPositionScreen,
  2417. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  2418. v1, v2, v3, v4, isFaceMaterial, objectMaterials, material, side;
  2419. _face3Count = 0;
  2420. _face4Count = 0;
  2421. _lineCount = 0;
  2422. _particleCount = 0;
  2423. _renderData.elements.length = 0;
  2424. scene.updateMatrixWorld();
  2425. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  2426. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2427. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2428. _frustum.setFromMatrix( _viewProjectionMatrix );
  2429. _renderData = projectGraph( scene, sortObjects );
  2430. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  2431. object = _renderData.objects[ o ].object;
  2432. modelMatrix = object.matrixWorld;
  2433. _vertexCount = 0;
  2434. if ( object instanceof THREE.Mesh ) {
  2435. geometry = object.geometry;
  2436. vertices = geometry.vertices;
  2437. faces = geometry.faces;
  2438. faceVertexUvs = geometry.faceVertexUvs;
  2439. _normalMatrix.getInverse( modelMatrix );
  2440. _normalMatrix.transpose();
  2441. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  2442. objectMaterials = isFaceMaterial === true ? object.material : null;
  2443. side = object.material.side;
  2444. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  2445. _vertex = getNextVertexInPool();
  2446. _vertex.positionWorld.copy( vertices[ v ] );
  2447. modelMatrix.multiplyVector3( _vertex.positionWorld );
  2448. _vertex.positionScreen.copy( _vertex.positionWorld );
  2449. _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
  2450. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  2451. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  2452. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  2453. }
  2454. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  2455. face = faces[ f ];
  2456. material = isFaceMaterial === true ? objectMaterials.materials[ face.materialIndex ] : object.material;
  2457. if ( material === undefined ) continue;
  2458. side = material.side;
  2459. if ( face instanceof THREE.Face3 ) {
  2460. v1 = _vertexPool[ face.a ];
  2461. v2 = _vertexPool[ face.b ];
  2462. v3 = _vertexPool[ face.c ];
  2463. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  2464. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2465. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  2466. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2467. _face = getNextFace3InPool();
  2468. _face.v1.copy( v1 );
  2469. _face.v2.copy( v2 );
  2470. _face.v3.copy( v3 );
  2471. } else {
  2472. continue;
  2473. }
  2474. } else {
  2475. continue;
  2476. }
  2477. } else if ( face instanceof THREE.Face4 ) {
  2478. v1 = _vertexPool[ face.a ];
  2479. v2 = _vertexPool[ face.b ];
  2480. v3 = _vertexPool[ face.c ];
  2481. v4 = _vertexPool[ face.d ];
  2482. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  2483. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2484. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  2485. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  2486. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  2487. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2488. _face = getNextFace4InPool();
  2489. _face.v1.copy( v1 );
  2490. _face.v2.copy( v2 );
  2491. _face.v3.copy( v3 );
  2492. _face.v4.copy( v4 );
  2493. } else {
  2494. continue;
  2495. }
  2496. } else {
  2497. continue;
  2498. }
  2499. }
  2500. _face.normalWorld.copy( face.normal );
  2501. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
  2502. _normalMatrix.multiplyVector3( _face.normalWorld ).normalize();
  2503. _face.centroidWorld.copy( face.centroid );
  2504. modelMatrix.multiplyVector3( _face.centroidWorld );
  2505. _face.centroidScreen.copy( _face.centroidWorld );
  2506. _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
  2507. faceVertexNormals = face.vertexNormals;
  2508. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  2509. normal = _face.vertexNormalsWorld[ n ];
  2510. normal.copy( faceVertexNormals[ n ] );
  2511. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
  2512. _normalMatrix.multiplyVector3( normal ).normalize();
  2513. }
  2514. _face.vertexNormalsLength = faceVertexNormals.length;
  2515. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  2516. uvs = faceVertexUvs[ c ][ f ];
  2517. if ( uvs === undefined ) continue;
  2518. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  2519. _face.uvs[ c ][ u ] = uvs[ u ];
  2520. }
  2521. }
  2522. _face.color = face.color;
  2523. _face.material = material;
  2524. _face.z = _face.centroidScreen.z;
  2525. _renderData.elements.push( _face );
  2526. }
  2527. } else if ( object instanceof THREE.Line ) {
  2528. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
  2529. vertices = object.geometry.vertices;
  2530. v1 = getNextVertexInPool();
  2531. v1.positionScreen.copy( vertices[ 0 ] );
  2532. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2533. // Handle LineStrip and LinePieces
  2534. var step = object.type === THREE.LinePieces ? 2 : 1;
  2535. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2536. v1 = getNextVertexInPool();
  2537. v1.positionScreen.copy( vertices[ v ] );
  2538. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2539. if ( ( v + 1 ) % step > 0 ) continue;
  2540. v2 = _vertexPool[ _vertexCount - 2 ];
  2541. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2542. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2543. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  2544. // Perform the perspective divide
  2545. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2546. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2547. _line = getNextLineInPool();
  2548. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2549. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2550. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2551. _line.material = object.material;
  2552. _renderData.elements.push( _line );
  2553. }
  2554. }
  2555. }
  2556. }
  2557. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2558. object = _renderData.sprites[ o ].object;
  2559. modelMatrix = object.matrixWorld;
  2560. if ( object instanceof THREE.Particle ) {
  2561. _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
  2562. _viewProjectionMatrix.multiplyVector4( _vector4 );
  2563. _vector4.z /= _vector4.w;
  2564. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2565. _particle = getNextParticleInPool();
  2566. _particle.object = object;
  2567. _particle.x = _vector4.x / _vector4.w;
  2568. _particle.y = _vector4.y / _vector4.w;
  2569. _particle.z = _vector4.z;
  2570. _particle.rotation = object.rotation.z;
  2571. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2572. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2573. _particle.material = object.material;
  2574. _renderData.elements.push( _particle );
  2575. }
  2576. }
  2577. }
  2578. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  2579. return _renderData;
  2580. };
  2581. // Pools
  2582. function getNextObjectInPool() {
  2583. if ( _objectCount === _objectPoolLength ) {
  2584. var object = new THREE.RenderableObject();
  2585. _objectPool.push( object );
  2586. _objectPoolLength ++;
  2587. _objectCount ++;
  2588. return object;
  2589. }
  2590. return _objectPool[ _objectCount ++ ];
  2591. }
  2592. function getNextVertexInPool() {
  2593. if ( _vertexCount === _vertexPoolLength ) {
  2594. var vertex = new THREE.RenderableVertex();
  2595. _vertexPool.push( vertex );
  2596. _vertexPoolLength ++;
  2597. _vertexCount ++;
  2598. return vertex;
  2599. }
  2600. return _vertexPool[ _vertexCount ++ ];
  2601. }
  2602. function getNextFace3InPool() {
  2603. if ( _face3Count === _face3PoolLength ) {
  2604. var face = new THREE.RenderableFace3();
  2605. _face3Pool.push( face );
  2606. _face3PoolLength ++;
  2607. _face3Count ++;
  2608. return face;
  2609. }
  2610. return _face3Pool[ _face3Count ++ ];
  2611. }
  2612. function getNextFace4InPool() {
  2613. if ( _face4Count === _face4PoolLength ) {
  2614. var face = new THREE.RenderableFace4();
  2615. _face4Pool.push( face );
  2616. _face4PoolLength ++;
  2617. _face4Count ++;
  2618. return face;
  2619. }
  2620. return _face4Pool[ _face4Count ++ ];
  2621. }
  2622. function getNextLineInPool() {
  2623. if ( _lineCount === _linePoolLength ) {
  2624. var line = new THREE.RenderableLine();
  2625. _linePool.push( line );
  2626. _linePoolLength ++;
  2627. _lineCount ++
  2628. return line;
  2629. }
  2630. return _linePool[ _lineCount ++ ];
  2631. }
  2632. function getNextParticleInPool() {
  2633. if ( _particleCount === _particlePoolLength ) {
  2634. var particle = new THREE.RenderableParticle();
  2635. _particlePool.push( particle );
  2636. _particlePoolLength ++;
  2637. _particleCount ++
  2638. return particle;
  2639. }
  2640. return _particlePool[ _particleCount ++ ];
  2641. }
  2642. //
  2643. function painterSort( a, b ) {
  2644. return b.z - a.z;
  2645. }
  2646. function clipLine( s1, s2 ) {
  2647. var alpha1 = 0, alpha2 = 1,
  2648. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2649. // Z = -1 and Z = +1, respectively.
  2650. bc1near = s1.z + s1.w,
  2651. bc2near = s2.z + s2.w,
  2652. bc1far = - s1.z + s1.w,
  2653. bc2far = - s2.z + s2.w;
  2654. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2655. // Both vertices lie entirely within all clip planes.
  2656. return true;
  2657. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2658. // Both vertices lie entirely outside one of the clip planes.
  2659. return false;
  2660. } else {
  2661. // The line segment spans at least one clip plane.
  2662. if ( bc1near < 0 ) {
  2663. // v1 lies outside the near plane, v2 inside
  2664. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2665. } else if ( bc2near < 0 ) {
  2666. // v2 lies outside the near plane, v1 inside
  2667. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2668. }
  2669. if ( bc1far < 0 ) {
  2670. // v1 lies outside the far plane, v2 inside
  2671. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2672. } else if ( bc2far < 0 ) {
  2673. // v2 lies outside the far plane, v2 inside
  2674. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2675. }
  2676. if ( alpha2 < alpha1 ) {
  2677. // The line segment spans two boundaries, but is outside both of them.
  2678. // (This can't happen when we're only clipping against just near/far but good
  2679. // to leave the check here for future usage if other clip planes are added.)
  2680. return false;
  2681. } else {
  2682. // Update the s1 and s2 vertices to match the clipped line segment.
  2683. s1.lerpSelf( s2, alpha1 );
  2684. s2.lerpSelf( s1, 1 - alpha2 );
  2685. return true;
  2686. }
  2687. }
  2688. }
  2689. };
  2690. /**
  2691. * @author mikael emtinger / http://gomo.se/
  2692. * @author alteredq / http://alteredqualia.com/
  2693. * @author WestLangley / http://github.com/WestLangley
  2694. */
  2695. THREE.Quaternion = function( x, y, z, w ) {
  2696. this.x = x || 0;
  2697. this.y = y || 0;
  2698. this.z = z || 0;
  2699. this.w = ( w !== undefined ) ? w : 1;
  2700. };
  2701. THREE.Quaternion.prototype = {
  2702. constructor: THREE.Quaternion,
  2703. set: function ( x, y, z, w ) {
  2704. this.x = x;
  2705. this.y = y;
  2706. this.z = z;
  2707. this.w = w;
  2708. return this;
  2709. },
  2710. copy: function ( q ) {
  2711. this.x = q.x;
  2712. this.y = q.y;
  2713. this.z = q.z;
  2714. this.w = q.w;
  2715. return this;
  2716. },
  2717. setFromEuler: function ( v, order ) {
  2718. // http://www.mathworks.com/matlabcentral/fileexchange/
  2719. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2720. // content/SpinCalc.m
  2721. var c1 = Math.cos( v.x / 2 );
  2722. var c2 = Math.cos( v.y / 2 );
  2723. var c3 = Math.cos( v.z / 2 );
  2724. var s1 = Math.sin( v.x / 2 );
  2725. var s2 = Math.sin( v.y / 2 );
  2726. var s3 = Math.sin( v.z / 2 );
  2727. if ( order === undefined || order === 'XYZ' ) {
  2728. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2729. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2730. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2731. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2732. } else if ( order === 'YXZ' ) {
  2733. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2734. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2735. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2736. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2737. } else if ( order === 'ZXY' ) {
  2738. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2739. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2740. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2741. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2742. } else if ( order === 'ZYX' ) {
  2743. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2744. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2745. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2746. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2747. } else if ( order === 'YZX' ) {
  2748. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2749. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2750. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2751. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2752. } else if ( order === 'XZY' ) {
  2753. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2754. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2755. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2756. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2757. }
  2758. return this;
  2759. },
  2760. setFromAxisAngle: function ( axis, angle ) {
  2761. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2762. // axis have to be normalized
  2763. var halfAngle = angle / 2,
  2764. s = Math.sin( halfAngle );
  2765. this.x = axis.x * s;
  2766. this.y = axis.y * s;
  2767. this.z = axis.z * s;
  2768. this.w = Math.cos( halfAngle );
  2769. return this;
  2770. },
  2771. setFromRotationMatrix: function ( m ) {
  2772. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2773. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2774. var te = m.elements,
  2775. m11 = te[0], m12 = te[4], m13 = te[8],
  2776. m21 = te[1], m22 = te[5], m23 = te[9],
  2777. m31 = te[2], m32 = te[6], m33 = te[10],
  2778. trace = m11 + m22 + m33,
  2779. s;
  2780. if( trace > 0 ) {
  2781. s = 0.5 / Math.sqrt( trace + 1.0 );
  2782. this.w = 0.25 / s;
  2783. this.x = ( m32 - m23 ) * s;
  2784. this.y = ( m13 - m31 ) * s;
  2785. this.z = ( m21 - m12 ) * s;
  2786. } else if ( m11 > m22 && m11 > m33 ) {
  2787. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2788. this.w = (m32 - m23 ) / s;
  2789. this.x = 0.25 * s;
  2790. this.y = (m12 + m21 ) / s;
  2791. this.z = (m13 + m31 ) / s;
  2792. } else if (m22 > m33) {
  2793. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2794. this.w = (m13 - m31 ) / s;
  2795. this.x = (m12 + m21 ) / s;
  2796. this.y = 0.25 * s;
  2797. this.z = (m23 + m32 ) / s;
  2798. } else {
  2799. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2800. this.w = ( m21 - m12 ) / s;
  2801. this.x = ( m13 + m31 ) / s;
  2802. this.y = ( m23 + m32 ) / s;
  2803. this.z = 0.25 * s;
  2804. }
  2805. return this;
  2806. },
  2807. inverse: function () {
  2808. this.conjugate().normalize();
  2809. return this;
  2810. },
  2811. conjugate: function () {
  2812. this.x *= -1;
  2813. this.y *= -1;
  2814. this.z *= -1;
  2815. return this;
  2816. },
  2817. length: function () {
  2818. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2819. },
  2820. normalize: function () {
  2821. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2822. if ( l === 0 ) {
  2823. this.x = 0;
  2824. this.y = 0;
  2825. this.z = 0;
  2826. this.w = 1;
  2827. } else {
  2828. l = 1 / l;
  2829. this.x = this.x * l;
  2830. this.y = this.y * l;
  2831. this.z = this.z * l;
  2832. this.w = this.w * l;
  2833. }
  2834. return this;
  2835. },
  2836. multiply: function ( a, b ) {
  2837. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2838. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
  2839. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2840. this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
  2841. this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
  2842. this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
  2843. this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
  2844. return this;
  2845. },
  2846. multiplySelf: function ( b ) {
  2847. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2848. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2849. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2850. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2851. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2852. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2853. return this;
  2854. },
  2855. multiplyVector3: function ( vector, dest ) {
  2856. if ( !dest ) { dest = vector; }
  2857. var x = vector.x, y = vector.y, z = vector.z,
  2858. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2859. // calculate quat * vector
  2860. var ix = qw * x + qy * z - qz * y,
  2861. iy = qw * y + qz * x - qx * z,
  2862. iz = qw * z + qx * y - qy * x,
  2863. iw = -qx * x - qy * y - qz * z;
  2864. // calculate result * inverse quat
  2865. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2866. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2867. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2868. return dest;
  2869. },
  2870. slerpSelf: function ( qb, t ) {
  2871. var x = this.x, y = this.y, z = this.z, w = this.w;
  2872. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2873. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  2874. if ( cosHalfTheta < 0 ) {
  2875. this.w = -qb.w;
  2876. this.x = -qb.x;
  2877. this.y = -qb.y;
  2878. this.z = -qb.z;
  2879. cosHalfTheta = -cosHalfTheta;
  2880. } else {
  2881. this.copy( qb );
  2882. }
  2883. if ( cosHalfTheta >= 1.0 ) {
  2884. this.w = w;
  2885. this.x = x;
  2886. this.y = y;
  2887. this.z = z;
  2888. return this;
  2889. }
  2890. var halfTheta = Math.acos( cosHalfTheta );
  2891. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2892. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2893. this.w = 0.5 * ( w + this.w );
  2894. this.x = 0.5 * ( x + this.x );
  2895. this.y = 0.5 * ( y + this.y );
  2896. this.z = 0.5 * ( z + this.z );
  2897. return this;
  2898. }
  2899. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2900. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2901. this.w = ( w * ratioA + this.w * ratioB );
  2902. this.x = ( x * ratioA + this.x * ratioB );
  2903. this.y = ( y * ratioA + this.y * ratioB );
  2904. this.z = ( z * ratioA + this.z * ratioB );
  2905. return this;
  2906. },
  2907. clone: function () {
  2908. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2909. }
  2910. }
  2911. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2912. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2913. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2914. if ( cosHalfTheta < 0 ) {
  2915. qm.w = -qb.w;
  2916. qm.x = -qb.x;
  2917. qm.y = -qb.y;
  2918. qm.z = -qb.z;
  2919. cosHalfTheta = -cosHalfTheta;
  2920. } else {
  2921. qm.copy( qb );
  2922. }
  2923. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2924. qm.w = qa.w;
  2925. qm.x = qa.x;
  2926. qm.y = qa.y;
  2927. qm.z = qa.z;
  2928. return qm;
  2929. }
  2930. var halfTheta = Math.acos( cosHalfTheta );
  2931. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2932. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2933. qm.w = 0.5 * ( qa.w + qm.w );
  2934. qm.x = 0.5 * ( qa.x + qm.x );
  2935. qm.y = 0.5 * ( qa.y + qm.y );
  2936. qm.z = 0.5 * ( qa.z + qm.z );
  2937. return qm;
  2938. }
  2939. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
  2940. var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2941. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2942. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2943. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2944. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2945. return qm;
  2946. }
  2947. /**
  2948. * @author mrdoob / http://mrdoob.com/
  2949. */
  2950. THREE.Vertex = function ( v ) {
  2951. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  2952. return v;
  2953. };
  2954. /**
  2955. * @author mrdoob / http://mrdoob.com/
  2956. * @author alteredq / http://alteredqualia.com/
  2957. */
  2958. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  2959. this.a = a;
  2960. this.b = b;
  2961. this.c = c;
  2962. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2963. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2964. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2965. this.vertexColors = color instanceof Array ? color : [];
  2966. this.vertexTangents = [];
  2967. this.materialIndex = materialIndex;
  2968. this.centroid = new THREE.Vector3();
  2969. };
  2970. THREE.Face3.prototype = {
  2971. constructor: THREE.Face3,
  2972. clone: function () {
  2973. var face = new THREE.Face3( this.a, this.b, this.c );
  2974. face.normal.copy( this.normal );
  2975. face.color.copy( this.color );
  2976. face.centroid.copy( this.centroid );
  2977. face.materialIndex = this.materialIndex;
  2978. var i, il;
  2979. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2980. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2981. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2982. return face;
  2983. }
  2984. };
  2985. /**
  2986. * @author mrdoob / http://mrdoob.com/
  2987. * @author alteredq / http://alteredqualia.com/
  2988. */
  2989. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  2990. this.a = a;
  2991. this.b = b;
  2992. this.c = c;
  2993. this.d = d;
  2994. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2995. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2996. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2997. this.vertexColors = color instanceof Array ? color : [];
  2998. this.vertexTangents = [];
  2999. this.materialIndex = materialIndex;
  3000. this.centroid = new THREE.Vector3();
  3001. };
  3002. THREE.Face4.prototype = {
  3003. constructor: THREE.Face4,
  3004. clone: function () {
  3005. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  3006. face.normal.copy( this.normal );
  3007. face.color.copy( this.color );
  3008. face.centroid.copy( this.centroid );
  3009. face.materialIndex = this.materialIndex;
  3010. var i, il;
  3011. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  3012. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  3013. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  3014. return face;
  3015. }
  3016. };
  3017. /**
  3018. * @author mrdoob / http://mrdoob.com/
  3019. */
  3020. THREE.UV = function ( u, v ) {
  3021. this.u = u || 0;
  3022. this.v = v || 0;
  3023. };
  3024. THREE.UV.prototype = {
  3025. constructor: THREE.UV,
  3026. set: function ( u, v ) {
  3027. this.u = u;
  3028. this.v = v;
  3029. return this;
  3030. },
  3031. copy: function ( uv ) {
  3032. this.u = uv.u;
  3033. this.v = uv.v;
  3034. return this;
  3035. },
  3036. lerpSelf: function ( uv, alpha ) {
  3037. this.u += ( uv.u - this.u ) * alpha;
  3038. this.v += ( uv.v - this.v ) * alpha;
  3039. return this;
  3040. },
  3041. clone: function () {
  3042. return new THREE.UV( this.u, this.v );
  3043. }
  3044. };
  3045. /**
  3046. * @author mrdoob / http://mrdoob.com/
  3047. * @author kile / http://kile.stravaganza.org/
  3048. * @author alteredq / http://alteredqualia.com/
  3049. * @author mikael emtinger / http://gomo.se/
  3050. * @author zz85 / http://www.lab4games.net/zz85/blog
  3051. */
  3052. THREE.Geometry = function () {
  3053. THREE.GeometryLibrary.push( this );
  3054. this.id = THREE.GeometryIdCount ++;
  3055. this.name = '';
  3056. this.vertices = [];
  3057. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  3058. this.normals = []; // one-to-one vertex normals, used in Ribbon
  3059. this.faces = [];
  3060. this.faceUvs = [[]];
  3061. this.faceVertexUvs = [[]];
  3062. this.morphTargets = [];
  3063. this.morphColors = [];
  3064. this.morphNormals = [];
  3065. this.skinWeights = [];
  3066. this.skinIndices = [];
  3067. this.lineDistances = [];
  3068. this.boundingBox = null;
  3069. this.boundingSphere = null;
  3070. this.hasTangents = false;
  3071. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  3072. // update flags
  3073. this.verticesNeedUpdate = false;
  3074. this.elementsNeedUpdate = false;
  3075. this.uvsNeedUpdate = false;
  3076. this.normalsNeedUpdate = false;
  3077. this.tangentsNeedUpdate = false;
  3078. this.colorsNeedUpdate = false;
  3079. this.lineDistancesNeedUpdate = false;
  3080. this.buffersNeedUpdate = false;
  3081. };
  3082. THREE.Geometry.prototype = {
  3083. constructor : THREE.Geometry,
  3084. applyMatrix: function ( matrix ) {
  3085. var normalMatrix = new THREE.Matrix3();
  3086. normalMatrix.getInverse( matrix ).transpose();
  3087. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  3088. var vertex = this.vertices[ i ];
  3089. matrix.multiplyVector3( vertex );
  3090. }
  3091. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  3092. var face = this.faces[ i ];
  3093. normalMatrix.multiplyVector3( face.normal ).normalize();
  3094. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  3095. normalMatrix.multiplyVector3( face.vertexNormals[ j ] ).normalize();
  3096. }
  3097. matrix.multiplyVector3( face.centroid );
  3098. }
  3099. },
  3100. computeCentroids: function () {
  3101. var f, fl, face;
  3102. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3103. face = this.faces[ f ];
  3104. face.centroid.set( 0, 0, 0 );
  3105. if ( face instanceof THREE.Face3 ) {
  3106. face.centroid.addSelf( this.vertices[ face.a ] );
  3107. face.centroid.addSelf( this.vertices[ face.b ] );
  3108. face.centroid.addSelf( this.vertices[ face.c ] );
  3109. face.centroid.divideScalar( 3 );
  3110. } else if ( face instanceof THREE.Face4 ) {
  3111. face.centroid.addSelf( this.vertices[ face.a ] );
  3112. face.centroid.addSelf( this.vertices[ face.b ] );
  3113. face.centroid.addSelf( this.vertices[ face.c ] );
  3114. face.centroid.addSelf( this.vertices[ face.d ] );
  3115. face.centroid.divideScalar( 4 );
  3116. }
  3117. }
  3118. },
  3119. computeFaceNormals: function () {
  3120. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  3121. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  3122. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3123. face = this.faces[ f ];
  3124. vA = this.vertices[ face.a ];
  3125. vB = this.vertices[ face.b ];
  3126. vC = this.vertices[ face.c ];
  3127. cb.sub( vC, vB );
  3128. ab.sub( vA, vB );
  3129. cb.crossSelf( ab );
  3130. cb.normalize();
  3131. face.normal.copy( cb );
  3132. }
  3133. },
  3134. computeVertexNormals: function ( areaWeighted ) {
  3135. var v, vl, f, fl, face, vertices;
  3136. // create internal buffers for reuse when calling this method repeatedly
  3137. // (otherwise memory allocation / deallocation every frame is big resource hog)
  3138. if ( this.__tmpVertices === undefined ) {
  3139. this.__tmpVertices = new Array( this.vertices.length );
  3140. vertices = this.__tmpVertices;
  3141. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3142. vertices[ v ] = new THREE.Vector3();
  3143. }
  3144. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3145. face = this.faces[ f ];
  3146. if ( face instanceof THREE.Face3 ) {
  3147. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3148. } else if ( face instanceof THREE.Face4 ) {
  3149. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3150. }
  3151. }
  3152. } else {
  3153. vertices = this.__tmpVertices;
  3154. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3155. vertices[ v ].set( 0, 0, 0 );
  3156. }
  3157. }
  3158. if ( areaWeighted ) {
  3159. // vertex normals weighted by triangle areas
  3160. // http://www.iquilezles.org/www/articles/normals/normals.htm
  3161. var vA, vB, vC, vD;
  3162. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  3163. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  3164. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3165. face = this.faces[ f ];
  3166. if ( face instanceof THREE.Face3 ) {
  3167. vA = this.vertices[ face.a ];
  3168. vB = this.vertices[ face.b ];
  3169. vC = this.vertices[ face.c ];
  3170. cb.sub( vC, vB );
  3171. ab.sub( vA, vB );
  3172. cb.crossSelf( ab );
  3173. vertices[ face.a ].addSelf( cb );
  3174. vertices[ face.b ].addSelf( cb );
  3175. vertices[ face.c ].addSelf( cb );
  3176. } else if ( face instanceof THREE.Face4 ) {
  3177. vA = this.vertices[ face.a ];
  3178. vB = this.vertices[ face.b ];
  3179. vC = this.vertices[ face.c ];
  3180. vD = this.vertices[ face.d ];
  3181. // abd
  3182. db.sub( vD, vB );
  3183. ab.sub( vA, vB );
  3184. db.crossSelf( ab );
  3185. vertices[ face.a ].addSelf( db );
  3186. vertices[ face.b ].addSelf( db );
  3187. vertices[ face.d ].addSelf( db );
  3188. // bcd
  3189. dc.sub( vD, vC );
  3190. bc.sub( vB, vC );
  3191. dc.crossSelf( bc );
  3192. vertices[ face.b ].addSelf( dc );
  3193. vertices[ face.c ].addSelf( dc );
  3194. vertices[ face.d ].addSelf( dc );
  3195. }
  3196. }
  3197. } else {
  3198. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3199. face = this.faces[ f ];
  3200. if ( face instanceof THREE.Face3 ) {
  3201. vertices[ face.a ].addSelf( face.normal );
  3202. vertices[ face.b ].addSelf( face.normal );
  3203. vertices[ face.c ].addSelf( face.normal );
  3204. } else if ( face instanceof THREE.Face4 ) {
  3205. vertices[ face.a ].addSelf( face.normal );
  3206. vertices[ face.b ].addSelf( face.normal );
  3207. vertices[ face.c ].addSelf( face.normal );
  3208. vertices[ face.d ].addSelf( face.normal );
  3209. }
  3210. }
  3211. }
  3212. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3213. vertices[ v ].normalize();
  3214. }
  3215. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3216. face = this.faces[ f ];
  3217. if ( face instanceof THREE.Face3 ) {
  3218. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3219. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3220. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3221. } else if ( face instanceof THREE.Face4 ) {
  3222. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3223. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3224. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3225. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  3226. }
  3227. }
  3228. },
  3229. computeMorphNormals: function () {
  3230. var i, il, f, fl, face;
  3231. // save original normals
  3232. // - create temp variables on first access
  3233. // otherwise just copy (for faster repeated calls)
  3234. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3235. face = this.faces[ f ];
  3236. if ( ! face.__originalFaceNormal ) {
  3237. face.__originalFaceNormal = face.normal.clone();
  3238. } else {
  3239. face.__originalFaceNormal.copy( face.normal );
  3240. }
  3241. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  3242. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  3243. if ( ! face.__originalVertexNormals[ i ] ) {
  3244. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  3245. } else {
  3246. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  3247. }
  3248. }
  3249. }
  3250. // use temp geometry to compute face and vertex normals for each morph
  3251. var tmpGeo = new THREE.Geometry();
  3252. tmpGeo.faces = this.faces;
  3253. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  3254. // create on first access
  3255. if ( ! this.morphNormals[ i ] ) {
  3256. this.morphNormals[ i ] = {};
  3257. this.morphNormals[ i ].faceNormals = [];
  3258. this.morphNormals[ i ].vertexNormals = [];
  3259. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  3260. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  3261. var faceNormal, vertexNormals;
  3262. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3263. face = this.faces[ f ];
  3264. faceNormal = new THREE.Vector3();
  3265. if ( face instanceof THREE.Face3 ) {
  3266. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  3267. } else {
  3268. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  3269. }
  3270. dstNormalsFace.push( faceNormal );
  3271. dstNormalsVertex.push( vertexNormals );
  3272. }
  3273. }
  3274. var morphNormals = this.morphNormals[ i ];
  3275. // set vertices to morph target
  3276. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  3277. // compute morph normals
  3278. tmpGeo.computeFaceNormals();
  3279. tmpGeo.computeVertexNormals();
  3280. // store morph normals
  3281. var faceNormal, vertexNormals;
  3282. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3283. face = this.faces[ f ];
  3284. faceNormal = morphNormals.faceNormals[ f ];
  3285. vertexNormals = morphNormals.vertexNormals[ f ];
  3286. faceNormal.copy( face.normal );
  3287. if ( face instanceof THREE.Face3 ) {
  3288. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3289. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3290. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3291. } else {
  3292. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3293. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3294. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3295. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  3296. }
  3297. }
  3298. }
  3299. // restore original normals
  3300. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3301. face = this.faces[ f ];
  3302. face.normal = face.__originalFaceNormal;
  3303. face.vertexNormals = face.__originalVertexNormals;
  3304. }
  3305. },
  3306. computeTangents: function () {
  3307. // based on http://www.terathon.com/code/tangent.html
  3308. // tangents go to vertices
  3309. var f, fl, v, vl, i, il, vertexIndex,
  3310. face, uv, vA, vB, vC, uvA, uvB, uvC,
  3311. x1, x2, y1, y2, z1, z2,
  3312. s1, s2, t1, t2, r, t, test,
  3313. tan1 = [], tan2 = [],
  3314. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  3315. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  3316. n = new THREE.Vector3(), w;
  3317. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3318. tan1[ v ] = new THREE.Vector3();
  3319. tan2[ v ] = new THREE.Vector3();
  3320. }
  3321. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  3322. vA = context.vertices[ a ];
  3323. vB = context.vertices[ b ];
  3324. vC = context.vertices[ c ];
  3325. uvA = uv[ ua ];
  3326. uvB = uv[ ub ];
  3327. uvC = uv[ uc ];
  3328. x1 = vB.x - vA.x;
  3329. x2 = vC.x - vA.x;
  3330. y1 = vB.y - vA.y;
  3331. y2 = vC.y - vA.y;
  3332. z1 = vB.z - vA.z;
  3333. z2 = vC.z - vA.z;
  3334. s1 = uvB.u - uvA.u;
  3335. s2 = uvC.u - uvA.u;
  3336. t1 = uvB.v - uvA.v;
  3337. t2 = uvC.v - uvA.v;
  3338. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3339. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  3340. ( t2 * y1 - t1 * y2 ) * r,
  3341. ( t2 * z1 - t1 * z2 ) * r );
  3342. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  3343. ( s1 * y2 - s2 * y1 ) * r,
  3344. ( s1 * z2 - s2 * z1 ) * r );
  3345. tan1[ a ].addSelf( sdir );
  3346. tan1[ b ].addSelf( sdir );
  3347. tan1[ c ].addSelf( sdir );
  3348. tan2[ a ].addSelf( tdir );
  3349. tan2[ b ].addSelf( tdir );
  3350. tan2[ c ].addSelf( tdir );
  3351. }
  3352. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3353. face = this.faces[ f ];
  3354. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  3355. if ( face instanceof THREE.Face3 ) {
  3356. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  3357. } else if ( face instanceof THREE.Face4 ) {
  3358. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  3359. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  3360. }
  3361. }
  3362. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  3363. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3364. face = this.faces[ f ];
  3365. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  3366. n.copy( face.vertexNormals[ i ] );
  3367. vertexIndex = face[ faceIndex[ i ] ];
  3368. t = tan1[ vertexIndex ];
  3369. // Gram-Schmidt orthogonalize
  3370. tmp.copy( t );
  3371. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3372. // Calculate handedness
  3373. tmp2.cross( face.vertexNormals[ i ], t );
  3374. test = tmp2.dot( tan2[ vertexIndex ] );
  3375. w = (test < 0.0) ? -1.0 : 1.0;
  3376. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  3377. }
  3378. }
  3379. this.hasTangents = true;
  3380. },
  3381. computeLineDistances: function ( ) {
  3382. var d = 0;
  3383. var vertices = this.vertices;
  3384. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  3385. if ( i > 0 ) {
  3386. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  3387. }
  3388. this.lineDistances[ i ] = d;
  3389. }
  3390. },
  3391. computeBoundingBox: function () {
  3392. if ( ! this.boundingBox ) {
  3393. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  3394. }
  3395. if ( this.vertices.length > 0 ) {
  3396. var position, firstPosition = this.vertices[ 0 ];
  3397. this.boundingBox.min.copy( firstPosition );
  3398. this.boundingBox.max.copy( firstPosition );
  3399. var min = this.boundingBox.min,
  3400. max = this.boundingBox.max;
  3401. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  3402. position = this.vertices[ v ];
  3403. if ( position.x < min.x ) {
  3404. min.x = position.x;
  3405. } else if ( position.x > max.x ) {
  3406. max.x = position.x;
  3407. }
  3408. if ( position.y < min.y ) {
  3409. min.y = position.y;
  3410. } else if ( position.y > max.y ) {
  3411. max.y = position.y;
  3412. }
  3413. if ( position.z < min.z ) {
  3414. min.z = position.z;
  3415. } else if ( position.z > max.z ) {
  3416. max.z = position.z;
  3417. }
  3418. }
  3419. } else {
  3420. this.boundingBox.min.set( 0, 0, 0 );
  3421. this.boundingBox.max.set( 0, 0, 0 );
  3422. }
  3423. },
  3424. computeBoundingSphere: function () {
  3425. var maxRadiusSq = 0;
  3426. if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };
  3427. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  3428. var radiusSq = this.vertices[ i ].lengthSq();
  3429. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3430. }
  3431. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3432. },
  3433. /*
  3434. * Checks for duplicate vertices with hashmap.
  3435. * Duplicated vertices are removed
  3436. * and faces' vertices are updated.
  3437. */
  3438. mergeVertices: function () {
  3439. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  3440. var unique = [], changes = [];
  3441. var v, key;
  3442. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  3443. var precision = Math.pow( 10, precisionPoints );
  3444. var i,il, face;
  3445. var abcd = 'abcd', o, k, j, jl, u;
  3446. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  3447. v = this.vertices[ i ];
  3448. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  3449. if ( verticesMap[ key ] === undefined ) {
  3450. verticesMap[ key ] = i;
  3451. unique.push( this.vertices[ i ] );
  3452. changes[ i ] = unique.length - 1;
  3453. } else {
  3454. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  3455. changes[ i ] = changes[ verticesMap[ key ] ];
  3456. }
  3457. };
  3458. // Start to patch face indices
  3459. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  3460. face = this.faces[ i ];
  3461. if ( face instanceof THREE.Face3 ) {
  3462. face.a = changes[ face.a ];
  3463. face.b = changes[ face.b ];
  3464. face.c = changes[ face.c ];
  3465. } else if ( face instanceof THREE.Face4 ) {
  3466. face.a = changes[ face.a ];
  3467. face.b = changes[ face.b ];
  3468. face.c = changes[ face.c ];
  3469. face.d = changes[ face.d ];
  3470. // check dups in (a, b, c, d) and convert to -> face3
  3471. o = [ face.a, face.b, face.c, face.d ];
  3472. for ( k = 3; k > 0; k -- ) {
  3473. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  3474. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  3475. o.splice( k, 1 );
  3476. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  3477. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  3478. u = this.faceVertexUvs[ j ][ i ];
  3479. if ( u ) u.splice( k, 1 );
  3480. }
  3481. this.faces[ i ].vertexColors = face.vertexColors;
  3482. break;
  3483. }
  3484. }
  3485. }
  3486. }
  3487. // Use unique set of vertices
  3488. var diff = this.vertices.length - unique.length;
  3489. this.vertices = unique;
  3490. return diff;
  3491. },
  3492. clone: function () {
  3493. var geometry = new THREE.Geometry();
  3494. var vertices = this.vertices;
  3495. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  3496. geometry.vertices.push( vertices[ i ].clone() );
  3497. }
  3498. var faces = this.faces;
  3499. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  3500. geometry.faces.push( faces[ i ].clone() );
  3501. }
  3502. var uvs = this.faceVertexUvs[ 0 ];
  3503. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  3504. var uv = uvs[ i ], uvCopy = [];
  3505. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  3506. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  3507. }
  3508. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  3509. }
  3510. return geometry;
  3511. },
  3512. deallocate: function () {
  3513. var index = THREE.GeometryLibrary.indexOf( this );
  3514. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  3515. }
  3516. };
  3517. THREE.GeometryIdCount = 0;
  3518. THREE.GeometryLibrary = [];
  3519. /**
  3520. * @author alteredq / http://alteredqualia.com/
  3521. */
  3522. THREE.BufferGeometry = function () {
  3523. THREE.GeometryLibrary.push( this );
  3524. this.id = THREE.GeometryIdCount ++;
  3525. // attributes
  3526. this.attributes = {};
  3527. // attributes typed arrays are kept only if dynamic flag is set
  3528. this.dynamic = false;
  3529. // boundings
  3530. this.boundingBox = null;
  3531. this.boundingSphere = null;
  3532. this.hasTangents = false;
  3533. // for compatibility
  3534. this.morphTargets = [];
  3535. };
  3536. THREE.BufferGeometry.prototype = {
  3537. constructor : THREE.BufferGeometry,
  3538. applyMatrix: function ( matrix ) {
  3539. var positionArray;
  3540. var normalArray;
  3541. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  3542. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  3543. if ( positionArray !== undefined ) {
  3544. matrix.multiplyVector3Array( positionArray );
  3545. this.verticesNeedUpdate = true;
  3546. }
  3547. if ( normalArray !== undefined ) {
  3548. var normalMatrix = new THREE.Matrix3();
  3549. normalMatrix.getInverse( matrix ).transpose();
  3550. normalMatrix.multiplyVector3Array( normalArray );
  3551. this.normalizeNormals();
  3552. this.normalsNeedUpdate = true;
  3553. }
  3554. },
  3555. computeBoundingBox: function () {
  3556. if ( ! this.boundingBox ) {
  3557. this.boundingBox = {
  3558. min: new THREE.Vector3( Infinity, Infinity, Infinity ),
  3559. max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
  3560. };
  3561. }
  3562. var positions = this.attributes[ "position" ].array;
  3563. if ( positions ) {
  3564. var bb = this.boundingBox;
  3565. var x, y, z;
  3566. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3567. x = positions[ i ];
  3568. y = positions[ i + 1 ];
  3569. z = positions[ i + 2 ];
  3570. // bounding box
  3571. if ( x < bb.min.x ) {
  3572. bb.min.x = x;
  3573. } else if ( x > bb.max.x ) {
  3574. bb.max.x = x;
  3575. }
  3576. if ( y < bb.min.y ) {
  3577. bb.min.y = y;
  3578. } else if ( y > bb.max.y ) {
  3579. bb.max.y = y;
  3580. }
  3581. if ( z < bb.min.z ) {
  3582. bb.min.z = z;
  3583. } else if ( z > bb.max.z ) {
  3584. bb.max.z = z;
  3585. }
  3586. }
  3587. }
  3588. if ( positions === undefined || positions.length === 0 ) {
  3589. this.boundingBox.min.set( 0, 0, 0 );
  3590. this.boundingBox.max.set( 0, 0, 0 );
  3591. }
  3592. },
  3593. computeBoundingSphere: function () {
  3594. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  3595. var positions = this.attributes[ "position" ].array;
  3596. if ( positions ) {
  3597. var radiusSq, maxRadiusSq = 0;
  3598. var x, y, z;
  3599. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3600. x = positions[ i ];
  3601. y = positions[ i + 1 ];
  3602. z = positions[ i + 2 ];
  3603. radiusSq = x * x + y * y + z * z;
  3604. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3605. }
  3606. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3607. }
  3608. },
  3609. computeVertexNormals: function () {
  3610. if ( this.attributes[ "position" ] && this.attributes[ "index" ] ) {
  3611. var i, il;
  3612. var j, jl;
  3613. var nVertexElements = this.attributes[ "position" ].array.length;
  3614. if ( this.attributes[ "normal" ] === undefined ) {
  3615. this.attributes[ "normal" ] = {
  3616. itemSize: 3,
  3617. array: new Float32Array( nVertexElements ),
  3618. numItems: nVertexElements
  3619. };
  3620. } else {
  3621. // reset existing normals to zero
  3622. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  3623. this.attributes[ "normal" ].array[ i ] = 0;
  3624. }
  3625. }
  3626. var offsets = this.offsets;
  3627. var indices = this.attributes[ "index" ].array;
  3628. var positions = this.attributes[ "position" ].array;
  3629. var normals = this.attributes[ "normal" ].array;
  3630. var vA, vB, vC, x, y, z,
  3631. pA = new THREE.Vector3(),
  3632. pB = new THREE.Vector3(),
  3633. pC = new THREE.Vector3(),
  3634. cb = new THREE.Vector3(),
  3635. ab = new THREE.Vector3();
  3636. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3637. var start = offsets[ j ].start;
  3638. var count = offsets[ j ].count;
  3639. var index = offsets[ j ].index;
  3640. for ( i = start, il = start + count; i < il; i += 3 ) {
  3641. vA = index + indices[ i ];
  3642. vB = index + indices[ i + 1 ];
  3643. vC = index + indices[ i + 2 ];
  3644. x = positions[ vA * 3 ];
  3645. y = positions[ vA * 3 + 1 ];
  3646. z = positions[ vA * 3 + 2 ];
  3647. pA.set( x, y, z );
  3648. x = positions[ vB * 3 ];
  3649. y = positions[ vB * 3 + 1 ];
  3650. z = positions[ vB * 3 + 2 ];
  3651. pB.set( x, y, z );
  3652. x = positions[ vC * 3 ];
  3653. y = positions[ vC * 3 + 1 ];
  3654. z = positions[ vC * 3 + 2 ];
  3655. pC.set( x, y, z );
  3656. cb.sub( pC, pB );
  3657. ab.sub( pA, pB );
  3658. cb.crossSelf( ab );
  3659. normals[ vA * 3 ] += cb.x;
  3660. normals[ vA * 3 + 1 ] += cb.y;
  3661. normals[ vA * 3 + 2 ] += cb.z;
  3662. normals[ vB * 3 ] += cb.x;
  3663. normals[ vB * 3 + 1 ] += cb.y;
  3664. normals[ vB * 3 + 2 ] += cb.z;
  3665. normals[ vC * 3 ] += cb.x;
  3666. normals[ vC * 3 + 1 ] += cb.y;
  3667. normals[ vC * 3 + 2 ] += cb.z;
  3668. }
  3669. }
  3670. this.normalizeNormals();
  3671. this.normalsNeedUpdate = true;
  3672. }
  3673. },
  3674. normalizeNormals: function () {
  3675. var normals = this.attributes[ "normal" ].array;
  3676. var x, y, z, n;
  3677. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  3678. x = normals[ i ];
  3679. y = normals[ i + 1 ];
  3680. z = normals[ i + 2 ];
  3681. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  3682. normals[ i ] *= n;
  3683. normals[ i + 1 ] *= n;
  3684. normals[ i + 2 ] *= n;
  3685. }
  3686. },
  3687. computeTangents: function () {
  3688. // based on http://www.terathon.com/code/tangent.html
  3689. // (per vertex tangents)
  3690. if ( this.attributes[ "index" ] === undefined ||
  3691. this.attributes[ "position" ] === undefined ||
  3692. this.attributes[ "normal" ] === undefined ||
  3693. this.attributes[ "uv" ] === undefined ) {
  3694. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  3695. return;
  3696. }
  3697. var indices = this.attributes[ "index" ].array;
  3698. var positions = this.attributes[ "position" ].array;
  3699. var normals = this.attributes[ "normal" ].array;
  3700. var uvs = this.attributes[ "uv" ].array;
  3701. var nVertices = positions.length / 3;
  3702. if ( this.attributes[ "tangent" ] === undefined ) {
  3703. var nTangentElements = 4 * nVertices;
  3704. this.attributes[ "tangent" ] = {
  3705. itemSize: 4,
  3706. array: new Float32Array( nTangentElements ),
  3707. numItems: nTangentElements
  3708. };
  3709. }
  3710. var tangents = this.attributes[ "tangent" ].array;
  3711. var tan1 = [], tan2 = [];
  3712. for ( var k = 0; k < nVertices; k ++ ) {
  3713. tan1[ k ] = new THREE.Vector3();
  3714. tan2[ k ] = new THREE.Vector3();
  3715. }
  3716. var xA, yA, zA,
  3717. xB, yB, zB,
  3718. xC, yC, zC,
  3719. uA, vA,
  3720. uB, vB,
  3721. uC, vC,
  3722. x1, x2, y1, y2, z1, z2,
  3723. s1, s2, t1, t2, r;
  3724. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  3725. function handleTriangle( a, b, c ) {
  3726. xA = positions[ a * 3 ];
  3727. yA = positions[ a * 3 + 1 ];
  3728. zA = positions[ a * 3 + 2 ];
  3729. xB = positions[ b * 3 ];
  3730. yB = positions[ b * 3 + 1 ];
  3731. zB = positions[ b * 3 + 2 ];
  3732. xC = positions[ c * 3 ];
  3733. yC = positions[ c * 3 + 1 ];
  3734. zC = positions[ c * 3 + 2 ];
  3735. uA = uvs[ a * 2 ];
  3736. vA = uvs[ a * 2 + 1 ];
  3737. uB = uvs[ b * 2 ];
  3738. vB = uvs[ b * 2 + 1 ];
  3739. uC = uvs[ c * 2 ];
  3740. vC = uvs[ c * 2 + 1 ];
  3741. x1 = xB - xA;
  3742. x2 = xC - xA;
  3743. y1 = yB - yA;
  3744. y2 = yC - yA;
  3745. z1 = zB - zA;
  3746. z2 = zC - zA;
  3747. s1 = uB - uA;
  3748. s2 = uC - uA;
  3749. t1 = vB - vA;
  3750. t2 = vC - vA;
  3751. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3752. sdir.set(
  3753. ( t2 * x1 - t1 * x2 ) * r,
  3754. ( t2 * y1 - t1 * y2 ) * r,
  3755. ( t2 * z1 - t1 * z2 ) * r
  3756. );
  3757. tdir.set(
  3758. ( s1 * x2 - s2 * x1 ) * r,
  3759. ( s1 * y2 - s2 * y1 ) * r,
  3760. ( s1 * z2 - s2 * z1 ) * r
  3761. );
  3762. tan1[ a ].addSelf( sdir );
  3763. tan1[ b ].addSelf( sdir );
  3764. tan1[ c ].addSelf( sdir );
  3765. tan2[ a ].addSelf( tdir );
  3766. tan2[ b ].addSelf( tdir );
  3767. tan2[ c ].addSelf( tdir );
  3768. }
  3769. var i, il;
  3770. var j, jl;
  3771. var iA, iB, iC;
  3772. var offsets = this.offsets;
  3773. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3774. var start = offsets[ j ].start;
  3775. var count = offsets[ j ].count;
  3776. var index = offsets[ j ].index;
  3777. for ( i = start, il = start + count; i < il; i += 3 ) {
  3778. iA = index + indices[ i ];
  3779. iB = index + indices[ i + 1 ];
  3780. iC = index + indices[ i + 2 ];
  3781. handleTriangle( iA, iB, iC );
  3782. }
  3783. }
  3784. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  3785. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  3786. var w, t, test;
  3787. var nx, ny, nz;
  3788. function handleVertex( v ) {
  3789. n.x = normals[ v * 3 ];
  3790. n.y = normals[ v * 3 + 1 ];
  3791. n.z = normals[ v * 3 + 2 ];
  3792. n2.copy( n );
  3793. t = tan1[ v ];
  3794. // Gram-Schmidt orthogonalize
  3795. tmp.copy( t );
  3796. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3797. // Calculate handedness
  3798. tmp2.cross( n2, t );
  3799. test = tmp2.dot( tan2[ v ] );
  3800. w = ( test < 0.0 ) ? -1.0 : 1.0;
  3801. tangents[ v * 4 ] = tmp.x;
  3802. tangents[ v * 4 + 1 ] = tmp.y;
  3803. tangents[ v * 4 + 2 ] = tmp.z;
  3804. tangents[ v * 4 + 3 ] = w;
  3805. }
  3806. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3807. var start = offsets[ j ].start;
  3808. var count = offsets[ j ].count;
  3809. var index = offsets[ j ].index;
  3810. for ( i = start, il = start + count; i < il; i += 3 ) {
  3811. iA = index + indices[ i ];
  3812. iB = index + indices[ i + 1 ];
  3813. iC = index + indices[ i + 2 ];
  3814. handleVertex( iA );
  3815. handleVertex( iB );
  3816. handleVertex( iC );
  3817. }
  3818. }
  3819. this.hasTangents = true;
  3820. this.tangentsNeedUpdate = true;
  3821. },
  3822. deallocate: function () {
  3823. var index = THREE.GeometryLibrary.indexOf( this );
  3824. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  3825. }
  3826. };
  3827. /**
  3828. * Spline from Tween.js, slightly optimized (and trashed)
  3829. * http://sole.github.com/tween.js/examples/05_spline.html
  3830. *
  3831. * @author mrdoob / http://mrdoob.com/
  3832. * @author alteredq / http://alteredqualia.com/
  3833. */
  3834. THREE.Spline = function ( points ) {
  3835. this.points = points;
  3836. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3837. point, intPoint, weight, w2, w3,
  3838. pa, pb, pc, pd;
  3839. this.initFromArray = function( a ) {
  3840. this.points = [];
  3841. for ( var i = 0; i < a.length; i++ ) {
  3842. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3843. }
  3844. };
  3845. this.getPoint = function ( k ) {
  3846. point = ( this.points.length - 1 ) * k;
  3847. intPoint = Math.floor( point );
  3848. weight = point - intPoint;
  3849. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3850. c[ 1 ] = intPoint;
  3851. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3852. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3853. pa = this.points[ c[ 0 ] ];
  3854. pb = this.points[ c[ 1 ] ];
  3855. pc = this.points[ c[ 2 ] ];
  3856. pd = this.points[ c[ 3 ] ];
  3857. w2 = weight * weight;
  3858. w3 = weight * w2;
  3859. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3860. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3861. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3862. return v3;
  3863. };
  3864. this.getControlPointsArray = function () {
  3865. var i, p, l = this.points.length,
  3866. coords = [];
  3867. for ( i = 0; i < l; i ++ ) {
  3868. p = this.points[ i ];
  3869. coords[ i ] = [ p.x, p.y, p.z ];
  3870. }
  3871. return coords;
  3872. };
  3873. // approximate length by summing linear segments
  3874. this.getLength = function ( nSubDivisions ) {
  3875. var i, index, nSamples, position,
  3876. point = 0, intPoint = 0, oldIntPoint = 0,
  3877. oldPosition = new THREE.Vector3(),
  3878. tmpVec = new THREE.Vector3(),
  3879. chunkLengths = [],
  3880. totalLength = 0;
  3881. // first point has 0 length
  3882. chunkLengths[ 0 ] = 0;
  3883. if ( !nSubDivisions ) nSubDivisions = 100;
  3884. nSamples = this.points.length * nSubDivisions;
  3885. oldPosition.copy( this.points[ 0 ] );
  3886. for ( i = 1; i < nSamples; i ++ ) {
  3887. index = i / nSamples;
  3888. position = this.getPoint( index );
  3889. tmpVec.copy( position );
  3890. totalLength += tmpVec.distanceTo( oldPosition );
  3891. oldPosition.copy( position );
  3892. point = ( this.points.length - 1 ) * index;
  3893. intPoint = Math.floor( point );
  3894. if ( intPoint != oldIntPoint ) {
  3895. chunkLengths[ intPoint ] = totalLength;
  3896. oldIntPoint = intPoint;
  3897. }
  3898. }
  3899. // last point ends with total length
  3900. chunkLengths[ chunkLengths.length ] = totalLength;
  3901. return { chunks: chunkLengths, total: totalLength };
  3902. };
  3903. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3904. var i, j,
  3905. index, indexCurrent, indexNext,
  3906. linearDistance, realDistance,
  3907. sampling, position,
  3908. newpoints = [],
  3909. tmpVec = new THREE.Vector3(),
  3910. sl = this.getLength();
  3911. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3912. for ( i = 1; i < this.points.length; i++ ) {
  3913. //tmpVec.copy( this.points[ i - 1 ] );
  3914. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3915. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3916. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3917. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3918. indexNext = i / ( this.points.length - 1 );
  3919. for ( j = 1; j < sampling - 1; j++ ) {
  3920. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3921. position = this.getPoint( index );
  3922. newpoints.push( tmpVec.copy( position ).clone() );
  3923. }
  3924. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3925. }
  3926. this.points = newpoints;
  3927. };
  3928. // Catmull-Rom
  3929. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3930. var v0 = ( p2 - p0 ) * 0.5,
  3931. v1 = ( p3 - p1 ) * 0.5;
  3932. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3933. };
  3934. };
  3935. /**
  3936. * @author mrdoob / http://mrdoob.com/
  3937. * @author mikael emtinger / http://gomo.se/
  3938. */
  3939. THREE.Camera = function () {
  3940. THREE.Object3D.call( this );
  3941. this.matrixWorldInverse = new THREE.Matrix4();
  3942. this.projectionMatrix = new THREE.Matrix4();
  3943. this.projectionMatrixInverse = new THREE.Matrix4();
  3944. };
  3945. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  3946. THREE.Camera.prototype.lookAt = function ( vector ) {
  3947. // TODO: Add hierarchy support.
  3948. this.matrix.lookAt( this.position, vector, this.up );
  3949. if ( this.rotationAutoUpdate === true ) {
  3950. if ( this.useQuaternion === false ) {
  3951. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3952. } else {
  3953. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  3954. }
  3955. }
  3956. };
  3957. /**
  3958. * @author alteredq / http://alteredqualia.com/
  3959. */
  3960. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  3961. THREE.Camera.call( this );
  3962. this.left = left;
  3963. this.right = right;
  3964. this.top = top;
  3965. this.bottom = bottom;
  3966. this.near = ( near !== undefined ) ? near : 0.1;
  3967. this.far = ( far !== undefined ) ? far : 2000;
  3968. this.updateProjectionMatrix();
  3969. };
  3970. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  3971. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  3972. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  3973. };
  3974. /**
  3975. * @author mrdoob / http://mrdoob.com/
  3976. * @author greggman / http://games.greggman.com/
  3977. * @author zz85 / http://www.lab4games.net/zz85/blog
  3978. */
  3979. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  3980. THREE.Camera.call( this );
  3981. this.fov = fov !== undefined ? fov : 50;
  3982. this.aspect = aspect !== undefined ? aspect : 1;
  3983. this.near = near !== undefined ? near : 0.1;
  3984. this.far = far !== undefined ? far : 2000;
  3985. this.updateProjectionMatrix();
  3986. };
  3987. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  3988. /**
  3989. * Uses Focal Length (in mm) to estimate and set FOV
  3990. * 35mm (fullframe) camera is used if frame size is not specified;
  3991. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  3992. */
  3993. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  3994. if ( frameHeight === undefined ) frameHeight = 24;
  3995. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  3996. this.updateProjectionMatrix();
  3997. }
  3998. /**
  3999. * Sets an offset in a larger frustum. This is useful for multi-window or
  4000. * multi-monitor/multi-machine setups.
  4001. *
  4002. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  4003. * the monitors are in grid like this
  4004. *
  4005. * +---+---+---+
  4006. * | A | B | C |
  4007. * +---+---+---+
  4008. * | D | E | F |
  4009. * +---+---+---+
  4010. *
  4011. * then for each monitor you would call it like this
  4012. *
  4013. * var w = 1920;
  4014. * var h = 1080;
  4015. * var fullWidth = w * 3;
  4016. * var fullHeight = h * 2;
  4017. *
  4018. * --A--
  4019. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  4020. * --B--
  4021. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  4022. * --C--
  4023. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  4024. * --D--
  4025. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  4026. * --E--
  4027. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  4028. * --F--
  4029. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  4030. *
  4031. * Note there is no reason monitors have to be the same size or in a grid.
  4032. */
  4033. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  4034. this.fullWidth = fullWidth;
  4035. this.fullHeight = fullHeight;
  4036. this.x = x;
  4037. this.y = y;
  4038. this.width = width;
  4039. this.height = height;
  4040. this.updateProjectionMatrix();
  4041. };
  4042. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  4043. if ( this.fullWidth ) {
  4044. var aspect = this.fullWidth / this.fullHeight;
  4045. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  4046. var bottom = -top;
  4047. var left = aspect * bottom;
  4048. var right = aspect * top;
  4049. var width = Math.abs( right - left );
  4050. var height = Math.abs( top - bottom );
  4051. this.projectionMatrix.makeFrustum(
  4052. left + this.x * width / this.fullWidth,
  4053. left + ( this.x + this.width ) * width / this.fullWidth,
  4054. top - ( this.y + this.height ) * height / this.fullHeight,
  4055. top - this.y * height / this.fullHeight,
  4056. this.near,
  4057. this.far
  4058. );
  4059. } else {
  4060. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  4061. }
  4062. };
  4063. /**
  4064. * @author mrdoob / http://mrdoob.com/
  4065. * @author alteredq / http://alteredqualia.com/
  4066. */
  4067. THREE.Light = function ( hex ) {
  4068. THREE.Object3D.call( this );
  4069. this.color = new THREE.Color( hex );
  4070. };
  4071. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  4072. /**
  4073. * @author mrdoob / http://mrdoob.com/
  4074. */
  4075. THREE.AmbientLight = function ( hex ) {
  4076. THREE.Light.call( this, hex );
  4077. };
  4078. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  4079. /**
  4080. * @author mrdoob / http://mrdoob.com/
  4081. * @author alteredq / http://alteredqualia.com/
  4082. */
  4083. THREE.DirectionalLight = function ( hex, intensity ) {
  4084. THREE.Light.call( this, hex );
  4085. this.position = new THREE.Vector3( 0, 1, 0 );
  4086. this.target = new THREE.Object3D();
  4087. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4088. this.castShadow = false;
  4089. this.onlyShadow = false;
  4090. //
  4091. this.shadowCameraNear = 50;
  4092. this.shadowCameraFar = 5000;
  4093. this.shadowCameraLeft = -500;
  4094. this.shadowCameraRight = 500;
  4095. this.shadowCameraTop = 500;
  4096. this.shadowCameraBottom = -500;
  4097. this.shadowCameraVisible = false;
  4098. this.shadowBias = 0;
  4099. this.shadowDarkness = 0.5;
  4100. this.shadowMapWidth = 512;
  4101. this.shadowMapHeight = 512;
  4102. //
  4103. this.shadowCascade = false;
  4104. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  4105. this.shadowCascadeCount = 2;
  4106. this.shadowCascadeBias = [ 0, 0, 0 ];
  4107. this.shadowCascadeWidth = [ 512, 512, 512 ];
  4108. this.shadowCascadeHeight = [ 512, 512, 512 ];
  4109. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  4110. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  4111. this.shadowCascadeArray = [];
  4112. //
  4113. this.shadowMap = null;
  4114. this.shadowMapSize = null;
  4115. this.shadowCamera = null;
  4116. this.shadowMatrix = null;
  4117. };
  4118. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  4119. /**
  4120. * @author alteredq / http://alteredqualia.com/
  4121. */
  4122. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  4123. THREE.Light.call( this, skyColorHex );
  4124. this.groundColor = new THREE.Color( groundColorHex );
  4125. this.position = new THREE.Vector3( 0, 100, 0 );
  4126. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4127. };
  4128. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  4129. /**
  4130. * @author mrdoob / http://mrdoob.com/
  4131. */
  4132. THREE.PointLight = function ( hex, intensity, distance ) {
  4133. THREE.Light.call( this, hex );
  4134. this.position = new THREE.Vector3( 0, 0, 0 );
  4135. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4136. this.distance = ( distance !== undefined ) ? distance : 0;
  4137. };
  4138. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  4139. /**
  4140. * @author alteredq / http://alteredqualia.com/
  4141. */
  4142. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  4143. THREE.Light.call( this, hex );
  4144. this.position = new THREE.Vector3( 0, 1, 0 );
  4145. this.target = new THREE.Object3D();
  4146. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4147. this.distance = ( distance !== undefined ) ? distance : 0;
  4148. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  4149. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  4150. this.castShadow = false;
  4151. this.onlyShadow = false;
  4152. //
  4153. this.shadowCameraNear = 50;
  4154. this.shadowCameraFar = 5000;
  4155. this.shadowCameraFov = 50;
  4156. this.shadowCameraVisible = false;
  4157. this.shadowBias = 0;
  4158. this.shadowDarkness = 0.5;
  4159. this.shadowMapWidth = 512;
  4160. this.shadowMapHeight = 512;
  4161. //
  4162. this.shadowMap = null;
  4163. this.shadowMapSize = null;
  4164. this.shadowCamera = null;
  4165. this.shadowMatrix = null;
  4166. };
  4167. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  4168. /**
  4169. * @author alteredq / http://alteredqualia.com/
  4170. */
  4171. THREE.Loader = function ( showStatus ) {
  4172. this.showStatus = showStatus;
  4173. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  4174. this.onLoadStart = function () {};
  4175. this.onLoadProgress = function () {};
  4176. this.onLoadComplete = function () {};
  4177. };
  4178. THREE.Loader.prototype = {
  4179. constructor: THREE.Loader,
  4180. crossOrigin: 'anonymous',
  4181. addStatusElement: function () {
  4182. var e = document.createElement( "div" );
  4183. e.style.position = "absolute";
  4184. e.style.right = "0px";
  4185. e.style.top = "0px";
  4186. e.style.fontSize = "0.8em";
  4187. e.style.textAlign = "left";
  4188. e.style.background = "rgba(0,0,0,0.25)";
  4189. e.style.color = "#fff";
  4190. e.style.width = "120px";
  4191. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  4192. e.style.zIndex = 1000;
  4193. e.innerHTML = "Loading ...";
  4194. return e;
  4195. },
  4196. updateProgress: function ( progress ) {
  4197. var message = "Loaded ";
  4198. if ( progress.total ) {
  4199. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  4200. } else {
  4201. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  4202. }
  4203. this.statusDomElement.innerHTML = message;
  4204. },
  4205. extractUrlBase: function ( url ) {
  4206. var parts = url.split( '/' );
  4207. parts.pop();
  4208. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  4209. },
  4210. initMaterials: function ( materials, texturePath ) {
  4211. var array = [];
  4212. for ( var i = 0; i < materials.length; ++ i ) {
  4213. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  4214. }
  4215. return array;
  4216. },
  4217. needsTangents: function ( materials ) {
  4218. for( var i = 0, il = materials.length; i < il; i ++ ) {
  4219. var m = materials[ i ];
  4220. if ( m instanceof THREE.ShaderMaterial ) return true;
  4221. }
  4222. return false;
  4223. },
  4224. createMaterial: function ( m, texturePath ) {
  4225. var _this = this;
  4226. function is_pow2( n ) {
  4227. var l = Math.log( n ) / Math.LN2;
  4228. return Math.floor( l ) == l;
  4229. }
  4230. function nearest_pow2( n ) {
  4231. var l = Math.log( n ) / Math.LN2;
  4232. return Math.pow( 2, Math.round( l ) );
  4233. }
  4234. function load_image( where, url ) {
  4235. var image = new Image();
  4236. image.onload = function () {
  4237. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  4238. var width = nearest_pow2( this.width );
  4239. var height = nearest_pow2( this.height );
  4240. where.image.width = width;
  4241. where.image.height = height;
  4242. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  4243. } else {
  4244. where.image = this;
  4245. }
  4246. where.needsUpdate = true;
  4247. };
  4248. image.crossOrigin = _this.crossOrigin;
  4249. image.src = url;
  4250. }
  4251. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  4252. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  4253. var fullPath = texturePath + "/" + sourceFile;
  4254. if ( isCompressed ) {
  4255. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  4256. where[ name ] = texture;
  4257. } else {
  4258. var texture = document.createElement( 'canvas' );
  4259. where[ name ] = new THREE.Texture( texture );
  4260. }
  4261. where[ name ].sourceFile = sourceFile;
  4262. if( repeat ) {
  4263. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4264. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4265. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4266. }
  4267. if ( offset ) {
  4268. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4269. }
  4270. if ( wrap ) {
  4271. var wrapMap = {
  4272. "repeat": THREE.RepeatWrapping,
  4273. "mirror": THREE.MirroredRepeatWrapping
  4274. }
  4275. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4276. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4277. }
  4278. if ( anisotropy ) {
  4279. where[ name ].anisotropy = anisotropy;
  4280. }
  4281. if ( ! isCompressed ) {
  4282. load_image( where[ name ], fullPath );
  4283. }
  4284. }
  4285. function rgb2hex( rgb ) {
  4286. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4287. }
  4288. // defaults
  4289. var mtype = "MeshLambertMaterial";
  4290. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4291. // parameters from model file
  4292. if ( m.shading ) {
  4293. var shading = m.shading.toLowerCase();
  4294. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4295. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4296. }
  4297. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4298. mpars.blending = THREE[ m.blending ];
  4299. }
  4300. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4301. mpars.transparent = m.transparent;
  4302. }
  4303. if ( m.depthTest !== undefined ) {
  4304. mpars.depthTest = m.depthTest;
  4305. }
  4306. if ( m.depthWrite !== undefined ) {
  4307. mpars.depthWrite = m.depthWrite;
  4308. }
  4309. if ( m.visible !== undefined ) {
  4310. mpars.visible = m.visible;
  4311. }
  4312. if ( m.flipSided !== undefined ) {
  4313. mpars.side = THREE.BackSide;
  4314. }
  4315. if ( m.doubleSided !== undefined ) {
  4316. mpars.side = THREE.DoubleSide;
  4317. }
  4318. if ( m.wireframe !== undefined ) {
  4319. mpars.wireframe = m.wireframe;
  4320. }
  4321. if ( m.vertexColors !== undefined ) {
  4322. if ( m.vertexColors === "face" ) {
  4323. mpars.vertexColors = THREE.FaceColors;
  4324. } else if ( m.vertexColors ) {
  4325. mpars.vertexColors = THREE.VertexColors;
  4326. }
  4327. }
  4328. // colors
  4329. if ( m.colorDiffuse ) {
  4330. mpars.color = rgb2hex( m.colorDiffuse );
  4331. } else if ( m.DbgColor ) {
  4332. mpars.color = m.DbgColor;
  4333. }
  4334. if ( m.colorSpecular ) {
  4335. mpars.specular = rgb2hex( m.colorSpecular );
  4336. }
  4337. if ( m.colorAmbient ) {
  4338. mpars.ambient = rgb2hex( m.colorAmbient );
  4339. }
  4340. // modifiers
  4341. if ( m.transparency ) {
  4342. mpars.opacity = m.transparency;
  4343. }
  4344. if ( m.specularCoef ) {
  4345. mpars.shininess = m.specularCoef;
  4346. }
  4347. // textures
  4348. if ( m.mapDiffuse && texturePath ) {
  4349. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  4350. }
  4351. if ( m.mapLight && texturePath ) {
  4352. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  4353. }
  4354. if ( m.mapBump && texturePath ) {
  4355. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  4356. }
  4357. if ( m.mapNormal && texturePath ) {
  4358. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  4359. }
  4360. if ( m.mapSpecular && texturePath ) {
  4361. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  4362. }
  4363. //
  4364. if ( m.mapBumpScale ) {
  4365. mpars.bumpScale = m.mapBumpScale;
  4366. }
  4367. // special case for normal mapped material
  4368. if ( m.mapNormal ) {
  4369. var shader = THREE.ShaderUtils.lib[ "normal" ];
  4370. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  4371. uniforms[ "tNormal" ].value = mpars.normalMap;
  4372. if ( m.mapNormalFactor ) {
  4373. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  4374. }
  4375. if ( mpars.map ) {
  4376. uniforms[ "tDiffuse" ].value = mpars.map;
  4377. uniforms[ "enableDiffuse" ].value = true;
  4378. }
  4379. if ( mpars.specularMap ) {
  4380. uniforms[ "tSpecular" ].value = mpars.specularMap;
  4381. uniforms[ "enableSpecular" ].value = true;
  4382. }
  4383. if ( mpars.lightMap ) {
  4384. uniforms[ "tAO" ].value = mpars.lightMap;
  4385. uniforms[ "enableAO" ].value = true;
  4386. }
  4387. // for the moment don't handle displacement texture
  4388. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  4389. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  4390. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  4391. uniforms[ "uShininess" ].value = mpars.shininess;
  4392. if ( mpars.opacity !== undefined ) {
  4393. uniforms[ "uOpacity" ].value = mpars.opacity;
  4394. }
  4395. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  4396. var material = new THREE.ShaderMaterial( parameters );
  4397. } else {
  4398. var material = new THREE[ mtype ]( mpars );
  4399. }
  4400. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  4401. return material;
  4402. }
  4403. };
  4404. /**
  4405. * @author alteredq / http://alteredqualia.com/
  4406. */
  4407. THREE.BinaryLoader = function ( showStatus ) {
  4408. THREE.Loader.call( this, showStatus );
  4409. };
  4410. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  4411. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  4412. // - binary models consist of two files: JS and BIN
  4413. // - parameters
  4414. // - url (required)
  4415. // - callback (required)
  4416. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  4417. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  4418. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  4419. // todo: unify load API to for easier SceneLoader use
  4420. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  4421. binaryPath = binaryPath && ( typeof binaryPath === "string" ) ? binaryPath : this.extractUrlBase( url );
  4422. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  4423. this.onLoadStart();
  4424. // #1 load JS part via web worker
  4425. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  4426. };
  4427. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  4428. var xhr = new XMLHttpRequest();
  4429. xhr.onreadystatechange = function () {
  4430. if ( xhr.readyState == 4 ) {
  4431. if ( xhr.status == 200 || xhr.status == 0 ) {
  4432. var json = JSON.parse( xhr.responseText );
  4433. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  4434. } else {
  4435. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4436. }
  4437. }
  4438. };
  4439. xhr.open( "GET", url, true );
  4440. xhr.send( null );
  4441. };
  4442. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  4443. var xhr = new XMLHttpRequest(),
  4444. url = binaryPath + "/" + json.buffers;
  4445. var length = 0;
  4446. xhr.onreadystatechange = function () {
  4447. if ( xhr.readyState == 4 ) {
  4448. if ( xhr.status == 200 || xhr.status == 0 ) {
  4449. var buffer = xhr.response;
  4450. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  4451. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  4452. } else {
  4453. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4454. }
  4455. } else if ( xhr.readyState == 3 ) {
  4456. if ( callbackProgress ) {
  4457. if ( length == 0 ) {
  4458. length = xhr.getResponseHeader( "Content-Length" );
  4459. }
  4460. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4461. }
  4462. } else if ( xhr.readyState == 2 ) {
  4463. length = xhr.getResponseHeader( "Content-Length" );
  4464. }
  4465. };
  4466. xhr.open( "GET", url, true );
  4467. xhr.responseType = "arraybuffer";
  4468. xhr.send( null );
  4469. };
  4470. // Binary AJAX parser
  4471. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, jsonMaterials ) {
  4472. var Model = function ( texturePath ) {
  4473. var scope = this,
  4474. currentOffset = 0,
  4475. md,
  4476. normals = [],
  4477. uvs = [],
  4478. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  4479. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  4480. tri_size, quad_size,
  4481. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  4482. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  4483. THREE.Geometry.call( this );
  4484. md = parseMetaData( data, currentOffset );
  4485. currentOffset += md.header_bytes;
  4486. /*
  4487. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4488. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  4489. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4490. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4491. */
  4492. // buffers sizes
  4493. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  4494. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  4495. len_tri_flat = md.ntri_flat * ( tri_size );
  4496. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  4497. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  4498. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  4499. len_quad_flat = md.nquad_flat * ( quad_size );
  4500. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  4501. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  4502. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  4503. // read buffers
  4504. currentOffset += init_vertices( currentOffset );
  4505. currentOffset += init_normals( currentOffset );
  4506. currentOffset += handlePadding( md.nnormals * 3 );
  4507. currentOffset += init_uvs( currentOffset );
  4508. start_tri_flat = currentOffset;
  4509. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  4510. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  4511. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  4512. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  4513. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  4514. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  4515. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  4516. // have to first process faces with uvs
  4517. // so that face and uv indices match
  4518. init_triangles_flat_uv( start_tri_flat_uv );
  4519. init_triangles_smooth_uv( start_tri_smooth_uv );
  4520. init_quads_flat_uv( start_quad_flat_uv );
  4521. init_quads_smooth_uv( start_quad_smooth_uv );
  4522. // now we can process untextured faces
  4523. init_triangles_flat( start_tri_flat );
  4524. init_triangles_smooth( start_tri_smooth );
  4525. init_quads_flat( start_quad_flat );
  4526. init_quads_smooth( start_quad_smooth );
  4527. this.computeCentroids();
  4528. this.computeFaceNormals();
  4529. function handlePadding( n ) {
  4530. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  4531. };
  4532. function parseMetaData( data, offset ) {
  4533. var metaData = {
  4534. 'signature' :parseString( data, offset, 12 ),
  4535. 'header_bytes' :parseUChar8( data, offset + 12 ),
  4536. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  4537. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  4538. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  4539. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  4540. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  4541. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  4542. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  4543. 'nvertices' :parseUInt32( data, offset + 20 ),
  4544. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  4545. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  4546. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  4547. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  4548. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  4549. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  4550. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  4551. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  4552. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  4553. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  4554. };
  4555. /*
  4556. console.log( "signature: " + metaData.signature );
  4557. console.log( "header_bytes: " + metaData.header_bytes );
  4558. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  4559. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  4560. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  4561. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  4562. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  4563. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  4564. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  4565. console.log( "nvertices: " + metaData.nvertices );
  4566. console.log( "nnormals: " + metaData.nnormals );
  4567. console.log( "nuvs: " + metaData.nuvs );
  4568. console.log( "ntri_flat: " + metaData.ntri_flat );
  4569. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  4570. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  4571. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  4572. console.log( "nquad_flat: " + metaData.nquad_flat );
  4573. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  4574. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  4575. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  4576. var total = metaData.header_bytes
  4577. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  4578. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  4579. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  4580. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  4581. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  4582. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  4583. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  4584. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  4585. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  4586. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  4587. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  4588. console.log( "total bytes: " + total );
  4589. */
  4590. return metaData;
  4591. };
  4592. function parseString( data, offset, length ) {
  4593. var charArray = new Uint8Array( data, offset, length );
  4594. var text = "";
  4595. for ( var i = 0; i < length; i ++ ) {
  4596. text += String.fromCharCode( charArray[ offset + i ] );
  4597. }
  4598. return text;
  4599. };
  4600. function parseUChar8( data, offset ) {
  4601. var charArray = new Uint8Array( data, offset, 1 );
  4602. return charArray[ 0 ];
  4603. };
  4604. function parseUInt32( data, offset ) {
  4605. var intArray = new Uint32Array( data, offset, 1 );
  4606. return intArray[ 0 ];
  4607. };
  4608. function init_vertices( start ) {
  4609. var nElements = md.nvertices;
  4610. var coordArray = new Float32Array( data, start, nElements * 3 );
  4611. var i, x, y, z;
  4612. for( i = 0; i < nElements; i ++ ) {
  4613. x = coordArray[ i * 3 ];
  4614. y = coordArray[ i * 3 + 1 ];
  4615. z = coordArray[ i * 3 + 2 ];
  4616. vertex( scope, x, y, z );
  4617. }
  4618. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  4619. };
  4620. function init_normals( start ) {
  4621. var nElements = md.nnormals;
  4622. if ( nElements ) {
  4623. var normalArray = new Int8Array( data, start, nElements * 3 );
  4624. var i, x, y, z;
  4625. for( i = 0; i < nElements; i ++ ) {
  4626. x = normalArray[ i * 3 ];
  4627. y = normalArray[ i * 3 + 1 ];
  4628. z = normalArray[ i * 3 + 2 ];
  4629. normals.push( x/127, y/127, z/127 );
  4630. }
  4631. }
  4632. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  4633. };
  4634. function init_uvs( start ) {
  4635. var nElements = md.nuvs;
  4636. if ( nElements ) {
  4637. var uvArray = new Float32Array( data, start, nElements * 2 );
  4638. var i, u, v;
  4639. for( i = 0; i < nElements; i ++ ) {
  4640. u = uvArray[ i * 2 ];
  4641. v = uvArray[ i * 2 + 1 ];
  4642. uvs.push( u, v );
  4643. }
  4644. }
  4645. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  4646. };
  4647. function init_uvs3( nElements, offset ) {
  4648. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  4649. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  4650. for( i = 0; i < nElements; i ++ ) {
  4651. uva = uvIndexBuffer[ i * 3 ];
  4652. uvb = uvIndexBuffer[ i * 3 + 1 ];
  4653. uvc = uvIndexBuffer[ i * 3 + 2 ];
  4654. u1 = uvs[ uva*2 ];
  4655. v1 = uvs[ uva*2 + 1 ];
  4656. u2 = uvs[ uvb*2 ];
  4657. v2 = uvs[ uvb*2 + 1 ];
  4658. u3 = uvs[ uvc*2 ];
  4659. v3 = uvs[ uvc*2 + 1 ];
  4660. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  4661. }
  4662. };
  4663. function init_uvs4( nElements, offset ) {
  4664. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  4665. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  4666. for( i = 0; i < nElements; i ++ ) {
  4667. uva = uvIndexBuffer[ i * 4 ];
  4668. uvb = uvIndexBuffer[ i * 4 + 1 ];
  4669. uvc = uvIndexBuffer[ i * 4 + 2 ];
  4670. uvd = uvIndexBuffer[ i * 4 + 3 ];
  4671. u1 = uvs[ uva*2 ];
  4672. v1 = uvs[ uva*2 + 1 ];
  4673. u2 = uvs[ uvb*2 ];
  4674. v2 = uvs[ uvb*2 + 1 ];
  4675. u3 = uvs[ uvc*2 ];
  4676. v3 = uvs[ uvc*2 + 1 ];
  4677. u4 = uvs[ uvd*2 ];
  4678. v4 = uvs[ uvd*2 + 1 ];
  4679. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  4680. }
  4681. };
  4682. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  4683. var i, a, b, c, m;
  4684. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4685. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4686. for( i = 0; i < nElements; i ++ ) {
  4687. a = vertexIndexBuffer[ i * 3 ];
  4688. b = vertexIndexBuffer[ i * 3 + 1 ];
  4689. c = vertexIndexBuffer[ i * 3 + 2 ];
  4690. m = materialIndexBuffer[ i ];
  4691. f3( scope, a, b, c, m );
  4692. }
  4693. };
  4694. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  4695. var i, a, b, c, d, m;
  4696. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4697. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4698. for( i = 0; i < nElements; i ++ ) {
  4699. a = vertexIndexBuffer[ i * 4 ];
  4700. b = vertexIndexBuffer[ i * 4 + 1 ];
  4701. c = vertexIndexBuffer[ i * 4 + 2 ];
  4702. d = vertexIndexBuffer[ i * 4 + 3 ];
  4703. m = materialIndexBuffer[ i ];
  4704. f4( scope, a, b, c, d, m );
  4705. }
  4706. };
  4707. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4708. var i, a, b, c, m;
  4709. var na, nb, nc;
  4710. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4711. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  4712. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4713. for( i = 0; i < nElements; i ++ ) {
  4714. a = vertexIndexBuffer[ i * 3 ];
  4715. b = vertexIndexBuffer[ i * 3 + 1 ];
  4716. c = vertexIndexBuffer[ i * 3 + 2 ];
  4717. na = normalIndexBuffer[ i * 3 ];
  4718. nb = normalIndexBuffer[ i * 3 + 1 ];
  4719. nc = normalIndexBuffer[ i * 3 + 2 ];
  4720. m = materialIndexBuffer[ i ];
  4721. f3n( scope, normals, a, b, c, m, na, nb, nc );
  4722. }
  4723. };
  4724. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4725. var i, a, b, c, d, m;
  4726. var na, nb, nc, nd;
  4727. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4728. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  4729. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4730. for( i = 0; i < nElements; i ++ ) {
  4731. a = vertexIndexBuffer[ i * 4 ];
  4732. b = vertexIndexBuffer[ i * 4 + 1 ];
  4733. c = vertexIndexBuffer[ i * 4 + 2 ];
  4734. d = vertexIndexBuffer[ i * 4 + 3 ];
  4735. na = normalIndexBuffer[ i * 4 ];
  4736. nb = normalIndexBuffer[ i * 4 + 1 ];
  4737. nc = normalIndexBuffer[ i * 4 + 2 ];
  4738. nd = normalIndexBuffer[ i * 4 + 3 ];
  4739. m = materialIndexBuffer[ i ];
  4740. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  4741. }
  4742. };
  4743. function init_triangles_flat( start ) {
  4744. var nElements = md.ntri_flat;
  4745. if ( nElements ) {
  4746. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4747. init_faces3_flat( nElements, start, offsetMaterials );
  4748. }
  4749. };
  4750. function init_triangles_flat_uv( start ) {
  4751. var nElements = md.ntri_flat_uv;
  4752. if ( nElements ) {
  4753. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4754. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4755. init_faces3_flat( nElements, start, offsetMaterials );
  4756. init_uvs3( nElements, offsetUvs );
  4757. }
  4758. };
  4759. function init_triangles_smooth( start ) {
  4760. var nElements = md.ntri_smooth;
  4761. if ( nElements ) {
  4762. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4763. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4764. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4765. }
  4766. };
  4767. function init_triangles_smooth_uv( start ) {
  4768. var nElements = md.ntri_smooth_uv;
  4769. if ( nElements ) {
  4770. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4771. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4772. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4773. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4774. init_uvs3( nElements, offsetUvs );
  4775. }
  4776. };
  4777. function init_quads_flat( start ) {
  4778. var nElements = md.nquad_flat;
  4779. if ( nElements ) {
  4780. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4781. init_faces4_flat( nElements, start, offsetMaterials );
  4782. }
  4783. };
  4784. function init_quads_flat_uv( start ) {
  4785. var nElements = md.nquad_flat_uv;
  4786. if ( nElements ) {
  4787. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4788. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4789. init_faces4_flat( nElements, start, offsetMaterials );
  4790. init_uvs4( nElements, offsetUvs );
  4791. }
  4792. };
  4793. function init_quads_smooth( start ) {
  4794. var nElements = md.nquad_smooth;
  4795. if ( nElements ) {
  4796. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4797. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4798. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4799. }
  4800. };
  4801. function init_quads_smooth_uv( start ) {
  4802. var nElements = md.nquad_smooth_uv;
  4803. if ( nElements ) {
  4804. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4805. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4806. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4807. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4808. init_uvs4( nElements, offsetUvs );
  4809. }
  4810. };
  4811. };
  4812. function vertex ( scope, x, y, z ) {
  4813. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  4814. };
  4815. function f3 ( scope, a, b, c, mi ) {
  4816. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  4817. };
  4818. function f4 ( scope, a, b, c, d, mi ) {
  4819. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  4820. };
  4821. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  4822. var nax = normals[ na*3 ],
  4823. nay = normals[ na*3 + 1 ],
  4824. naz = normals[ na*3 + 2 ],
  4825. nbx = normals[ nb*3 ],
  4826. nby = normals[ nb*3 + 1 ],
  4827. nbz = normals[ nb*3 + 2 ],
  4828. ncx = normals[ nc*3 ],
  4829. ncy = normals[ nc*3 + 1 ],
  4830. ncz = normals[ nc*3 + 2 ];
  4831. scope.faces.push( new THREE.Face3( a, b, c,
  4832. [new THREE.Vector3( nax, nay, naz ),
  4833. new THREE.Vector3( nbx, nby, nbz ),
  4834. new THREE.Vector3( ncx, ncy, ncz )],
  4835. null,
  4836. mi ) );
  4837. };
  4838. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  4839. var nax = normals[ na*3 ],
  4840. nay = normals[ na*3 + 1 ],
  4841. naz = normals[ na*3 + 2 ],
  4842. nbx = normals[ nb*3 ],
  4843. nby = normals[ nb*3 + 1 ],
  4844. nbz = normals[ nb*3 + 2 ],
  4845. ncx = normals[ nc*3 ],
  4846. ncy = normals[ nc*3 + 1 ],
  4847. ncz = normals[ nc*3 + 2 ],
  4848. ndx = normals[ nd*3 ],
  4849. ndy = normals[ nd*3 + 1 ],
  4850. ndz = normals[ nd*3 + 2 ];
  4851. scope.faces.push( new THREE.Face4( a, b, c, d,
  4852. [new THREE.Vector3( nax, nay, naz ),
  4853. new THREE.Vector3( nbx, nby, nbz ),
  4854. new THREE.Vector3( ncx, ncy, ncz ),
  4855. new THREE.Vector3( ndx, ndy, ndz )],
  4856. null,
  4857. mi ) );
  4858. };
  4859. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  4860. where.push( [
  4861. new THREE.UV( u1, v1 ),
  4862. new THREE.UV( u2, v2 ),
  4863. new THREE.UV( u3, v3 )
  4864. ] );
  4865. };
  4866. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  4867. where.push( [
  4868. new THREE.UV( u1, v1 ),
  4869. new THREE.UV( u2, v2 ),
  4870. new THREE.UV( u3, v3 ),
  4871. new THREE.UV( u4, v4 )
  4872. ] );
  4873. };
  4874. Model.prototype = Object.create( THREE.Geometry.prototype );
  4875. var geometry = new Model( texturePath );
  4876. var materials = this.initMaterials( jsonMaterials, texturePath );
  4877. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  4878. callback( geometry, materials );
  4879. };
  4880. /**
  4881. * @author mrdoob / http://mrdoob.com/
  4882. */
  4883. THREE.ImageLoader = function () {
  4884. THREE.EventTarget.call( this );
  4885. this.crossOrigin = null;
  4886. };
  4887. THREE.ImageLoader.prototype = {
  4888. constructor: THREE.ImageLoader,
  4889. load: function ( url, image ) {
  4890. var scope = this;
  4891. if ( image === undefined ) image = new Image();
  4892. image.addEventListener( 'load', function () {
  4893. scope.dispatchEvent( { type: 'load', content: image } );
  4894. }, false );
  4895. image.addEventListener( 'error', function () {
  4896. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4897. }, false );
  4898. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  4899. image.src = url;
  4900. }
  4901. }
  4902. /**
  4903. * @author mrdoob / http://mrdoob.com/
  4904. * @author alteredq / http://alteredqualia.com/
  4905. */
  4906. THREE.JSONLoader = function ( showStatus ) {
  4907. THREE.Loader.call( this, showStatus );
  4908. this.withCredentials = false;
  4909. };
  4910. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  4911. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  4912. var scope = this;
  4913. // todo: unify load API to for easier SceneLoader use
  4914. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  4915. this.onLoadStart();
  4916. this.loadAjaxJSON( this, url, callback, texturePath );
  4917. };
  4918. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  4919. var xhr = new XMLHttpRequest();
  4920. var length = 0;
  4921. xhr.withCredentials = this.withCredentials;
  4922. xhr.onreadystatechange = function () {
  4923. if ( xhr.readyState === xhr.DONE ) {
  4924. if ( xhr.status === 200 || xhr.status === 0 ) {
  4925. if ( xhr.responseText ) {
  4926. var json = JSON.parse( xhr.responseText );
  4927. context.createModel( json, callback, texturePath );
  4928. } else {
  4929. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  4930. }
  4931. // in context of more complex asset initialization
  4932. // do not block on single failed file
  4933. // maybe should go even one more level up
  4934. context.onLoadComplete();
  4935. } else {
  4936. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4937. }
  4938. } else if ( xhr.readyState === xhr.LOADING ) {
  4939. if ( callbackProgress ) {
  4940. if ( length === 0 ) {
  4941. length = xhr.getResponseHeader( "Content-Length" );
  4942. }
  4943. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4944. }
  4945. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  4946. length = xhr.getResponseHeader( "Content-Length" );
  4947. }
  4948. };
  4949. xhr.open( "GET", url, true );
  4950. xhr.send( null );
  4951. };
  4952. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  4953. var scope = this,
  4954. geometry = new THREE.Geometry(),
  4955. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  4956. parseModel( scale );
  4957. parseSkin();
  4958. parseMorphing( scale );
  4959. geometry.computeCentroids();
  4960. geometry.computeFaceNormals();
  4961. function parseModel( scale ) {
  4962. function isBitSet( value, position ) {
  4963. return value & ( 1 << position );
  4964. }
  4965. var i, j, fi,
  4966. offset, zLength, nVertices,
  4967. colorIndex, normalIndex, uvIndex, materialIndex,
  4968. type,
  4969. isQuad,
  4970. hasMaterial,
  4971. hasFaceUv, hasFaceVertexUv,
  4972. hasFaceNormal, hasFaceVertexNormal,
  4973. hasFaceColor, hasFaceVertexColor,
  4974. vertex, face, color, normal,
  4975. uvLayer, uvs, u, v,
  4976. faces = json.faces,
  4977. vertices = json.vertices,
  4978. normals = json.normals,
  4979. colors = json.colors,
  4980. nUvLayers = 0;
  4981. // disregard empty arrays
  4982. for ( i = 0; i < json.uvs.length; i++ ) {
  4983. if ( json.uvs[ i ].length ) nUvLayers ++;
  4984. }
  4985. for ( i = 0; i < nUvLayers; i++ ) {
  4986. geometry.faceUvs[ i ] = [];
  4987. geometry.faceVertexUvs[ i ] = [];
  4988. }
  4989. offset = 0;
  4990. zLength = vertices.length;
  4991. while ( offset < zLength ) {
  4992. vertex = new THREE.Vector3();
  4993. vertex.x = vertices[ offset ++ ] * scale;
  4994. vertex.y = vertices[ offset ++ ] * scale;
  4995. vertex.z = vertices[ offset ++ ] * scale;
  4996. geometry.vertices.push( vertex );
  4997. }
  4998. offset = 0;
  4999. zLength = faces.length;
  5000. while ( offset < zLength ) {
  5001. type = faces[ offset ++ ];
  5002. isQuad = isBitSet( type, 0 );
  5003. hasMaterial = isBitSet( type, 1 );
  5004. hasFaceUv = isBitSet( type, 2 );
  5005. hasFaceVertexUv = isBitSet( type, 3 );
  5006. hasFaceNormal = isBitSet( type, 4 );
  5007. hasFaceVertexNormal = isBitSet( type, 5 );
  5008. hasFaceColor = isBitSet( type, 6 );
  5009. hasFaceVertexColor = isBitSet( type, 7 );
  5010. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5011. if ( isQuad ) {
  5012. face = new THREE.Face4();
  5013. face.a = faces[ offset ++ ];
  5014. face.b = faces[ offset ++ ];
  5015. face.c = faces[ offset ++ ];
  5016. face.d = faces[ offset ++ ];
  5017. nVertices = 4;
  5018. } else {
  5019. face = new THREE.Face3();
  5020. face.a = faces[ offset ++ ];
  5021. face.b = faces[ offset ++ ];
  5022. face.c = faces[ offset ++ ];
  5023. nVertices = 3;
  5024. }
  5025. if ( hasMaterial ) {
  5026. materialIndex = faces[ offset ++ ];
  5027. face.materialIndex = materialIndex;
  5028. }
  5029. // to get face <=> uv index correspondence
  5030. fi = geometry.faces.length;
  5031. if ( hasFaceUv ) {
  5032. for ( i = 0; i < nUvLayers; i++ ) {
  5033. uvLayer = json.uvs[ i ];
  5034. uvIndex = faces[ offset ++ ];
  5035. u = uvLayer[ uvIndex * 2 ];
  5036. v = uvLayer[ uvIndex * 2 + 1 ];
  5037. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  5038. }
  5039. }
  5040. if ( hasFaceVertexUv ) {
  5041. for ( i = 0; i < nUvLayers; i++ ) {
  5042. uvLayer = json.uvs[ i ];
  5043. uvs = [];
  5044. for ( j = 0; j < nVertices; j ++ ) {
  5045. uvIndex = faces[ offset ++ ];
  5046. u = uvLayer[ uvIndex * 2 ];
  5047. v = uvLayer[ uvIndex * 2 + 1 ];
  5048. uvs[ j ] = new THREE.UV( u, v );
  5049. }
  5050. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5051. }
  5052. }
  5053. if ( hasFaceNormal ) {
  5054. normalIndex = faces[ offset ++ ] * 3;
  5055. normal = new THREE.Vector3();
  5056. normal.x = normals[ normalIndex ++ ];
  5057. normal.y = normals[ normalIndex ++ ];
  5058. normal.z = normals[ normalIndex ];
  5059. face.normal = normal;
  5060. }
  5061. if ( hasFaceVertexNormal ) {
  5062. for ( i = 0; i < nVertices; i++ ) {
  5063. normalIndex = faces[ offset ++ ] * 3;
  5064. normal = new THREE.Vector3();
  5065. normal.x = normals[ normalIndex ++ ];
  5066. normal.y = normals[ normalIndex ++ ];
  5067. normal.z = normals[ normalIndex ];
  5068. face.vertexNormals.push( normal );
  5069. }
  5070. }
  5071. if ( hasFaceColor ) {
  5072. colorIndex = faces[ offset ++ ];
  5073. color = new THREE.Color( colors[ colorIndex ] );
  5074. face.color = color;
  5075. }
  5076. if ( hasFaceVertexColor ) {
  5077. for ( i = 0; i < nVertices; i++ ) {
  5078. colorIndex = faces[ offset ++ ];
  5079. color = new THREE.Color( colors[ colorIndex ] );
  5080. face.vertexColors.push( color );
  5081. }
  5082. }
  5083. geometry.faces.push( face );
  5084. }
  5085. };
  5086. function parseSkin() {
  5087. var i, l, x, y, z, w, a, b, c, d;
  5088. if ( json.skinWeights ) {
  5089. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5090. x = json.skinWeights[ i ];
  5091. y = json.skinWeights[ i + 1 ];
  5092. z = 0;
  5093. w = 0;
  5094. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5095. }
  5096. }
  5097. if ( json.skinIndices ) {
  5098. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5099. a = json.skinIndices[ i ];
  5100. b = json.skinIndices[ i + 1 ];
  5101. c = 0;
  5102. d = 0;
  5103. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5104. }
  5105. }
  5106. geometry.bones = json.bones;
  5107. geometry.animation = json.animation;
  5108. };
  5109. function parseMorphing( scale ) {
  5110. if ( json.morphTargets !== undefined ) {
  5111. var i, l, v, vl, dstVertices, srcVertices;
  5112. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5113. geometry.morphTargets[ i ] = {};
  5114. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5115. geometry.morphTargets[ i ].vertices = [];
  5116. dstVertices = geometry.morphTargets[ i ].vertices;
  5117. srcVertices = json.morphTargets [ i ].vertices;
  5118. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5119. var vertex = new THREE.Vector3();
  5120. vertex.x = srcVertices[ v ] * scale;
  5121. vertex.y = srcVertices[ v + 1 ] * scale;
  5122. vertex.z = srcVertices[ v + 2 ] * scale;
  5123. dstVertices.push( vertex );
  5124. }
  5125. }
  5126. }
  5127. if ( json.morphColors !== undefined ) {
  5128. var i, l, c, cl, dstColors, srcColors, color;
  5129. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5130. geometry.morphColors[ i ] = {};
  5131. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5132. geometry.morphColors[ i ].colors = [];
  5133. dstColors = geometry.morphColors[ i ].colors;
  5134. srcColors = json.morphColors [ i ].colors;
  5135. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5136. color = new THREE.Color( 0xffaa00 );
  5137. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5138. dstColors.push( color );
  5139. }
  5140. }
  5141. }
  5142. };
  5143. var materials = this.initMaterials( json.materials, texturePath );
  5144. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5145. callback( geometry, materials );
  5146. };
  5147. /**
  5148. * @author mrdoob / http://mrdoob.com/
  5149. */
  5150. THREE.LoadingMonitor = function () {
  5151. THREE.EventTarget.call( this );
  5152. var scope = this;
  5153. var loaded = 0;
  5154. var total = 0;
  5155. var onLoad = function ( event ) {
  5156. loaded ++;
  5157. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5158. if ( loaded === total ) {
  5159. scope.dispatchEvent( { type: 'load' } );
  5160. }
  5161. };
  5162. this.add = function ( loader ) {
  5163. total ++;
  5164. loader.addEventListener( 'load', onLoad, false );
  5165. };
  5166. };
  5167. /**
  5168. * @author alteredq / http://alteredqualia.com/
  5169. */
  5170. THREE.SceneLoader = function () {
  5171. this.onLoadStart = function () {};
  5172. this.onLoadProgress = function() {};
  5173. this.onLoadComplete = function () {};
  5174. this.callbackSync = function () {};
  5175. this.callbackProgress = function () {};
  5176. this.geometryHandlerMap = {};
  5177. this.hierarchyHandlerMap = {};
  5178. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5179. this.addGeometryHandler( "binary", THREE.BinaryLoader );
  5180. };
  5181. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5182. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5183. var scope = this;
  5184. var xhr = new XMLHttpRequest();
  5185. xhr.onreadystatechange = function () {
  5186. if ( xhr.readyState === 4 ) {
  5187. if ( xhr.status === 200 || xhr.status === 0 ) {
  5188. var json = JSON.parse( xhr.responseText );
  5189. scope.parse( json, callbackFinished, url );
  5190. } else {
  5191. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5192. }
  5193. }
  5194. };
  5195. xhr.open( "GET", url, true );
  5196. xhr.send( null );
  5197. };
  5198. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5199. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5200. };
  5201. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5202. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5203. };
  5204. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5205. var scope = this;
  5206. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5207. var dg, dm, dc, df, dt,
  5208. g, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  5209. geometry, material, camera, fog,
  5210. texture, images,
  5211. light, hex, intensity,
  5212. counter_models, counter_textures,
  5213. total_models, total_textures,
  5214. result;
  5215. var target_array = [];
  5216. var data = json;
  5217. // async geometry loaders
  5218. for ( var typeID in this.geometryHandlerMap ) {
  5219. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5220. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5221. }
  5222. // async hierachy loaders
  5223. for ( var typeID in this.hierarchyHandlerMap ) {
  5224. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5225. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5226. }
  5227. counter_models = 0;
  5228. counter_textures = 0;
  5229. result = {
  5230. scene: new THREE.Scene(),
  5231. geometries: {},
  5232. face_materials: {},
  5233. materials: {},
  5234. textures: {},
  5235. objects: {},
  5236. cameras: {},
  5237. lights: {},
  5238. fogs: {},
  5239. empties: {}
  5240. };
  5241. if ( data.transform ) {
  5242. var position = data.transform.position,
  5243. rotation = data.transform.rotation,
  5244. scale = data.transform.scale;
  5245. if ( position )
  5246. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5247. if ( rotation )
  5248. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5249. if ( scale )
  5250. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5251. if ( position || rotation || scale ) {
  5252. result.scene.updateMatrix();
  5253. result.scene.updateMatrixWorld();
  5254. }
  5255. }
  5256. function get_url( source_url, url_type ) {
  5257. if ( url_type == "relativeToHTML" ) {
  5258. return source_url;
  5259. } else {
  5260. return urlBase + "/" + source_url;
  5261. }
  5262. };
  5263. // toplevel loader function, delegates to handle_children
  5264. function handle_objects() {
  5265. handle_children( result.scene, data.objects );
  5266. }
  5267. // handle all the children from the loaded json and attach them to given parent
  5268. function handle_children( parent, children ) {
  5269. for ( var dd in children ) {
  5270. // check by id if child has already been handled,
  5271. // if not, create new object
  5272. if ( result.objects[ dd ] === undefined ) {
  5273. var o = children[ dd ];
  5274. var object = null;
  5275. // meshes
  5276. if ( o.type && ( o.type in scope.hierarchyHandlerMap ) && o.loading === undefined ) {
  5277. var loaderParameters = {};
  5278. for ( var parType in g ) {
  5279. if ( parType !== "type" && parType !== "url" ) {
  5280. loaderParameters[ parType ] = g[ parType ];
  5281. }
  5282. }
  5283. material = result.materials[ o.material ];
  5284. o.loading = true;
  5285. var loader = scope.hierarchyHandlerMap[ o.type ][ "loaderObject" ];
  5286. // OBJLoader
  5287. if ( loader.addEventListener ) {
  5288. loader.addEventListener( 'load', create_callback_hierachy( dd, parent, material, o ) );
  5289. loader.load( get_url( o.url, data.urlBaseType ) );
  5290. } else {
  5291. // ColladaLoader
  5292. if ( loader.options ) {
  5293. loader.load( get_url( o.url, data.urlBaseType ), create_callback_hierachy( dd, parent, material, o ) );
  5294. // UTF8Loader
  5295. } else {
  5296. loader.load( get_url( o.url, data.urlBaseType ), create_callback_hierachy( dd, parent, material, o ), loaderParameters );
  5297. }
  5298. }
  5299. } else if ( o.geometry !== undefined ) {
  5300. geometry = result.geometries[ o.geometry ];
  5301. // geometry already loaded
  5302. if ( geometry ) {
  5303. var needsTangents = false;
  5304. material = result.materials[ o.material ];
  5305. needsTangents = material instanceof THREE.ShaderMaterial;
  5306. p = o.position;
  5307. r = o.rotation;
  5308. q = o.quaternion;
  5309. s = o.scale;
  5310. m = o.matrix;
  5311. // turn off quaternions, for the moment
  5312. q = 0;
  5313. // use materials from the model file
  5314. // if there is no material specified in the object
  5315. if ( ! o.material ) {
  5316. material = new THREE.MeshFaceMaterial( result.face_materials[ o.geometry ] );
  5317. }
  5318. // use materials from the model file
  5319. // if there is just empty face material
  5320. // (must create new material as each model has its own face material)
  5321. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  5322. material = new THREE.MeshFaceMaterial( result.face_materials[ o.geometry ] );
  5323. }
  5324. if ( material instanceof THREE.MeshFaceMaterial ) {
  5325. for ( var i = 0; i < material.materials.length; i ++ ) {
  5326. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  5327. }
  5328. }
  5329. if ( needsTangents ) {
  5330. geometry.computeTangents();
  5331. }
  5332. if ( o.skin ) {
  5333. object = new THREE.SkinnedMesh( geometry, material );
  5334. } else if ( o.morph ) {
  5335. object = new THREE.MorphAnimMesh( geometry, material );
  5336. if ( o.duration !== undefined ) {
  5337. object.duration = o.duration;
  5338. }
  5339. if ( o.time !== undefined ) {
  5340. object.time = o.time;
  5341. }
  5342. if ( o.mirroredLoop !== undefined ) {
  5343. object.mirroredLoop = o.mirroredLoop;
  5344. }
  5345. if ( material.morphNormals ) {
  5346. geometry.computeMorphNormals();
  5347. }
  5348. } else {
  5349. object = new THREE.Mesh( geometry, material );
  5350. }
  5351. object.name = dd;
  5352. if ( m ) {
  5353. object.matrixAutoUpdate = false;
  5354. object.matrix.set(
  5355. m[0], m[1], m[2], m[3],
  5356. m[4], m[5], m[6], m[7],
  5357. m[8], m[9], m[10], m[11],
  5358. m[12], m[13], m[14], m[15]
  5359. );
  5360. } else {
  5361. object.position.set( p[0], p[1], p[2] );
  5362. if ( q ) {
  5363. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5364. object.useQuaternion = true;
  5365. } else {
  5366. object.rotation.set( r[0], r[1], r[2] );
  5367. }
  5368. object.scale.set( s[0], s[1], s[2] );
  5369. }
  5370. object.visible = o.visible;
  5371. object.castShadow = o.castShadow;
  5372. object.receiveShadow = o.receiveShadow;
  5373. parent.add( object );
  5374. result.objects[ dd ] = object;
  5375. }
  5376. // lights
  5377. } else if ( o.type === "DirectionalLight" || o.type === "PointLight" || o.type === "AmbientLight" ) {
  5378. hex = ( o.color !== undefined ) ? o.color : 0xffffff;
  5379. intensity = ( o.intensity !== undefined ) ? o.intensity : 1;
  5380. if ( o.type === "DirectionalLight" ) {
  5381. p = o.direction;
  5382. light = new THREE.DirectionalLight( hex, intensity );
  5383. light.position.set( p[0], p[1], p[2] );
  5384. if ( o.target ) {
  5385. target_array.push( { "object": light, "targetName" : o.target } );
  5386. // kill existing default target
  5387. // otherwise it gets added to scene when parent gets added
  5388. light.target = null;
  5389. }
  5390. } else if ( o.type === "PointLight" ) {
  5391. p = o.position;
  5392. d = o.distance;
  5393. light = new THREE.PointLight( hex, intensity, d );
  5394. light.position.set( p[0], p[1], p[2] );
  5395. } else if ( o.type === "AmbientLight" ) {
  5396. light = new THREE.AmbientLight( hex );
  5397. }
  5398. parent.add( light );
  5399. light.name = dd;
  5400. result.lights[ dd ] = light;
  5401. result.objects[ dd ] = light;
  5402. // cameras
  5403. } else if ( o.type === "PerspectiveCamera" || o.type === "OrthographicCamera" ) {
  5404. if ( o.type === "PerspectiveCamera" ) {
  5405. camera = new THREE.PerspectiveCamera( o.fov, o.aspect, o.near, o.far );
  5406. } else if ( o.type === "OrthographicCamera" ) {
  5407. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  5408. }
  5409. p = o.position;
  5410. camera.position.set( p[0], p[1], p[2] );
  5411. parent.add( camera );
  5412. camera.name = dd;
  5413. result.cameras[ dd ] = camera;
  5414. result.objects[ dd ] = camera;
  5415. // pure Object3D
  5416. } else {
  5417. p = o.position;
  5418. r = o.rotation;
  5419. q = o.quaternion;
  5420. s = o.scale;
  5421. // turn off quaternions, for the moment
  5422. q = 0;
  5423. object = new THREE.Object3D();
  5424. object.name = dd;
  5425. object.position.set( p[0], p[1], p[2] );
  5426. if ( q ) {
  5427. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5428. object.useQuaternion = true;
  5429. } else {
  5430. object.rotation.set( r[0], r[1], r[2] );
  5431. }
  5432. object.scale.set( s[0], s[1], s[2] );
  5433. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  5434. parent.add( object );
  5435. result.objects[ dd ] = object;
  5436. result.empties[ dd ] = object;
  5437. }
  5438. if ( object ) {
  5439. if ( o.properties !== undefined ) {
  5440. for ( var key in o.properties ) {
  5441. var value = o.properties[ key ];
  5442. object.properties[ key ] = value;
  5443. }
  5444. }
  5445. if ( o.children !== undefined ) {
  5446. handle_children( object, o.children );
  5447. }
  5448. }
  5449. }
  5450. }
  5451. };
  5452. function handle_mesh( geo, mat, id ) {
  5453. result.geometries[ id ] = geo;
  5454. result.face_materials[ id ] = mat;
  5455. handle_objects();
  5456. };
  5457. function handle_hierarchy( node, id, parent, material, o ) {
  5458. var p = o.position;
  5459. var r = o.rotation;
  5460. var q = o.quaternion;
  5461. var s = o.scale;
  5462. node.position.set( p[0], p[1], p[2] );
  5463. if ( q ) {
  5464. node.quaternion.set( q[0], q[1], q[2], q[3] );
  5465. node.useQuaternion = true;
  5466. } else {
  5467. node.rotation.set( r[0], r[1], r[2] );
  5468. }
  5469. node.scale.set( s[0], s[1], s[2] );
  5470. if ( material ) {
  5471. node.traverse( function ( child ) {
  5472. child.material = material;
  5473. } );
  5474. }
  5475. parent.add( node );
  5476. result.objects[ id ] = node;
  5477. handle_objects();
  5478. };
  5479. function create_callback_geometry( id ) {
  5480. return function( geo, mat ) {
  5481. handle_mesh( geo, mat, id );
  5482. counter_models -= 1;
  5483. scope.onLoadComplete();
  5484. async_callback_gate();
  5485. }
  5486. };
  5487. function create_callback_hierachy( id, parent, material, obj ) {
  5488. return function( event ) {
  5489. var result;
  5490. // loaders which use EventTarget
  5491. if ( event.content ) {
  5492. result = event.content;
  5493. // ColladaLoader
  5494. } else if ( event.dae ) {
  5495. result = event.scene;
  5496. // UTF8Loader
  5497. } else {
  5498. result = event;
  5499. }
  5500. handle_hierarchy( result, id, parent, material, obj );
  5501. counter_models -= 1;
  5502. scope.onLoadComplete();
  5503. async_callback_gate();
  5504. }
  5505. };
  5506. function create_callback_embed( id ) {
  5507. return function( geo, mat ) {
  5508. result.geometries[ id ] = geo;
  5509. result.face_materials[ id ] = mat;
  5510. }
  5511. };
  5512. function async_callback_gate() {
  5513. var progress = {
  5514. totalModels : total_models,
  5515. totalTextures : total_textures,
  5516. loadedModels : total_models - counter_models,
  5517. loadedTextures : total_textures - counter_textures
  5518. };
  5519. scope.callbackProgress( progress, result );
  5520. scope.onLoadProgress();
  5521. if ( counter_models === 0 && counter_textures === 0 ) {
  5522. finalize();
  5523. callbackFinished( result );
  5524. }
  5525. };
  5526. function finalize() {
  5527. // take care of targets which could be asynchronously loaded objects
  5528. for ( var i = 0; i < target_array.length; i ++ ) {
  5529. var ta = target_array[ i ];
  5530. var target = result.objects[ ta.targetName ];
  5531. if ( target ) {
  5532. ta.object.target = target;
  5533. } else {
  5534. // if there was error and target of specified name doesn't exist in the scene file
  5535. // create instead dummy target
  5536. // (target must be added to scene explicitly as parent is already added)
  5537. ta.object.target = new THREE.Object3D();
  5538. result.scene.add( ta.object.target );
  5539. }
  5540. ta.object.target.properties.targetInverse = ta.object;
  5541. }
  5542. };
  5543. var callbackTexture = function ( count ) {
  5544. counter_textures -= count;
  5545. async_callback_gate();
  5546. scope.onLoadComplete();
  5547. };
  5548. // must use this instead of just directly calling callbackTexture
  5549. // because of closure in the calling context loop
  5550. var generateTextureCallback = function ( count ) {
  5551. return function() {
  5552. callbackTexture( count );
  5553. };
  5554. };
  5555. // first go synchronous elements
  5556. // fogs
  5557. for ( df in data.fogs ) {
  5558. f = data.fogs[ df ];
  5559. if ( f.type === "linear" ) {
  5560. fog = new THREE.Fog( 0x000000, f.near, f.far );
  5561. } else if ( f.type === "exp2" ) {
  5562. fog = new THREE.FogExp2( 0x000000, f.density );
  5563. }
  5564. c = f.color;
  5565. fog.color.setRGB( c[0], c[1], c[2] );
  5566. result.fogs[ df ] = fog;
  5567. }
  5568. // now come potentially asynchronous elements
  5569. // geometries
  5570. // count how many geometries will be loaded asynchronously
  5571. for ( dg in data.geometries ) {
  5572. g = data.geometries[ dg ];
  5573. if ( g.type in this.geometryHandlerMap ) {
  5574. counter_models += 1;
  5575. scope.onLoadStart();
  5576. }
  5577. }
  5578. // count how many hierarchies will be loaded asynchronously
  5579. for ( var dd in data.objects ) {
  5580. var o = data.objects[ dd ];
  5581. if ( o.type && ( o.type in this.hierarchyHandlerMap ) ) {
  5582. counter_models += 1;
  5583. scope.onLoadStart();
  5584. }
  5585. }
  5586. total_models = counter_models;
  5587. for ( dg in data.geometries ) {
  5588. g = data.geometries[ dg ];
  5589. if ( g.type === "cube" ) {
  5590. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.widthSegments, g.heightSegments, g.depthSegments );
  5591. result.geometries[ dg ] = geometry;
  5592. } else if ( g.type === "plane" ) {
  5593. geometry = new THREE.PlaneGeometry( g.width, g.height, g.widthSegments, g.heightSegments );
  5594. result.geometries[ dg ] = geometry;
  5595. } else if ( g.type === "sphere" ) {
  5596. geometry = new THREE.SphereGeometry( g.radius, g.widthSegments, g.heightSegments );
  5597. result.geometries[ dg ] = geometry;
  5598. } else if ( g.type === "cylinder" ) {
  5599. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  5600. result.geometries[ dg ] = geometry;
  5601. } else if ( g.type === "torus" ) {
  5602. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  5603. result.geometries[ dg ] = geometry;
  5604. } else if ( g.type === "icosahedron" ) {
  5605. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  5606. result.geometries[ dg ] = geometry;
  5607. } else if ( g.type in this.geometryHandlerMap ) {
  5608. var loaderParameters = {};
  5609. for ( var parType in g ) {
  5610. if ( parType !== "type" && parType !== "url" ) {
  5611. loaderParameters[ parType ] = g[ parType ];
  5612. }
  5613. }
  5614. var loader = this.geometryHandlerMap[ g.type ][ "loaderObject" ];
  5615. loader.load( get_url( g.url, data.urlBaseType ), create_callback_geometry( dg ), loaderParameters );
  5616. } else if ( g.type === "embedded" ) {
  5617. var modelJson = data.embeds[ g.id ],
  5618. texture_path = "";
  5619. // pass metadata along to jsonLoader so it knows the format version
  5620. modelJson.metadata = data.metadata;
  5621. if ( modelJson ) {
  5622. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  5623. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  5624. }
  5625. }
  5626. }
  5627. // textures
  5628. // count how many textures will be loaded asynchronously
  5629. for ( dt in data.textures ) {
  5630. tt = data.textures[ dt ];
  5631. if ( tt.url instanceof Array ) {
  5632. counter_textures += tt.url.length;
  5633. for( var n = 0; n < tt.url.length; n ++ ) {
  5634. scope.onLoadStart();
  5635. }
  5636. } else {
  5637. counter_textures += 1;
  5638. scope.onLoadStart();
  5639. }
  5640. }
  5641. total_textures = counter_textures;
  5642. for ( dt in data.textures ) {
  5643. tt = data.textures[ dt ];
  5644. if ( tt.mapping !== undefined && THREE[ tt.mapping ] !== undefined ) {
  5645. tt.mapping = new THREE[ tt.mapping ]();
  5646. }
  5647. if ( tt.url instanceof Array ) {
  5648. var count = tt.url.length;
  5649. var url_array = [];
  5650. for( var i = 0; i < count; i ++ ) {
  5651. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  5652. }
  5653. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  5654. if ( isCompressed ) {
  5655. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5656. } else {
  5657. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5658. }
  5659. } else {
  5660. var isCompressed = tt.url.toLowerCase().endsWith( ".dds" );
  5661. var fullUrl = get_url( tt.url, data.urlBaseType );
  5662. var textureCallback = generateTextureCallback( 1 );
  5663. if ( isCompressed ) {
  5664. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, tt.mapping, textureCallback );
  5665. } else {
  5666. texture = THREE.ImageUtils.loadTexture( fullUrl, tt.mapping, textureCallback );
  5667. }
  5668. if ( THREE[ tt.minFilter ] !== undefined )
  5669. texture.minFilter = THREE[ tt.minFilter ];
  5670. if ( THREE[ tt.magFilter ] !== undefined )
  5671. texture.magFilter = THREE[ tt.magFilter ];
  5672. if ( tt.anisotropy ) texture.anisotropy = tt.anisotropy;
  5673. if ( tt.repeat ) {
  5674. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  5675. if ( tt.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  5676. if ( tt.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  5677. }
  5678. if ( tt.offset ) {
  5679. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  5680. }
  5681. // handle wrap after repeat so that default repeat can be overriden
  5682. if ( tt.wrap ) {
  5683. var wrapMap = {
  5684. "repeat" : THREE.RepeatWrapping,
  5685. "mirror" : THREE.MirroredRepeatWrapping
  5686. }
  5687. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  5688. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  5689. }
  5690. }
  5691. result.textures[ dt ] = texture;
  5692. }
  5693. // materials
  5694. for ( dm in data.materials ) {
  5695. m = data.materials[ dm ];
  5696. for ( pp in m.parameters ) {
  5697. if ( pp === "envMap" || pp === "map" || pp === "lightMap" || pp === "bumpMap" ) {
  5698. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  5699. } else if ( pp === "shading" ) {
  5700. m.parameters[ pp ] = ( m.parameters[ pp ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  5701. } else if ( pp === "side" ) {
  5702. if ( m.parameters[ pp ] == "double" ) {
  5703. m.parameters[ pp ] = THREE.DoubleSide;
  5704. } else if ( m.parameters[ pp ] == "back" ) {
  5705. m.parameters[ pp ] = THREE.BackSide;
  5706. } else {
  5707. m.parameters[ pp ] = THREE.FrontSide;
  5708. }
  5709. } else if ( pp === "blending" ) {
  5710. m.parameters[ pp ] = m.parameters[ pp ] in THREE ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  5711. } else if ( pp === "combine" ) {
  5712. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  5713. } else if ( pp === "vertexColors" ) {
  5714. if ( m.parameters[ pp ] == "face" ) {
  5715. m.parameters[ pp ] = THREE.FaceColors;
  5716. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  5717. } else if ( m.parameters[ pp ] ) {
  5718. m.parameters[ pp ] = THREE.VertexColors;
  5719. }
  5720. } else if ( pp === "wrapRGB" ) {
  5721. var v3 = m.parameters[ pp ];
  5722. m.parameters[ pp ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  5723. }
  5724. }
  5725. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  5726. m.parameters.transparent = true;
  5727. }
  5728. if ( m.parameters.normalMap ) {
  5729. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5730. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5731. var diffuse = m.parameters.color;
  5732. var specular = m.parameters.specular;
  5733. var ambient = m.parameters.ambient;
  5734. var shininess = m.parameters.shininess;
  5735. uniforms[ "tNormal" ].value = result.textures[ m.parameters.normalMap ];
  5736. if ( m.parameters.normalScale ) {
  5737. uniforms[ "uNormalScale" ].value.set( m.parameters.normalScale[ 0 ], m.parameters.normalScale[ 1 ] );
  5738. }
  5739. if ( m.parameters.map ) {
  5740. uniforms[ "tDiffuse" ].value = m.parameters.map;
  5741. uniforms[ "enableDiffuse" ].value = true;
  5742. }
  5743. if ( m.parameters.envMap ) {
  5744. uniforms[ "tCube" ].value = m.parameters.envMap;
  5745. uniforms[ "enableReflection" ].value = true;
  5746. uniforms[ "uReflectivity" ].value = m.parameters.reflectivity;
  5747. }
  5748. if ( m.parameters.lightMap ) {
  5749. uniforms[ "tAO" ].value = m.parameters.lightMap;
  5750. uniforms[ "enableAO" ].value = true;
  5751. }
  5752. if ( m.parameters.specularMap ) {
  5753. uniforms[ "tSpecular" ].value = result.textures[ m.parameters.specularMap ];
  5754. uniforms[ "enableSpecular" ].value = true;
  5755. }
  5756. if ( m.parameters.displacementMap ) {
  5757. uniforms[ "tDisplacement" ].value = result.textures[ m.parameters.displacementMap ];
  5758. uniforms[ "enableDisplacement" ].value = true;
  5759. uniforms[ "uDisplacementBias" ].value = m.parameters.displacementBias;
  5760. uniforms[ "uDisplacementScale" ].value = m.parameters.displacementScale;
  5761. }
  5762. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  5763. uniforms[ "uSpecularColor" ].value.setHex( specular );
  5764. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  5765. uniforms[ "uShininess" ].value = shininess;
  5766. if ( m.parameters.opacity ) {
  5767. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  5768. }
  5769. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5770. material = new THREE.ShaderMaterial( parameters );
  5771. } else {
  5772. material = new THREE[ m.type ]( m.parameters );
  5773. }
  5774. result.materials[ dm ] = material;
  5775. }
  5776. // second pass through all materials to initialize MeshFaceMaterials
  5777. // that could be referring to other materials out of order
  5778. for ( dm in data.materials ) {
  5779. m = data.materials[ dm ];
  5780. if ( m.parameters.materials ) {
  5781. var materialArray = [];
  5782. for ( var i = 0; i < m.parameters.materials.length; i ++ ) {
  5783. var label = m.parameters.materials[ i ];
  5784. materialArray.push( result.materials[ label ] );
  5785. }
  5786. result.materials[ dm ].materials = materialArray;
  5787. }
  5788. }
  5789. // objects ( synchronous init of procedural primitives )
  5790. handle_objects();
  5791. // defaults
  5792. if ( result.cameras && data.defaults.camera ) {
  5793. result.currentCamera = result.cameras[ data.defaults.camera ];
  5794. }
  5795. if ( result.fogs && data.defaults.fog ) {
  5796. result.scene.fog = result.fogs[ data.defaults.fog ];
  5797. }
  5798. c = data.defaults.bgcolor;
  5799. result.bgColor = new THREE.Color();
  5800. result.bgColor.setRGB( c[0], c[1], c[2] );
  5801. result.bgColorAlpha = data.defaults.bgalpha;
  5802. // synchronous callback
  5803. scope.callbackSync( result );
  5804. // just in case there are no async elements
  5805. async_callback_gate();
  5806. };
  5807. /**
  5808. * @author mrdoob / http://mrdoob.com/
  5809. */
  5810. THREE.TextureLoader = function () {
  5811. THREE.EventTarget.call( this );
  5812. this.crossOrigin = null;
  5813. };
  5814. THREE.TextureLoader.prototype = {
  5815. constructor: THREE.TextureLoader,
  5816. load: function ( url ) {
  5817. var scope = this;
  5818. var image = new Image();
  5819. image.addEventListener( 'load', function () {
  5820. var texture = new THREE.Texture( image );
  5821. texture.needsUpdate = true;
  5822. scope.dispatchEvent( { type: 'load', content: texture } );
  5823. }, false );
  5824. image.addEventListener( 'error', function () {
  5825. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5826. }, false );
  5827. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5828. image.src = url;
  5829. }
  5830. }
  5831. /**
  5832. * @author mrdoob / http://mrdoob.com/
  5833. * @author alteredq / http://alteredqualia.com/
  5834. */
  5835. THREE.Material = function () {
  5836. THREE.MaterialLibrary.push( this );
  5837. this.id = THREE.MaterialIdCount ++;
  5838. this.name = '';
  5839. this.side = THREE.FrontSide;
  5840. this.opacity = 1;
  5841. this.transparent = false;
  5842. this.blending = THREE.NormalBlending;
  5843. this.blendSrc = THREE.SrcAlphaFactor;
  5844. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  5845. this.blendEquation = THREE.AddEquation;
  5846. this.depthTest = true;
  5847. this.depthWrite = true;
  5848. this.polygonOffset = false;
  5849. this.polygonOffsetFactor = 0;
  5850. this.polygonOffsetUnits = 0;
  5851. this.alphaTest = 0;
  5852. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  5853. this.visible = true;
  5854. this.needsUpdate = true;
  5855. };
  5856. THREE.Material.prototype.setValues = function ( values ) {
  5857. if ( values === undefined ) return;
  5858. for ( var key in values ) {
  5859. var newValue = values[ key ];
  5860. if ( newValue === undefined ) {
  5861. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5862. continue;
  5863. }
  5864. if ( key in this ) {
  5865. var currentValue = this[ key ];
  5866. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  5867. currentValue.copy( newValue );
  5868. } else if ( currentValue instanceof THREE.Color && typeof( newValue ) === "number" ) {
  5869. currentValue.setHex( newValue );
  5870. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  5871. currentValue.copy( newValue );
  5872. } else {
  5873. this[ key ] = newValue;
  5874. }
  5875. }
  5876. }
  5877. };
  5878. THREE.Material.prototype.clone = function ( material ) {
  5879. if ( material === undefined ) material = new THREE.Material();
  5880. material.name = this.name;
  5881. material.side = this.side;
  5882. material.opacity = this.opacity;
  5883. material.transparent = this.transparent;
  5884. material.blending = this.blending;
  5885. material.blendSrc = this.blendSrc;
  5886. material.blendDst = this.blendDst;
  5887. material.blendEquation = this.blendEquation;
  5888. material.depthTest = this.depthTest;
  5889. material.depthWrite = this.depthWrite;
  5890. material.polygonOffset = this.polygonOffset;
  5891. material.polygonOffsetFactor = this.polygonOffsetFactor;
  5892. material.polygonOffsetUnits = this.polygonOffsetUnits;
  5893. material.alphaTest = this.alphaTest;
  5894. material.overdraw = this.overdraw;
  5895. material.visible = this.visible;
  5896. return material;
  5897. };
  5898. THREE.Material.prototype.deallocate = function () {
  5899. var index = THREE.MaterialLibrary.indexOf( this );
  5900. if ( index !== -1 ) THREE.MaterialLibrary.splice( index, 1 );
  5901. };
  5902. THREE.MaterialIdCount = 0;
  5903. THREE.MaterialLibrary = [];
  5904. /**
  5905. * @author mrdoob / http://mrdoob.com/
  5906. * @author alteredq / http://alteredqualia.com/
  5907. *
  5908. * parameters = {
  5909. * color: <hex>,
  5910. * opacity: <float>,
  5911. *
  5912. * blending: THREE.NormalBlending,
  5913. * depthTest: <bool>,
  5914. * depthWrite: <bool>,
  5915. *
  5916. * linewidth: <float>,
  5917. * linecap: "round",
  5918. * linejoin: "round",
  5919. *
  5920. * vertexColors: <bool>
  5921. *
  5922. * fog: <bool>
  5923. * }
  5924. */
  5925. THREE.LineBasicMaterial = function ( parameters ) {
  5926. THREE.Material.call( this );
  5927. this.color = new THREE.Color( 0xffffff );
  5928. this.linewidth = 1;
  5929. this.linecap = 'round';
  5930. this.linejoin = 'round';
  5931. this.vertexColors = false;
  5932. this.fog = true;
  5933. this.setValues( parameters );
  5934. };
  5935. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  5936. THREE.LineBasicMaterial.prototype.clone = function () {
  5937. var material = new THREE.LineBasicMaterial();
  5938. THREE.Material.prototype.clone.call( this, material );
  5939. material.color.copy( this.color );
  5940. material.linewidth = this.linewidth;
  5941. material.linecap = this.linecap;
  5942. material.linejoin = this.linejoin;
  5943. material.vertexColors = this.vertexColors;
  5944. material.fog = this.fog;
  5945. return material;
  5946. };
  5947. /**
  5948. * @author alteredq / http://alteredqualia.com/
  5949. *
  5950. * parameters = {
  5951. * color: <hex>,
  5952. * opacity: <float>,
  5953. *
  5954. * blending: THREE.NormalBlending,
  5955. * depthTest: <bool>,
  5956. * depthWrite: <bool>,
  5957. *
  5958. * linewidth: <float>,
  5959. *
  5960. * scale: <float>,
  5961. * dashSize: <float>,
  5962. * gapSize: <float>,
  5963. *
  5964. * vertexColors: <bool>
  5965. *
  5966. * fog: <bool>
  5967. * }
  5968. */
  5969. THREE.LineDashedMaterial = function ( parameters ) {
  5970. THREE.Material.call( this );
  5971. this.color = new THREE.Color( 0xffffff );
  5972. this.linewidth = 1;
  5973. this.scale = 1;
  5974. this.dashSize = 3;
  5975. this.gapSize = 1;
  5976. this.vertexColors = false;
  5977. this.fog = true;
  5978. this.setValues( parameters );
  5979. };
  5980. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  5981. THREE.LineDashedMaterial.prototype.clone = function () {
  5982. var material = new THREE.LineDashedMaterial();
  5983. THREE.Material.prototype.clone.call( this, material );
  5984. material.color.copy( this.color );
  5985. material.linewidth = this.linewidth;
  5986. material.scale = this.scale;
  5987. material.dashSize = this.dashSize;
  5988. material.gapSize = this.gapSize;
  5989. material.vertexColors = this.vertexColors;
  5990. material.fog = this.fog;
  5991. return material;
  5992. };
  5993. /**
  5994. * @author mrdoob / http://mrdoob.com/
  5995. * @author alteredq / http://alteredqualia.com/
  5996. *
  5997. * parameters = {
  5998. * color: <hex>,
  5999. * opacity: <float>,
  6000. * map: new THREE.Texture( <Image> ),
  6001. *
  6002. * lightMap: new THREE.Texture( <Image> ),
  6003. *
  6004. * specularMap: new THREE.Texture( <Image> ),
  6005. *
  6006. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6007. * combine: THREE.Multiply,
  6008. * reflectivity: <float>,
  6009. * refractionRatio: <float>,
  6010. *
  6011. * shading: THREE.SmoothShading,
  6012. * blending: THREE.NormalBlending,
  6013. * depthTest: <bool>,
  6014. * depthWrite: <bool>,
  6015. *
  6016. * wireframe: <boolean>,
  6017. * wireframeLinewidth: <float>,
  6018. *
  6019. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6020. *
  6021. * skinning: <bool>,
  6022. * morphTargets: <bool>,
  6023. *
  6024. * fog: <bool>
  6025. * }
  6026. */
  6027. THREE.MeshBasicMaterial = function ( parameters ) {
  6028. THREE.Material.call( this );
  6029. this.color = new THREE.Color( 0xffffff ); // emissive
  6030. this.map = null;
  6031. this.lightMap = null;
  6032. this.specularMap = null;
  6033. this.envMap = null;
  6034. this.combine = THREE.MultiplyOperation;
  6035. this.reflectivity = 1;
  6036. this.refractionRatio = 0.98;
  6037. this.fog = true;
  6038. this.shading = THREE.SmoothShading;
  6039. this.wireframe = false;
  6040. this.wireframeLinewidth = 1;
  6041. this.wireframeLinecap = 'round';
  6042. this.wireframeLinejoin = 'round';
  6043. this.vertexColors = THREE.NoColors;
  6044. this.skinning = false;
  6045. this.morphTargets = false;
  6046. this.setValues( parameters );
  6047. };
  6048. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6049. THREE.MeshBasicMaterial.prototype.clone = function () {
  6050. var material = new THREE.MeshBasicMaterial();
  6051. THREE.Material.prototype.clone.call( this, material );
  6052. material.color.copy( this.color );
  6053. material.map = this.map;
  6054. material.lightMap = this.lightMap;
  6055. material.specularMap = this.specularMap;
  6056. material.envMap = this.envMap;
  6057. material.combine = this.combine;
  6058. material.reflectivity = this.reflectivity;
  6059. material.refractionRatio = this.refractionRatio;
  6060. material.fog = this.fog;
  6061. material.shading = this.shading;
  6062. material.wireframe = this.wireframe;
  6063. material.wireframeLinewidth = this.wireframeLinewidth;
  6064. material.wireframeLinecap = this.wireframeLinecap;
  6065. material.wireframeLinejoin = this.wireframeLinejoin;
  6066. material.vertexColors = this.vertexColors;
  6067. material.skinning = this.skinning;
  6068. material.morphTargets = this.morphTargets;
  6069. return material;
  6070. };
  6071. /**
  6072. * @author mrdoob / http://mrdoob.com/
  6073. * @author alteredq / http://alteredqualia.com/
  6074. *
  6075. * parameters = {
  6076. * color: <hex>,
  6077. * ambient: <hex>,
  6078. * emissive: <hex>,
  6079. * opacity: <float>,
  6080. *
  6081. * map: new THREE.Texture( <Image> ),
  6082. *
  6083. * lightMap: new THREE.Texture( <Image> ),
  6084. *
  6085. * specularMap: new THREE.Texture( <Image> ),
  6086. *
  6087. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6088. * combine: THREE.Multiply,
  6089. * reflectivity: <float>,
  6090. * refractionRatio: <float>,
  6091. *
  6092. * shading: THREE.SmoothShading,
  6093. * blending: THREE.NormalBlending,
  6094. * depthTest: <bool>,
  6095. * depthWrite: <bool>,
  6096. *
  6097. * wireframe: <boolean>,
  6098. * wireframeLinewidth: <float>,
  6099. *
  6100. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6101. *
  6102. * skinning: <bool>,
  6103. * morphTargets: <bool>,
  6104. * morphNormals: <bool>,
  6105. *
  6106. * fog: <bool>
  6107. * }
  6108. */
  6109. THREE.MeshLambertMaterial = function ( parameters ) {
  6110. THREE.Material.call( this );
  6111. this.color = new THREE.Color( 0xffffff ); // diffuse
  6112. this.ambient = new THREE.Color( 0xffffff );
  6113. this.emissive = new THREE.Color( 0x000000 );
  6114. this.wrapAround = false;
  6115. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6116. this.map = null;
  6117. this.lightMap = null;
  6118. this.specularMap = null;
  6119. this.envMap = null;
  6120. this.combine = THREE.MultiplyOperation;
  6121. this.reflectivity = 1;
  6122. this.refractionRatio = 0.98;
  6123. this.fog = true;
  6124. this.shading = THREE.SmoothShading;
  6125. this.wireframe = false;
  6126. this.wireframeLinewidth = 1;
  6127. this.wireframeLinecap = 'round';
  6128. this.wireframeLinejoin = 'round';
  6129. this.vertexColors = THREE.NoColors;
  6130. this.skinning = false;
  6131. this.morphTargets = false;
  6132. this.morphNormals = false;
  6133. this.setValues( parameters );
  6134. };
  6135. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6136. THREE.MeshLambertMaterial.prototype.clone = function () {
  6137. var material = new THREE.MeshLambertMaterial();
  6138. THREE.Material.prototype.clone.call( this, material );
  6139. material.color.copy( this.color );
  6140. material.ambient.copy( this.ambient );
  6141. material.emissive.copy( this.emissive );
  6142. material.wrapAround = this.wrapAround;
  6143. material.wrapRGB.copy( this.wrapRGB );
  6144. material.map = this.map;
  6145. material.lightMap = this.lightMap;
  6146. material.specularMap = this.specularMap;
  6147. material.envMap = this.envMap;
  6148. material.combine = this.combine;
  6149. material.reflectivity = this.reflectivity;
  6150. material.refractionRatio = this.refractionRatio;
  6151. material.fog = this.fog;
  6152. material.shading = this.shading;
  6153. material.wireframe = this.wireframe;
  6154. material.wireframeLinewidth = this.wireframeLinewidth;
  6155. material.wireframeLinecap = this.wireframeLinecap;
  6156. material.wireframeLinejoin = this.wireframeLinejoin;
  6157. material.vertexColors = this.vertexColors;
  6158. material.skinning = this.skinning;
  6159. material.morphTargets = this.morphTargets;
  6160. material.morphNormals = this.morphNormals;
  6161. return material;
  6162. };
  6163. /**
  6164. * @author mrdoob / http://mrdoob.com/
  6165. * @author alteredq / http://alteredqualia.com/
  6166. *
  6167. * parameters = {
  6168. * color: <hex>,
  6169. * ambient: <hex>,
  6170. * emissive: <hex>,
  6171. * specular: <hex>,
  6172. * shininess: <float>,
  6173. * opacity: <float>,
  6174. *
  6175. * map: new THREE.Texture( <Image> ),
  6176. *
  6177. * lightMap: new THREE.Texture( <Image> ),
  6178. *
  6179. * bumpMap: new THREE.Texture( <Image> ),
  6180. * bumpScale: <float>,
  6181. *
  6182. * normalMap: new THREE.Texture( <Image> ),
  6183. * normalScale: <Vector2>,
  6184. *
  6185. * specularMap: new THREE.Texture( <Image> ),
  6186. *
  6187. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6188. * combine: THREE.Multiply,
  6189. * reflectivity: <float>,
  6190. * refractionRatio: <float>,
  6191. *
  6192. * shading: THREE.SmoothShading,
  6193. * blending: THREE.NormalBlending,
  6194. * depthTest: <bool>,
  6195. * depthWrite: <bool>,
  6196. *
  6197. * wireframe: <boolean>,
  6198. * wireframeLinewidth: <float>,
  6199. *
  6200. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6201. *
  6202. * skinning: <bool>,
  6203. * morphTargets: <bool>,
  6204. * morphNormals: <bool>,
  6205. *
  6206. * fog: <bool>
  6207. * }
  6208. */
  6209. THREE.MeshPhongMaterial = function ( parameters ) {
  6210. THREE.Material.call( this );
  6211. this.color = new THREE.Color( 0xffffff ); // diffuse
  6212. this.ambient = new THREE.Color( 0xffffff );
  6213. this.emissive = new THREE.Color( 0x000000 );
  6214. this.specular = new THREE.Color( 0x111111 );
  6215. this.shininess = 30;
  6216. this.metal = false;
  6217. this.perPixel = true;
  6218. this.wrapAround = false;
  6219. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6220. this.map = null;
  6221. this.lightMap = null;
  6222. this.bumpMap = null;
  6223. this.bumpScale = 1;
  6224. this.normalMap = null;
  6225. this.normalScale = new THREE.Vector2( 1, 1 );
  6226. this.specularMap = null;
  6227. this.envMap = null;
  6228. this.combine = THREE.MultiplyOperation;
  6229. this.reflectivity = 1;
  6230. this.refractionRatio = 0.98;
  6231. this.fog = true;
  6232. this.shading = THREE.SmoothShading;
  6233. this.wireframe = false;
  6234. this.wireframeLinewidth = 1;
  6235. this.wireframeLinecap = 'round';
  6236. this.wireframeLinejoin = 'round';
  6237. this.vertexColors = THREE.NoColors;
  6238. this.skinning = false;
  6239. this.morphTargets = false;
  6240. this.morphNormals = false;
  6241. this.setValues( parameters );
  6242. };
  6243. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6244. THREE.MeshPhongMaterial.prototype.clone = function () {
  6245. var material = new THREE.MeshPhongMaterial();
  6246. THREE.Material.prototype.clone.call( this, material );
  6247. material.color.copy( this.color );
  6248. material.ambient.copy( this.ambient );
  6249. material.emissive.copy( this.emissive );
  6250. material.specular.copy( this.specular );
  6251. material.shininess = this.shininess;
  6252. material.metal = this.metal;
  6253. material.perPixel = this.perPixel;
  6254. material.wrapAround = this.wrapAround;
  6255. material.wrapRGB.copy( this.wrapRGB );
  6256. material.map = this.map;
  6257. material.lightMap = this.lightMap;
  6258. material.bumpMap = this.bumpMap;
  6259. material.bumpScale = this.bumpScale;
  6260. material.normalMap = this.normalMap;
  6261. material.normalScale.copy( this.normalScale );
  6262. material.specularMap = this.specularMap;
  6263. material.envMap = this.envMap;
  6264. material.combine = this.combine;
  6265. material.reflectivity = this.reflectivity;
  6266. material.refractionRatio = this.refractionRatio;
  6267. material.fog = this.fog;
  6268. material.shading = this.shading;
  6269. material.wireframe = this.wireframe;
  6270. material.wireframeLinewidth = this.wireframeLinewidth;
  6271. material.wireframeLinecap = this.wireframeLinecap;
  6272. material.wireframeLinejoin = this.wireframeLinejoin;
  6273. material.vertexColors = this.vertexColors;
  6274. material.skinning = this.skinning;
  6275. material.morphTargets = this.morphTargets;
  6276. material.morphNormals = this.morphNormals;
  6277. return material;
  6278. };
  6279. /**
  6280. * @author mrdoob / http://mrdoob.com/
  6281. * @author alteredq / http://alteredqualia.com/
  6282. *
  6283. * parameters = {
  6284. * opacity: <float>,
  6285. *
  6286. * blending: THREE.NormalBlending,
  6287. * depthTest: <bool>,
  6288. * depthWrite: <bool>,
  6289. *
  6290. * wireframe: <boolean>,
  6291. * wireframeLinewidth: <float>
  6292. * }
  6293. */
  6294. THREE.MeshDepthMaterial = function ( parameters ) {
  6295. THREE.Material.call( this );
  6296. this.wireframe = false;
  6297. this.wireframeLinewidth = 1;
  6298. this.setValues( parameters );
  6299. };
  6300. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6301. THREE.MeshDepthMaterial.prototype.clone = function () {
  6302. var material = new THREE.LineBasicMaterial();
  6303. THREE.Material.prototype.clone.call( this, material );
  6304. material.wireframe = this.wireframe;
  6305. material.wireframeLinewidth = this.wireframeLinewidth;
  6306. return material;
  6307. };
  6308. /**
  6309. * @author mrdoob / http://mrdoob.com/
  6310. *
  6311. * parameters = {
  6312. * opacity: <float>,
  6313. *
  6314. * shading: THREE.FlatShading,
  6315. * blending: THREE.NormalBlending,
  6316. * depthTest: <bool>,
  6317. * depthWrite: <bool>,
  6318. *
  6319. * wireframe: <boolean>,
  6320. * wireframeLinewidth: <float>
  6321. * }
  6322. */
  6323. THREE.MeshNormalMaterial = function ( parameters ) {
  6324. THREE.Material.call( this, parameters );
  6325. this.shading = THREE.FlatShading;
  6326. this.wireframe = false;
  6327. this.wireframeLinewidth = 1;
  6328. this.setValues( parameters );
  6329. };
  6330. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  6331. THREE.MeshNormalMaterial.prototype.clone = function () {
  6332. var material = new THREE.MeshNormalMaterial();
  6333. THREE.Material.prototype.clone.call( this, material );
  6334. material.shading = this.shading;
  6335. material.wireframe = this.wireframe;
  6336. material.wireframeLinewidth = this.wireframeLinewidth;
  6337. return material;
  6338. };
  6339. /**
  6340. * @author mrdoob / http://mrdoob.com/
  6341. */
  6342. THREE.MeshFaceMaterial = function ( materials ) {
  6343. this.materials = materials instanceof Array ? materials : [];
  6344. };
  6345. THREE.MeshFaceMaterial.prototype.clone = function () {
  6346. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  6347. };
  6348. /**
  6349. * @author mrdoob / http://mrdoob.com/
  6350. * @author alteredq / http://alteredqualia.com/
  6351. *
  6352. * parameters = {
  6353. * color: <hex>,
  6354. * opacity: <float>,
  6355. * map: new THREE.Texture( <Image> ),
  6356. *
  6357. * size: <float>,
  6358. *
  6359. * blending: THREE.NormalBlending,
  6360. * depthTest: <bool>,
  6361. * depthWrite: <bool>,
  6362. *
  6363. * vertexColors: <bool>,
  6364. *
  6365. * fog: <bool>
  6366. * }
  6367. */
  6368. THREE.ParticleBasicMaterial = function ( parameters ) {
  6369. THREE.Material.call( this );
  6370. this.color = new THREE.Color( 0xffffff );
  6371. this.map = null;
  6372. this.size = 1;
  6373. this.sizeAttenuation = true;
  6374. this.vertexColors = false;
  6375. this.fog = true;
  6376. this.setValues( parameters );
  6377. };
  6378. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6379. THREE.ParticleBasicMaterial.prototype.clone = function () {
  6380. var material = new THREE.ParticleBasicMaterial();
  6381. THREE.Material.prototype.clone.call( this, material );
  6382. material.color.copy( this.color );
  6383. material.map = this.map;
  6384. material.size = this.size;
  6385. material.sizeAttenuation = this.sizeAttenuation;
  6386. material.vertexColors = this.vertexColors;
  6387. material.fog = this.fog;
  6388. return material;
  6389. };
  6390. /**
  6391. * @author mrdoob / http://mrdoob.com/
  6392. *
  6393. * parameters = {
  6394. * color: <hex>,
  6395. * program: <function>,
  6396. * opacity: <float>,
  6397. * blending: THREE.NormalBlending
  6398. * }
  6399. */
  6400. THREE.ParticleCanvasMaterial = function ( parameters ) {
  6401. THREE.Material.call( this );
  6402. this.color = new THREE.Color( 0xffffff );
  6403. this.program = function ( context, color ) {};
  6404. this.setValues( parameters );
  6405. };
  6406. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  6407. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  6408. var material = new THREE.ParticleCanvasMaterial();
  6409. THREE.Material.prototype.clone.call( this, material );
  6410. material.color.copy( this.color );
  6411. material.program = this.program;
  6412. return material;
  6413. };
  6414. /**
  6415. * @author mrdoob / http://mrdoob.com/
  6416. */
  6417. THREE.ParticleDOMMaterial = function ( element ) {
  6418. this.element = element;
  6419. };
  6420. THREE.ParticleDOMMaterial.prototype.clone = function(){
  6421. return new THREE.ParticleDOMMaterial( this.element );
  6422. };
  6423. /**
  6424. * @author alteredq / http://alteredqualia.com/
  6425. *
  6426. * parameters = {
  6427. * fragmentShader: <string>,
  6428. * vertexShader: <string>,
  6429. *
  6430. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  6431. *
  6432. * defines: { "label" : "value" },
  6433. *
  6434. * shading: THREE.SmoothShading,
  6435. * blending: THREE.NormalBlending,
  6436. * depthTest: <bool>,
  6437. * depthWrite: <bool>,
  6438. *
  6439. * wireframe: <boolean>,
  6440. * wireframeLinewidth: <float>,
  6441. *
  6442. * lights: <bool>,
  6443. *
  6444. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6445. *
  6446. * skinning: <bool>,
  6447. * morphTargets: <bool>,
  6448. * morphNormals: <bool>,
  6449. *
  6450. * fog: <bool>
  6451. * }
  6452. */
  6453. THREE.ShaderMaterial = function ( parameters ) {
  6454. THREE.Material.call( this );
  6455. this.fragmentShader = "void main() {}";
  6456. this.vertexShader = "void main() {}";
  6457. this.uniforms = {};
  6458. this.defines = {};
  6459. this.attributes = null;
  6460. this.shading = THREE.SmoothShading;
  6461. this.wireframe = false;
  6462. this.wireframeLinewidth = 1;
  6463. this.fog = false; // set to use scene fog
  6464. this.lights = false; // set to use scene lights
  6465. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  6466. this.skinning = false; // set to use skinning attribute streams
  6467. this.morphTargets = false; // set to use morph targets
  6468. this.morphNormals = false; // set to use morph normals
  6469. this.setValues( parameters );
  6470. };
  6471. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  6472. THREE.ShaderMaterial.prototype.clone = function () {
  6473. var material = new THREE.ShaderMaterial();
  6474. THREE.Material.prototype.clone.call( this, material );
  6475. material.fragmentShader = this.fragmentShader;
  6476. material.vertexShader = this.vertexShader;
  6477. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  6478. material.attributes = this.attributes;
  6479. material.defines = this.defines;
  6480. material.shading = this.shading;
  6481. material.wireframe = this.wireframe;
  6482. material.wireframeLinewidth = this.wireframeLinewidth;
  6483. material.fog = this.fog;
  6484. material.lights = this.lights;
  6485. material.vertexColors = this.vertexColors;
  6486. material.skinning = this.skinning;
  6487. material.morphTargets = this.morphTargets;
  6488. material.morphNormals = this.morphNormals;
  6489. return material;
  6490. };
  6491. /**
  6492. * @author alteredq / http://alteredqualia.com/
  6493. *
  6494. * parameters = {
  6495. * color: <hex>,
  6496. * opacity: <float>,
  6497. * map: new THREE.Texture( <Image> ),
  6498. *
  6499. * blending: THREE.NormalBlending,
  6500. * depthTest: <bool>,
  6501. * depthWrite: <bool>,
  6502. *
  6503. * useScreenCoordinates: <bool>,
  6504. * sizeAttenuation: <bool>,
  6505. * scaleByViewport: <bool>,
  6506. * alignment: THREE.SpriteAlignment.center,
  6507. *
  6508. * uvOffset: new THREE.Vector2(),
  6509. * uvScale: new THREE.Vector2(),
  6510. *
  6511. * fog: <bool>
  6512. * }
  6513. */
  6514. THREE.SpriteMaterial = function ( parameters ) {
  6515. THREE.Material.call( this );
  6516. // defaults
  6517. this.color = new THREE.Color( 0xffffff );
  6518. this.map = new THREE.Texture();
  6519. this.useScreenCoordinates = true;
  6520. this.depthTest = !this.useScreenCoordinates;
  6521. this.sizeAttenuation = !this.useScreenCoordinates;
  6522. this.scaleByViewport = !this.sizeAttenuation;
  6523. this.alignment = THREE.SpriteAlignment.center.clone();
  6524. this.fog = false;
  6525. this.uvOffset = new THREE.Vector2( 0, 0 );
  6526. this.uvScale = new THREE.Vector2( 1, 1 );
  6527. // set parameters
  6528. this.setValues( parameters );
  6529. // override coupled defaults if not specified explicitly by parameters
  6530. parameters = parameters || {};
  6531. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  6532. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  6533. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  6534. };
  6535. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  6536. THREE.SpriteMaterial.prototype.clone = function () {
  6537. var material = new THREE.SpriteMaterial();
  6538. THREE.Material.prototype.clone.call( this, material );
  6539. material.color.copy( this.color );
  6540. material.map = this.map;
  6541. material.useScreenCoordinates = this.useScreenCoordinates;
  6542. material.sizeAttenuation = this.sizeAttenuation;
  6543. material.scaleByViewport = this.scaleByViewport;
  6544. material.alignment.copy( this.alignment );
  6545. material.uvOffset.copy( this.uvOffset );
  6546. material.uvScale.copy( this.uvScale );
  6547. material.fog = this.fog;
  6548. return material;
  6549. };
  6550. // Alignment enums
  6551. THREE.SpriteAlignment = {};
  6552. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  6553. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  6554. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  6555. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  6556. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  6557. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  6558. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  6559. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  6560. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  6561. /**
  6562. * @author mrdoob / http://mrdoob.com/
  6563. * @author alteredq / http://alteredqualia.com/
  6564. * @author szimek / https://github.com/szimek/
  6565. */
  6566. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  6567. THREE.TextureLibrary.push( this );
  6568. this.id = THREE.TextureIdCount ++;
  6569. this.name = '';
  6570. this.image = image;
  6571. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  6572. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  6573. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  6574. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  6575. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  6576. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6577. this.format = format !== undefined ? format : THREE.RGBAFormat;
  6578. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  6579. this.offset = new THREE.Vector2( 0, 0 );
  6580. this.repeat = new THREE.Vector2( 1, 1 );
  6581. this.generateMipmaps = true;
  6582. this.premultiplyAlpha = false;
  6583. this.flipY = true;
  6584. this.needsUpdate = false;
  6585. this.onUpdate = null;
  6586. };
  6587. THREE.Texture.prototype = {
  6588. constructor: THREE.Texture,
  6589. clone: function () {
  6590. var texture = new THREE.Texture();
  6591. texture.image = this.image;
  6592. texture.mapping = this.mapping;
  6593. texture.wrapS = this.wrapS;
  6594. texture.wrapT = this.wrapT;
  6595. texture.magFilter = this.magFilter;
  6596. texture.minFilter = this.minFilter;
  6597. texture.anisotropy = this.anisotropy;
  6598. texture.format = this.format;
  6599. texture.type = this.type;
  6600. texture.offset.copy( this.offset );
  6601. texture.repeat.copy( this.repeat );
  6602. texture.generateMipmaps = this.generateMipmaps;
  6603. texture.premultiplyAlpha = this.premultiplyAlpha;
  6604. texture.flipY = this.flipY;
  6605. return texture;
  6606. },
  6607. deallocate: function () {
  6608. var index = THREE.TextureLibrary.indexOf( this );
  6609. if ( index !== -1 ) THREE.TextureLibrary.splice( index, 1 );
  6610. }
  6611. };
  6612. THREE.TextureIdCount = 0;
  6613. THREE.TextureLibrary = [];
  6614. /**
  6615. * @author alteredq / http://alteredqualia.com/
  6616. */
  6617. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  6618. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  6619. this.image = { width: width, height: height };
  6620. this.mipmaps = mipmaps;
  6621. };
  6622. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  6623. THREE.CompressedTexture.prototype.clone = function () {
  6624. var texture = new THREE.CompressedTexture();
  6625. texture.image = this.image;
  6626. texture.mipmaps = this.mipmaps;
  6627. texture.format = this.format;
  6628. texture.type = this.type;
  6629. texture.mapping = this.mapping;
  6630. texture.wrapS = this.wrapS;
  6631. texture.wrapT = this.wrapT;
  6632. texture.magFilter = this.magFilter;
  6633. texture.minFilter = this.minFilter;
  6634. texture.anisotropy = this.anisotropy;
  6635. texture.offset.copy( this.offset );
  6636. texture.repeat.copy( this.repeat );
  6637. return texture;
  6638. };
  6639. /**
  6640. * @author alteredq / http://alteredqualia.com/
  6641. */
  6642. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  6643. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  6644. this.image = { data: data, width: width, height: height };
  6645. };
  6646. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  6647. THREE.DataTexture.prototype.clone = function () {
  6648. 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 );
  6649. clonedTexture.offset.copy( this.offset );
  6650. clonedTexture.repeat.copy( this.repeat );
  6651. return clonedTexture;
  6652. };
  6653. /**
  6654. * @author mrdoob / http://mrdoob.com/
  6655. */
  6656. THREE.Particle = function ( material ) {
  6657. THREE.Object3D.call( this );
  6658. this.material = material;
  6659. };
  6660. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  6661. THREE.Particle.prototype.clone = function ( object ) {
  6662. if ( object === undefined ) object = new THREE.Particle( this.material );
  6663. THREE.Object3D.prototype.clone.call( this, object );
  6664. return object;
  6665. };
  6666. /**
  6667. * @author alteredq / http://alteredqualia.com/
  6668. */
  6669. THREE.ParticleSystem = function ( geometry, material ) {
  6670. THREE.Object3D.call( this );
  6671. this.geometry = geometry;
  6672. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  6673. this.sortParticles = false;
  6674. if ( this.geometry ) {
  6675. // calc bound radius
  6676. if( this.geometry.boundingSphere === null ) {
  6677. this.geometry.computeBoundingSphere();
  6678. }
  6679. this.boundRadius = geometry.boundingSphere.radius;
  6680. }
  6681. this.frustumCulled = false;
  6682. };
  6683. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  6684. THREE.ParticleSystem.prototype.clone = function ( object ) {
  6685. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  6686. object.sortParticles = this.sortParticles;
  6687. THREE.Object3D.prototype.clone.call( this, object );
  6688. return object;
  6689. };
  6690. /**
  6691. * @author mrdoob / http://mrdoob.com/
  6692. */
  6693. THREE.Line = function ( geometry, material, type ) {
  6694. THREE.Object3D.call( this );
  6695. this.geometry = geometry;
  6696. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  6697. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  6698. if ( this.geometry ) {
  6699. if ( ! this.geometry.boundingSphere ) {
  6700. this.geometry.computeBoundingSphere();
  6701. }
  6702. }
  6703. };
  6704. THREE.LineStrip = 0;
  6705. THREE.LinePieces = 1;
  6706. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  6707. THREE.Line.prototype.clone = function ( object ) {
  6708. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  6709. THREE.Object3D.prototype.clone.call( this, object );
  6710. return object;
  6711. };
  6712. /**
  6713. * @author mrdoob / http://mrdoob.com/
  6714. * @author alteredq / http://alteredqualia.com/
  6715. * @author mikael emtinger / http://gomo.se/
  6716. */
  6717. THREE.Mesh = function ( geometry, material ) {
  6718. THREE.Object3D.call( this );
  6719. this.geometry = geometry;
  6720. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  6721. if ( this.geometry ) {
  6722. // calc bound radius
  6723. if ( this.geometry.boundingSphere === null ) {
  6724. this.geometry.computeBoundingSphere();
  6725. }
  6726. this.boundRadius = geometry.boundingSphere.radius;
  6727. // setup morph targets
  6728. if ( this.geometry.morphTargets.length ) {
  6729. this.morphTargetBase = -1;
  6730. this.morphTargetForcedOrder = [];
  6731. this.morphTargetInfluences = [];
  6732. this.morphTargetDictionary = {};
  6733. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  6734. this.morphTargetInfluences.push( 0 );
  6735. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  6736. }
  6737. }
  6738. }
  6739. }
  6740. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  6741. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  6742. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  6743. return this.morphTargetDictionary[ name ];
  6744. }
  6745. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  6746. return 0;
  6747. };
  6748. THREE.Mesh.prototype.clone = function ( object ) {
  6749. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  6750. THREE.Object3D.prototype.clone.call( this, object );
  6751. return object;
  6752. };
  6753. /**
  6754. * @author mikael emtinger / http://gomo.se/
  6755. * @author alteredq / http://alteredqualia.com/
  6756. */
  6757. THREE.Bone = function( belongsToSkin ) {
  6758. THREE.Object3D.call( this );
  6759. this.skin = belongsToSkin;
  6760. this.skinMatrix = new THREE.Matrix4();
  6761. };
  6762. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  6763. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  6764. // update local
  6765. if ( this.matrixAutoUpdate ) {
  6766. forceUpdate |= this.updateMatrix();
  6767. }
  6768. // update skin matrix
  6769. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  6770. if( parentSkinMatrix ) {
  6771. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  6772. } else {
  6773. this.skinMatrix.copy( this.matrix );
  6774. }
  6775. this.matrixWorldNeedsUpdate = false;
  6776. forceUpdate = true;
  6777. }
  6778. // update children
  6779. var child, i, l = this.children.length;
  6780. for ( i = 0; i < l; i ++ ) {
  6781. this.children[ i ].update( this.skinMatrix, forceUpdate );
  6782. }
  6783. };
  6784. /**
  6785. * @author mikael emtinger / http://gomo.se/
  6786. * @author alteredq / http://alteredqualia.com/
  6787. */
  6788. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  6789. THREE.Mesh.call( this, geometry, material );
  6790. //
  6791. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  6792. // init bones
  6793. this.identityMatrix = new THREE.Matrix4();
  6794. this.bones = [];
  6795. this.boneMatrices = [];
  6796. var b, bone, gbone, p, q, s;
  6797. if ( this.geometry && this.geometry.bones !== undefined ) {
  6798. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  6799. gbone = this.geometry.bones[ b ];
  6800. p = gbone.pos;
  6801. q = gbone.rotq;
  6802. s = gbone.scl;
  6803. bone = this.addBone();
  6804. bone.name = gbone.name;
  6805. bone.position.set( p[0], p[1], p[2] );
  6806. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  6807. bone.useQuaternion = true;
  6808. if ( s !== undefined ) {
  6809. bone.scale.set( s[0], s[1], s[2] );
  6810. } else {
  6811. bone.scale.set( 1, 1, 1 );
  6812. }
  6813. }
  6814. for ( b = 0; b < this.bones.length; b ++ ) {
  6815. gbone = this.geometry.bones[ b ];
  6816. bone = this.bones[ b ];
  6817. if ( gbone.parent === -1 ) {
  6818. this.add( bone );
  6819. } else {
  6820. this.bones[ gbone.parent ].add( bone );
  6821. }
  6822. }
  6823. //
  6824. var nBones = this.bones.length;
  6825. if ( this.useVertexTexture ) {
  6826. // layout (1 matrix = 4 pixels)
  6827. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  6828. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  6829. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  6830. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  6831. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  6832. var size;
  6833. if ( nBones > 256 )
  6834. size = 64;
  6835. else if ( nBones > 64 )
  6836. size = 32;
  6837. else if ( nBones > 16 )
  6838. size = 16;
  6839. else
  6840. size = 8;
  6841. this.boneTextureWidth = size;
  6842. this.boneTextureHeight = size;
  6843. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  6844. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  6845. this.boneTexture.minFilter = THREE.NearestFilter;
  6846. this.boneTexture.magFilter = THREE.NearestFilter;
  6847. this.boneTexture.generateMipmaps = false;
  6848. this.boneTexture.flipY = false;
  6849. } else {
  6850. this.boneMatrices = new Float32Array( 16 * nBones );
  6851. }
  6852. this.pose();
  6853. }
  6854. };
  6855. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  6856. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  6857. if ( bone === undefined ) {
  6858. bone = new THREE.Bone( this );
  6859. }
  6860. this.bones.push( bone );
  6861. return bone;
  6862. };
  6863. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  6864. this.matrixAutoUpdate && this.updateMatrix();
  6865. // update matrixWorld
  6866. if ( this.matrixWorldNeedsUpdate || force ) {
  6867. if ( this.parent ) {
  6868. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  6869. } else {
  6870. this.matrixWorld.copy( this.matrix );
  6871. }
  6872. this.matrixWorldNeedsUpdate = false;
  6873. force = true;
  6874. }
  6875. // update children
  6876. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6877. var child = this.children[ i ];
  6878. if ( child instanceof THREE.Bone ) {
  6879. child.update( this.identityMatrix, false );
  6880. } else {
  6881. child.updateMatrixWorld( true );
  6882. }
  6883. }
  6884. // make a snapshot of the bones' rest position
  6885. if ( this.boneInverses == undefined ) {
  6886. this.boneInverses = [];
  6887. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6888. var inverse = new THREE.Matrix4();
  6889. inverse.getInverse( this.bones[ b ].skinMatrix );
  6890. this.boneInverses.push( inverse );
  6891. }
  6892. }
  6893. // flatten bone matrices to array
  6894. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6895. // compute the offset between the current and the original transform;
  6896. //TODO: we could get rid of this multiplication step if the skinMatrix
  6897. // was already representing the offset; however, this requires some
  6898. // major changes to the animation system
  6899. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  6900. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  6901. }
  6902. if ( this.useVertexTexture ) {
  6903. this.boneTexture.needsUpdate = true;
  6904. }
  6905. };
  6906. THREE.SkinnedMesh.prototype.pose = function() {
  6907. this.updateMatrixWorld( true );
  6908. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  6909. // normalize weights
  6910. var sw = this.geometry.skinWeights[ i ];
  6911. var scale = 1.0 / sw.lengthManhattan();
  6912. if ( scale !== Infinity ) {
  6913. sw.multiplyScalar( scale );
  6914. } else {
  6915. sw.set( 1 ); // this will be normalized by the shader anyway
  6916. }
  6917. }
  6918. };
  6919. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  6920. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  6921. THREE.Mesh.prototype.clone.call( this, object );
  6922. return object;
  6923. };
  6924. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  6925. /**
  6926. * @author alteredq / http://alteredqualia.com/
  6927. */
  6928. THREE.MorphAnimMesh = function ( geometry, material ) {
  6929. THREE.Mesh.call( this, geometry, material );
  6930. // API
  6931. this.duration = 1000; // milliseconds
  6932. this.mirroredLoop = false;
  6933. this.time = 0;
  6934. // internals
  6935. this.lastKeyframe = 0;
  6936. this.currentKeyframe = 0;
  6937. this.direction = 1;
  6938. this.directionBackwards = false;
  6939. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  6940. };
  6941. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  6942. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  6943. this.startKeyframe = start;
  6944. this.endKeyframe = end;
  6945. this.length = this.endKeyframe - this.startKeyframe + 1;
  6946. };
  6947. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  6948. this.direction = 1;
  6949. this.directionBackwards = false;
  6950. };
  6951. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  6952. this.direction = -1;
  6953. this.directionBackwards = true;
  6954. };
  6955. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  6956. var geometry = this.geometry;
  6957. if ( ! geometry.animations ) geometry.animations = {};
  6958. var firstAnimation, animations = geometry.animations;
  6959. var pattern = /([a-z]+)(\d+)/;
  6960. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  6961. var morph = geometry.morphTargets[ i ];
  6962. var parts = morph.name.match( pattern );
  6963. if ( parts && parts.length > 1 ) {
  6964. var label = parts[ 1 ];
  6965. var num = parts[ 2 ];
  6966. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  6967. var animation = animations[ label ];
  6968. if ( i < animation.start ) animation.start = i;
  6969. if ( i > animation.end ) animation.end = i;
  6970. if ( ! firstAnimation ) firstAnimation = label;
  6971. }
  6972. }
  6973. geometry.firstAnimation = firstAnimation;
  6974. };
  6975. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  6976. if ( ! this.geometry.animations ) this.geometry.animations = {};
  6977. this.geometry.animations[ label ] = { start: start, end: end };
  6978. };
  6979. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  6980. var animation = this.geometry.animations[ label ];
  6981. if ( animation ) {
  6982. this.setFrameRange( animation.start, animation.end );
  6983. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  6984. this.time = 0;
  6985. } else {
  6986. console.warn( "animation[" + label + "] undefined" );
  6987. }
  6988. };
  6989. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  6990. var frameTime = this.duration / this.length;
  6991. this.time += this.direction * delta;
  6992. if ( this.mirroredLoop ) {
  6993. if ( this.time > this.duration || this.time < 0 ) {
  6994. this.direction *= -1;
  6995. if ( this.time > this.duration ) {
  6996. this.time = this.duration;
  6997. this.directionBackwards = true;
  6998. }
  6999. if ( this.time < 0 ) {
  7000. this.time = 0;
  7001. this.directionBackwards = false;
  7002. }
  7003. }
  7004. } else {
  7005. this.time = this.time % this.duration;
  7006. if ( this.time < 0 ) this.time += this.duration;
  7007. }
  7008. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7009. if ( keyframe !== this.currentKeyframe ) {
  7010. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7011. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7012. this.morphTargetInfluences[ keyframe ] = 0;
  7013. this.lastKeyframe = this.currentKeyframe;
  7014. this.currentKeyframe = keyframe;
  7015. }
  7016. var mix = ( this.time % frameTime ) / frameTime;
  7017. if ( this.directionBackwards ) {
  7018. mix = 1 - mix;
  7019. }
  7020. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7021. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7022. };
  7023. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7024. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7025. object.duration = this.duration;
  7026. object.mirroredLoop = this.mirroredLoop;
  7027. object.time = this.time;
  7028. object.lastKeyframe = this.lastKeyframe;
  7029. object.currentKeyframe = this.currentKeyframe;
  7030. object.direction = this.direction;
  7031. object.directionBackwards = this.directionBackwards;
  7032. THREE.Mesh.prototype.clone.call( this, object );
  7033. return object;
  7034. };
  7035. /**
  7036. * @author alteredq / http://alteredqualia.com/
  7037. */
  7038. THREE.Ribbon = function ( geometry, material ) {
  7039. THREE.Object3D.call( this );
  7040. this.geometry = geometry;
  7041. this.material = material;
  7042. };
  7043. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7044. THREE.Ribbon.prototype.clone = function ( object ) {
  7045. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7046. THREE.Object3D.prototype.clone.call( this, object );
  7047. return object;
  7048. };
  7049. /**
  7050. * @author mikael emtinger / http://gomo.se/
  7051. * @author alteredq / http://alteredqualia.com/
  7052. * @author mrdoob / http://mrdoob.com/
  7053. */
  7054. THREE.LOD = function () {
  7055. THREE.Object3D.call( this );
  7056. this.LODs = [];
  7057. };
  7058. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7059. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7060. if ( visibleAtDistance === undefined ) {
  7061. visibleAtDistance = 0;
  7062. }
  7063. visibleAtDistance = Math.abs( visibleAtDistance );
  7064. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7065. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7066. break;
  7067. }
  7068. }
  7069. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7070. this.add( object3D );
  7071. };
  7072. THREE.LOD.prototype.update = function ( camera ) {
  7073. if ( this.LODs.length > 1 ) {
  7074. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7075. var inverse = camera.matrixWorldInverse;
  7076. 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] );
  7077. this.LODs[ 0 ].object3D.visible = true;
  7078. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7079. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7080. this.LODs[ l - 1 ].object3D.visible = false;
  7081. this.LODs[ l ].object3D.visible = true;
  7082. } else {
  7083. break;
  7084. }
  7085. }
  7086. for( ; l < this.LODs.length; l ++ ) {
  7087. this.LODs[ l ].object3D.visible = false;
  7088. }
  7089. }
  7090. };
  7091. THREE.LOD.prototype.clone = function () {
  7092. // TODO
  7093. };
  7094. /**
  7095. * @author mikael emtinger / http://gomo.se/
  7096. * @author alteredq / http://alteredqualia.com/
  7097. */
  7098. THREE.Sprite = function ( material ) {
  7099. THREE.Object3D.call( this );
  7100. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7101. this.rotation3d = this.rotation;
  7102. this.rotation = 0;
  7103. };
  7104. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7105. /*
  7106. * Custom update matrix
  7107. */
  7108. THREE.Sprite.prototype.updateMatrix = function () {
  7109. this.matrix.setPosition( this.position );
  7110. this.rotation3d.set( 0, 0, this.rotation );
  7111. this.matrix.setRotationFromEuler( this.rotation3d );
  7112. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7113. this.matrix.scale( this.scale );
  7114. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  7115. }
  7116. this.matrixWorldNeedsUpdate = true;
  7117. };
  7118. THREE.Sprite.prototype.clone = function ( object ) {
  7119. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7120. THREE.Object3D.prototype.clone.call( this, object );
  7121. return object;
  7122. };
  7123. /**
  7124. * @author mrdoob / http://mrdoob.com/
  7125. */
  7126. THREE.Scene = function () {
  7127. THREE.Object3D.call( this );
  7128. this.fog = null;
  7129. this.overrideMaterial = null;
  7130. this.matrixAutoUpdate = false;
  7131. this.__objects = [];
  7132. this.__lights = [];
  7133. this.__objectsAdded = [];
  7134. this.__objectsRemoved = [];
  7135. };
  7136. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7137. THREE.Scene.prototype.__addObject = function ( object ) {
  7138. if ( object instanceof THREE.Light ) {
  7139. if ( this.__lights.indexOf( object ) === - 1 ) {
  7140. this.__lights.push( object );
  7141. }
  7142. if ( object.target && object.target.parent === undefined ) {
  7143. this.add( object.target );
  7144. }
  7145. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7146. if ( this.__objects.indexOf( object ) === - 1 ) {
  7147. this.__objects.push( object );
  7148. this.__objectsAdded.push( object );
  7149. // check if previously removed
  7150. var i = this.__objectsRemoved.indexOf( object );
  7151. if ( i !== -1 ) {
  7152. this.__objectsRemoved.splice( i, 1 );
  7153. }
  7154. }
  7155. }
  7156. for ( var c = 0; c < object.children.length; c ++ ) {
  7157. this.__addObject( object.children[ c ] );
  7158. }
  7159. };
  7160. THREE.Scene.prototype.__removeObject = function ( object ) {
  7161. if ( object instanceof THREE.Light ) {
  7162. var i = this.__lights.indexOf( object );
  7163. if ( i !== -1 ) {
  7164. this.__lights.splice( i, 1 );
  7165. }
  7166. } else if ( !( object instanceof THREE.Camera ) ) {
  7167. var i = this.__objects.indexOf( object );
  7168. if( i !== -1 ) {
  7169. this.__objects.splice( i, 1 );
  7170. this.__objectsRemoved.push( object );
  7171. // check if previously added
  7172. var ai = this.__objectsAdded.indexOf( object );
  7173. if ( ai !== -1 ) {
  7174. this.__objectsAdded.splice( ai, 1 );
  7175. }
  7176. }
  7177. }
  7178. for ( var c = 0; c < object.children.length; c ++ ) {
  7179. this.__removeObject( object.children[ c ] );
  7180. }
  7181. };
  7182. /**
  7183. * @author mrdoob / http://mrdoob.com/
  7184. * @author alteredq / http://alteredqualia.com/
  7185. */
  7186. THREE.Fog = function ( hex, near, far ) {
  7187. this.name = '';
  7188. this.color = new THREE.Color( hex );
  7189. this.near = ( near !== undefined ) ? near : 1;
  7190. this.far = ( far !== undefined ) ? far : 1000;
  7191. };
  7192. THREE.Fog.prototype.clone = function () {
  7193. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7194. };
  7195. /**
  7196. * @author mrdoob / http://mrdoob.com/
  7197. * @author alteredq / http://alteredqualia.com/
  7198. */
  7199. THREE.FogExp2 = function ( hex, density ) {
  7200. this.name = '';
  7201. this.color = new THREE.Color( hex );
  7202. this.density = ( density !== undefined ) ? density : 0.00025;
  7203. };
  7204. THREE.FogExp2.prototype.clone = function () {
  7205. return new THREE.FogExp2( this.color.getHex(), this.density );
  7206. };
  7207. /**
  7208. * @author mrdoob / http://mrdoob.com/
  7209. */
  7210. THREE.CanvasRenderer = function ( parameters ) {
  7211. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7212. parameters = parameters || {};
  7213. var _this = this,
  7214. _renderData, _elements, _lights,
  7215. _projector = new THREE.Projector(),
  7216. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  7217. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7218. _context = _canvas.getContext( '2d' ),
  7219. _clearColor = new THREE.Color( 0x000000 ),
  7220. _clearOpacity = 0,
  7221. _contextGlobalAlpha = 1,
  7222. _contextGlobalCompositeOperation = 0,
  7223. _contextStrokeStyle = null,
  7224. _contextFillStyle = null,
  7225. _contextLineWidth = null,
  7226. _contextLineCap = null,
  7227. _contextLineJoin = null,
  7228. _v1, _v2, _v3, _v4,
  7229. _v5 = new THREE.RenderableVertex(),
  7230. _v6 = new THREE.RenderableVertex(),
  7231. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7232. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7233. _color = new THREE.Color(),
  7234. _color1 = new THREE.Color(),
  7235. _color2 = new THREE.Color(),
  7236. _color3 = new THREE.Color(),
  7237. _color4 = new THREE.Color(),
  7238. _diffuseColor = new THREE.Color(),
  7239. _emissiveColor = new THREE.Color(),
  7240. _patterns = {}, _imagedatas = {},
  7241. _near, _far,
  7242. _image, _uvs,
  7243. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7244. _clipRect = new THREE.Rectangle(),
  7245. _clearRect = new THREE.Rectangle(),
  7246. _bboxRect = new THREE.Rectangle(),
  7247. _enableLighting = false,
  7248. _ambientLight = new THREE.Color(),
  7249. _directionalLights = new THREE.Color(),
  7250. _pointLights = new THREE.Color(),
  7251. _pi2 = Math.PI * 2,
  7252. _vector3 = new THREE.Vector3(), // Needed for PointLight
  7253. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  7254. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  7255. _pixelMap = document.createElement( 'canvas' );
  7256. _pixelMap.width = _pixelMap.height = 2;
  7257. _pixelMapContext = _pixelMap.getContext( '2d' );
  7258. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  7259. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  7260. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  7261. _pixelMapData = _pixelMapImage.data;
  7262. _gradientMap = document.createElement( 'canvas' );
  7263. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  7264. _gradientMapContext = _gradientMap.getContext( '2d' );
  7265. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  7266. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  7267. _gradientMapQuality --; // Fix UVs
  7268. this.domElement = _canvas;
  7269. this.autoClear = true;
  7270. this.sortObjects = true;
  7271. this.sortElements = true;
  7272. this.info = {
  7273. render: {
  7274. vertices: 0,
  7275. faces: 0
  7276. }
  7277. }
  7278. this.setSize = function ( width, height ) {
  7279. _canvasWidth = width;
  7280. _canvasHeight = height;
  7281. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  7282. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  7283. _canvas.width = _canvasWidth;
  7284. _canvas.height = _canvasHeight;
  7285. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7286. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7287. _contextGlobalAlpha = 1;
  7288. _contextGlobalCompositeOperation = 0;
  7289. _contextStrokeStyle = null;
  7290. _contextFillStyle = null;
  7291. _contextLineWidth = null;
  7292. _contextLineCap = null;
  7293. _contextLineJoin = null;
  7294. };
  7295. this.setClearColor = function ( color, opacity ) {
  7296. _clearColor.copy( color );
  7297. _clearOpacity = opacity !== undefined ? opacity : 1;
  7298. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7299. };
  7300. this.setClearColorHex = function ( hex, opacity ) {
  7301. _clearColor.setHex( hex );
  7302. _clearOpacity = opacity !== undefined ? opacity : 1;
  7303. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7304. };
  7305. this.getMaxAnisotropy = function () {
  7306. return 0;
  7307. };
  7308. this.clear = function () {
  7309. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7310. if ( _clearRect.isEmpty() === false ) {
  7311. _clearRect.minSelf( _clipRect );
  7312. _clearRect.inflate( 2 );
  7313. if ( _clearOpacity < 1 ) {
  7314. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7315. }
  7316. if ( _clearOpacity > 0 ) {
  7317. setBlending( THREE.NormalBlending );
  7318. setOpacity( 1 );
  7319. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  7320. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7321. }
  7322. _clearRect.empty();
  7323. }
  7324. };
  7325. this.render = function ( scene, camera ) {
  7326. if ( camera instanceof THREE.Camera === false ) {
  7327. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  7328. return;
  7329. }
  7330. var e, el, element, material;
  7331. this.autoClear === true
  7332. ? this.clear()
  7333. : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7334. _this.info.render.vertices = 0;
  7335. _this.info.render.faces = 0;
  7336. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  7337. _elements = _renderData.elements;
  7338. _lights = _renderData.lights;
  7339. /* DEBUG
  7340. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  7341. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  7342. */
  7343. _enableLighting = _lights.length > 0;
  7344. if ( _enableLighting === true ) {
  7345. calculateLights();
  7346. }
  7347. for ( e = 0, el = _elements.length; e < el; e++ ) {
  7348. element = _elements[ e ];
  7349. material = element.material;
  7350. if ( material === undefined || material.visible === false ) continue;
  7351. _bboxRect.empty();
  7352. if ( element instanceof THREE.RenderableParticle ) {
  7353. _v1 = element;
  7354. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  7355. renderParticle( _v1, element, material, scene );
  7356. } else if ( element instanceof THREE.RenderableLine ) {
  7357. _v1 = element.v1; _v2 = element.v2;
  7358. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7359. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7360. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7361. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7362. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7363. renderLine( _v1, _v2, element, material, scene );
  7364. }
  7365. } else if ( element instanceof THREE.RenderableFace3 ) {
  7366. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  7367. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7368. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7369. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7370. if ( material.overdraw === true ) {
  7371. expand( _v1.positionScreen, _v2.positionScreen );
  7372. expand( _v2.positionScreen, _v3.positionScreen );
  7373. expand( _v3.positionScreen, _v1.positionScreen );
  7374. }
  7375. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  7376. _v2.positionScreen.x, _v2.positionScreen.y,
  7377. _v3.positionScreen.x, _v3.positionScreen.y );
  7378. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7379. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  7380. }
  7381. } else if ( element instanceof THREE.RenderableFace4 ) {
  7382. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  7383. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7384. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7385. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7386. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  7387. _v5.positionScreen.copy( _v2.positionScreen );
  7388. _v6.positionScreen.copy( _v4.positionScreen );
  7389. if ( material.overdraw === true ) {
  7390. expand( _v1.positionScreen, _v2.positionScreen );
  7391. expand( _v2.positionScreen, _v4.positionScreen );
  7392. expand( _v4.positionScreen, _v1.positionScreen );
  7393. expand( _v3.positionScreen, _v5.positionScreen );
  7394. expand( _v3.positionScreen, _v6.positionScreen );
  7395. }
  7396. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7397. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7398. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  7399. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  7400. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7401. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  7402. }
  7403. }
  7404. /* DEBUG
  7405. _context.lineWidth = 1;
  7406. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  7407. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  7408. */
  7409. _clearRect.addRectangle( _bboxRect );
  7410. }
  7411. /* DEBUG
  7412. _context.lineWidth = 1;
  7413. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  7414. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  7415. */
  7416. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  7417. //
  7418. function calculateLights() {
  7419. _ambientLight.setRGB( 0, 0, 0 );
  7420. _directionalLights.setRGB( 0, 0, 0 );
  7421. _pointLights.setRGB( 0, 0, 0 );
  7422. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7423. var light = _lights[ l ];
  7424. var lightColor = light.color;
  7425. if ( light instanceof THREE.AmbientLight ) {
  7426. _ambientLight.r += lightColor.r;
  7427. _ambientLight.g += lightColor.g;
  7428. _ambientLight.b += lightColor.b;
  7429. } else if ( light instanceof THREE.DirectionalLight ) {
  7430. // for particles
  7431. _directionalLights.r += lightColor.r;
  7432. _directionalLights.g += lightColor.g;
  7433. _directionalLights.b += lightColor.b;
  7434. } else if ( light instanceof THREE.PointLight ) {
  7435. // for particles
  7436. _pointLights.r += lightColor.r;
  7437. _pointLights.g += lightColor.g;
  7438. _pointLights.b += lightColor.b;
  7439. }
  7440. }
  7441. }
  7442. function calculateLight( position, normal, color ) {
  7443. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7444. var light = _lights[ l ];
  7445. var lightColor = light.color;
  7446. if ( light instanceof THREE.DirectionalLight ) {
  7447. var lightPosition = light.matrixWorld.getPosition().normalize();
  7448. var amount = normal.dot( lightPosition );
  7449. if ( amount <= 0 ) continue;
  7450. amount *= light.intensity;
  7451. color.r += lightColor.r * amount;
  7452. color.g += lightColor.g * amount;
  7453. color.b += lightColor.b * amount;
  7454. } else if ( light instanceof THREE.PointLight ) {
  7455. var lightPosition = light.matrixWorld.getPosition();
  7456. var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  7457. if ( amount <= 0 ) continue;
  7458. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  7459. if ( amount == 0 ) continue;
  7460. amount *= light.intensity;
  7461. color.r += lightColor.r * amount;
  7462. color.g += lightColor.g * amount;
  7463. color.b += lightColor.b * amount;
  7464. }
  7465. }
  7466. }
  7467. function renderParticle( v1, element, material, scene ) {
  7468. setOpacity( material.opacity );
  7469. setBlending( material.blending );
  7470. var width, height, scaleX, scaleY,
  7471. bitmap, bitmapWidth, bitmapHeight;
  7472. if ( material instanceof THREE.ParticleBasicMaterial ) {
  7473. if ( material.map === null ) {
  7474. scaleX = element.object.scale.x;
  7475. scaleY = element.object.scale.y;
  7476. // TODO: Be able to disable this
  7477. scaleX *= element.scale.x * _canvasWidthHalf;
  7478. scaleY *= element.scale.y * _canvasHeightHalf;
  7479. _bboxRect.set( v1.x - scaleX, v1.y - scaleY, v1.x + scaleX, v1.y + scaleY );
  7480. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7481. return;
  7482. }
  7483. setFillStyle( material.color.getContextStyle() );
  7484. _context.save();
  7485. _context.translate( v1.x, v1.y );
  7486. _context.rotate( - element.rotation );
  7487. _context.scale( scaleX, scaleY );
  7488. _context.fillRect( -1, -1, 2, 2 );
  7489. _context.restore();
  7490. } else {
  7491. bitmap = material.map.image;
  7492. bitmapWidth = bitmap.width >> 1;
  7493. bitmapHeight = bitmap.height >> 1;
  7494. scaleX = element.scale.x * _canvasWidthHalf;
  7495. scaleY = element.scale.y * _canvasHeightHalf;
  7496. width = scaleX * bitmapWidth;
  7497. height = scaleY * bitmapHeight;
  7498. // TODO: Rotations break this...
  7499. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7500. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7501. return;
  7502. }
  7503. _context.save();
  7504. _context.translate( v1.x, v1.y );
  7505. _context.rotate( - element.rotation );
  7506. _context.scale( scaleX, - scaleY );
  7507. _context.translate( - bitmapWidth, - bitmapHeight );
  7508. _context.drawImage( bitmap, 0, 0 );
  7509. _context.restore();
  7510. }
  7511. /* DEBUG
  7512. setStrokeStyle( 'rgb(255,255,0)' );
  7513. _context.beginPath();
  7514. _context.moveTo( v1.x - 10, v1.y );
  7515. _context.lineTo( v1.x + 10, v1.y );
  7516. _context.moveTo( v1.x, v1.y - 10 );
  7517. _context.lineTo( v1.x, v1.y + 10 );
  7518. _context.stroke();
  7519. */
  7520. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  7521. width = element.scale.x * _canvasWidthHalf;
  7522. height = element.scale.y * _canvasHeightHalf;
  7523. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7524. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7525. return;
  7526. }
  7527. setStrokeStyle( material.color.getContextStyle() );
  7528. setFillStyle( material.color.getContextStyle() );
  7529. _context.save();
  7530. _context.translate( v1.x, v1.y );
  7531. _context.rotate( - element.rotation );
  7532. _context.scale( width, height );
  7533. material.program( _context );
  7534. _context.restore();
  7535. }
  7536. }
  7537. function renderLine( v1, v2, element, material, scene ) {
  7538. setOpacity( material.opacity );
  7539. setBlending( material.blending );
  7540. _context.beginPath();
  7541. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  7542. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  7543. if ( material instanceof THREE.LineBasicMaterial ) {
  7544. setLineWidth( material.linewidth );
  7545. setLineCap( material.linecap );
  7546. setLineJoin( material.linejoin );
  7547. setStrokeStyle( material.color.getContextStyle() );
  7548. _context.stroke();
  7549. _bboxRect.inflate( material.linewidth * 2 );
  7550. }
  7551. }
  7552. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  7553. _this.info.render.vertices += 3;
  7554. _this.info.render.faces ++;
  7555. setOpacity( material.opacity );
  7556. setBlending( material.blending );
  7557. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7558. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7559. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7560. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  7561. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  7562. _diffuseColor.copy( material.color );
  7563. _emissiveColor.copy( material.emissive );
  7564. if ( material.vertexColors === THREE.FaceColors ) {
  7565. _diffuseColor.r *= element.color.r;
  7566. _diffuseColor.g *= element.color.g;
  7567. _diffuseColor.b *= element.color.b;
  7568. }
  7569. if ( _enableLighting === true ) {
  7570. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  7571. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  7572. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  7573. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  7574. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7575. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7576. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  7577. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7578. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7579. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7580. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7581. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7582. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7583. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7584. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7585. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7586. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7587. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7588. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7589. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7590. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7591. } else {
  7592. _color.r = _ambientLight.r;
  7593. _color.g = _ambientLight.g;
  7594. _color.b = _ambientLight.b;
  7595. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7596. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7597. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7598. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7599. material.wireframe === true
  7600. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7601. : fillPath( _color );
  7602. }
  7603. } else {
  7604. material.wireframe === true
  7605. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7606. : fillPath( material.color );
  7607. }
  7608. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7609. if ( material.map !== null ) {
  7610. if ( material.map.mapping instanceof THREE.UVMapping ) {
  7611. _uvs = element.uvs[ 0 ];
  7612. 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 );
  7613. }
  7614. } else if ( material.envMap !== null ) {
  7615. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  7616. var cameraMatrix = camera.matrixWorldInverse;
  7617. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  7618. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7619. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7620. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  7621. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7622. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7623. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  7624. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7625. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7626. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  7627. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  7628. }*/
  7629. } else {
  7630. _color.copy( material.color );
  7631. if ( material.vertexColors === THREE.FaceColors ) {
  7632. _color.r *= element.color.r;
  7633. _color.g *= element.color.g;
  7634. _color.b *= element.color.b;
  7635. }
  7636. material.wireframe === true
  7637. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7638. : fillPath( _color );
  7639. }
  7640. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7641. _near = camera.near;
  7642. _far = camera.far;
  7643. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7644. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7645. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7646. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7647. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7648. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7649. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7650. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7651. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7652. _color.r = normalToComponent( element.normalWorld.x );
  7653. _color.g = normalToComponent( element.normalWorld.y );
  7654. _color.b = normalToComponent( element.normalWorld.z );
  7655. material.wireframe === true
  7656. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7657. : fillPath( _color );
  7658. }
  7659. }
  7660. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  7661. _this.info.render.vertices += 4;
  7662. _this.info.render.faces ++;
  7663. setOpacity( material.opacity );
  7664. setBlending( material.blending );
  7665. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  7666. // Let renderFace3() handle this
  7667. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  7668. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  7669. return;
  7670. }
  7671. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7672. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7673. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7674. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  7675. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  7676. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  7677. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7678. _diffuseColor.copy( material.color );
  7679. _emissiveColor.copy( material.emissive );
  7680. if ( material.vertexColors === THREE.FaceColors ) {
  7681. _diffuseColor.r *= element.color.r;
  7682. _diffuseColor.g *= element.color.g;
  7683. _diffuseColor.b *= element.color.b;
  7684. }
  7685. if ( _enableLighting === true ) {
  7686. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  7687. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  7688. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  7689. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  7690. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7691. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7692. calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  7693. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  7694. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7695. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7696. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7697. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7698. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7699. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7700. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7701. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7702. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7703. _color4.r = _color4.r * _diffuseColor.r + _emissiveColor.r;
  7704. _color4.g = _color4.g * _diffuseColor.g + _emissiveColor.g;
  7705. _color4.b = _color4.b * _diffuseColor.b + _emissiveColor.b;
  7706. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7707. // TODO: UVs are incorrect, v4->v3?
  7708. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7709. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7710. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7711. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7712. } else {
  7713. _color.r = _ambientLight.r;
  7714. _color.g = _ambientLight.g;
  7715. _color.b = _ambientLight.b;
  7716. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7717. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7718. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7719. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7720. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7721. material.wireframe === true
  7722. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7723. : fillPath( _color );
  7724. }
  7725. } else {
  7726. _color.r = _diffuseColor.r + _emissiveColor.r;
  7727. _color.g = _diffuseColor.g + _emissiveColor.g;
  7728. _color.b = _diffuseColor.b + _emissiveColor.b;
  7729. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7730. material.wireframe === true
  7731. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7732. : fillPath( _color );
  7733. }
  7734. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  7735. _color.copy( material.color );
  7736. if ( material.vertexColors === THREE.FaceColors ) {
  7737. _color.r *= element.color.r;
  7738. _color.g *= element.color.g;
  7739. _color.b *= element.color.b;
  7740. }
  7741. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7742. material.wireframe === true
  7743. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7744. : fillPath( _color );
  7745. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7746. _color.r = normalToComponent( element.normalWorld.x );
  7747. _color.g = normalToComponent( element.normalWorld.y );
  7748. _color.b = normalToComponent( element.normalWorld.z );
  7749. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7750. material.wireframe === true
  7751. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7752. : fillPath( _color );
  7753. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7754. _near = camera.near;
  7755. _far = camera.far;
  7756. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7757. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7758. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  7759. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7760. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7761. // TODO: UVs are incorrect, v4->v3?
  7762. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7763. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7764. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7765. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7766. }
  7767. }
  7768. //
  7769. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  7770. _context.beginPath();
  7771. _context.moveTo( x0, y0 );
  7772. _context.lineTo( x1, y1 );
  7773. _context.lineTo( x2, y2 );
  7774. _context.closePath();
  7775. }
  7776. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  7777. _context.beginPath();
  7778. _context.moveTo( x0, y0 );
  7779. _context.lineTo( x1, y1 );
  7780. _context.lineTo( x2, y2 );
  7781. _context.lineTo( x3, y3 );
  7782. _context.closePath();
  7783. }
  7784. function strokePath( color, linewidth, linecap, linejoin ) {
  7785. setLineWidth( linewidth );
  7786. setLineCap( linecap );
  7787. setLineJoin( linejoin );
  7788. setStrokeStyle( color.getContextStyle() );
  7789. _context.stroke();
  7790. _bboxRect.inflate( linewidth * 2 );
  7791. }
  7792. function fillPath( color ) {
  7793. setFillStyle( color.getContextStyle() );
  7794. _context.fill();
  7795. }
  7796. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  7797. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  7798. if ( texture.needsUpdate === true ) {
  7799. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  7800. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  7801. _patterns[ texture.id ] = _context.createPattern(
  7802. texture.image, repeatX === true && repeatY === true
  7803. ? 'repeat'
  7804. : repeatX === true && repeatY === false
  7805. ? 'repeat-x'
  7806. : repeatX === false && repeatY === true
  7807. ? 'repeat-y'
  7808. : 'no-repeat'
  7809. );
  7810. texture.needsUpdate = false;
  7811. }
  7812. _patterns[ texture.id ] === undefined
  7813. ? setFillStyle( 'rgba(0,0,0,1)' )
  7814. : setFillStyle( _patterns[ texture.id ] );
  7815. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7816. var a, b, c, d, e, f, det, idet,
  7817. offsetX = texture.offset.x / texture.repeat.x,
  7818. offsetY = texture.offset.y / texture.repeat.y,
  7819. width = texture.image.width * texture.repeat.x,
  7820. height = texture.image.height * texture.repeat.y;
  7821. u0 = ( u0 + offsetX ) * width;
  7822. v0 = ( 1.0 - v0 + offsetY ) * height;
  7823. u1 = ( u1 + offsetX ) * width;
  7824. v1 = ( 1.0 - v1 + offsetY ) * height;
  7825. u2 = ( u2 + offsetX ) * width;
  7826. v2 = ( 1.0 - v2 + offsetY ) * height;
  7827. x1 -= x0; y1 -= y0;
  7828. x2 -= x0; y2 -= y0;
  7829. u1 -= u0; v1 -= v0;
  7830. u2 -= u0; v2 -= v0;
  7831. det = u1 * v2 - u2 * v1;
  7832. if ( det === 0 ) {
  7833. if ( _imagedatas[ texture.id ] === undefined ) {
  7834. var canvas = document.createElement( 'canvas' )
  7835. canvas.width = texture.image.width;
  7836. canvas.height = texture.image.height;
  7837. var context = canvas.getContext( '2d' );
  7838. context.drawImage( texture.image, 0, 0 );
  7839. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  7840. }
  7841. var data = _imagedatas[ texture.id ];
  7842. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  7843. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  7844. fillPath( _color );
  7845. return;
  7846. }
  7847. idet = 1 / det;
  7848. a = ( v2 * x1 - v1 * x2 ) * idet;
  7849. b = ( v2 * y1 - v1 * y2 ) * idet;
  7850. c = ( u1 * x2 - u2 * x1 ) * idet;
  7851. d = ( u1 * y2 - u2 * y1 ) * idet;
  7852. e = x0 - a * u0 - c * v0;
  7853. f = y0 - b * u0 - d * v0;
  7854. _context.save();
  7855. _context.transform( a, b, c, d, e, f );
  7856. _context.fill();
  7857. _context.restore();
  7858. }
  7859. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  7860. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7861. var a, b, c, d, e, f, det, idet,
  7862. width = image.width - 1,
  7863. height = image.height - 1;
  7864. u0 *= width; v0 *= height;
  7865. u1 *= width; v1 *= height;
  7866. u2 *= width; v2 *= height;
  7867. x1 -= x0; y1 -= y0;
  7868. x2 -= x0; y2 -= y0;
  7869. u1 -= u0; v1 -= v0;
  7870. u2 -= u0; v2 -= v0;
  7871. det = u1 * v2 - u2 * v1;
  7872. idet = 1 / det;
  7873. a = ( v2 * x1 - v1 * x2 ) * idet;
  7874. b = ( v2 * y1 - v1 * y2 ) * idet;
  7875. c = ( u1 * x2 - u2 * x1 ) * idet;
  7876. d = ( u1 * y2 - u2 * y1 ) * idet;
  7877. e = x0 - a * u0 - c * v0;
  7878. f = y0 - b * u0 - d * v0;
  7879. _context.save();
  7880. _context.transform( a, b, c, d, e, f );
  7881. _context.clip();
  7882. _context.drawImage( image, 0, 0 );
  7883. _context.restore();
  7884. }
  7885. function getGradientTexture( color1, color2, color3, color4 ) {
  7886. // http://mrdoob.com/blog/post/710
  7887. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  7888. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  7889. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  7890. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  7891. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  7892. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  7893. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  7894. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  7895. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  7896. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  7897. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  7898. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  7899. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  7900. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  7901. return _gradientMap;
  7902. }
  7903. function smoothstep( value, min, max ) {
  7904. var x = ( value - min ) / ( max - min );
  7905. return x * x * ( 3 - 2 * x );
  7906. }
  7907. function normalToComponent( normal ) {
  7908. var component = ( normal + 1 ) * 0.5;
  7909. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  7910. }
  7911. // Hide anti-alias gaps
  7912. function expand( v1, v2 ) {
  7913. var x = v2.x - v1.x, y = v2.y - v1.y,
  7914. det = x * x + y * y, idet;
  7915. if ( det === 0 ) return;
  7916. idet = 1 / Math.sqrt( det );
  7917. x *= idet; y *= idet;
  7918. v2.x += x; v2.y += y;
  7919. v1.x -= x; v1.y -= y;
  7920. }
  7921. };
  7922. // Context cached methods.
  7923. function setOpacity( value ) {
  7924. if ( _contextGlobalAlpha !== value ) {
  7925. _context.globalAlpha = value;
  7926. _contextGlobalAlpha = value;
  7927. }
  7928. }
  7929. function setBlending( value ) {
  7930. if ( _contextGlobalCompositeOperation !== value ) {
  7931. if ( value === THREE.NormalBlending ) {
  7932. _context.globalCompositeOperation = 'source-over';
  7933. } else if ( value === THREE.AdditiveBlending ) {
  7934. _context.globalCompositeOperation = 'lighter';
  7935. } else if ( value === THREE.SubtractiveBlending ) {
  7936. _context.globalCompositeOperation = 'darker';
  7937. }
  7938. _contextGlobalCompositeOperation = value;
  7939. }
  7940. }
  7941. function setLineWidth( value ) {
  7942. if ( _contextLineWidth !== value ) {
  7943. _context.lineWidth = value;
  7944. _contextLineWidth = value;
  7945. }
  7946. }
  7947. function setLineCap( value ) {
  7948. // "butt", "round", "square"
  7949. if ( _contextLineCap !== value ) {
  7950. _context.lineCap = value;
  7951. _contextLineCap = value;
  7952. }
  7953. }
  7954. function setLineJoin( value ) {
  7955. // "round", "bevel", "miter"
  7956. if ( _contextLineJoin !== value ) {
  7957. _context.lineJoin = value;
  7958. _contextLineJoin = value;
  7959. }
  7960. }
  7961. function setStrokeStyle( value ) {
  7962. if ( _contextStrokeStyle !== value ) {
  7963. _context.strokeStyle = value;
  7964. _contextStrokeStyle = value;
  7965. }
  7966. }
  7967. function setFillStyle( value ) {
  7968. if ( _contextFillStyle !== value ) {
  7969. _context.fillStyle = value;
  7970. _contextFillStyle = value;
  7971. }
  7972. }
  7973. };
  7974. /**
  7975. * @author alteredq / http://alteredqualia.com/
  7976. * @author mrdoob / http://mrdoob.com/
  7977. * @author mikael emtinger / http://gomo.se/
  7978. */
  7979. THREE.ShaderChunk = {
  7980. // FOG
  7981. fog_pars_fragment: [
  7982. "#ifdef USE_FOG",
  7983. "uniform vec3 fogColor;",
  7984. "#ifdef FOG_EXP2",
  7985. "uniform float fogDensity;",
  7986. "#else",
  7987. "uniform float fogNear;",
  7988. "uniform float fogFar;",
  7989. "#endif",
  7990. "#endif"
  7991. ].join("\n"),
  7992. fog_fragment: [
  7993. "#ifdef USE_FOG",
  7994. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  7995. "#ifdef FOG_EXP2",
  7996. "const float LOG2 = 1.442695;",
  7997. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  7998. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  7999. "#else",
  8000. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8001. "#endif",
  8002. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8003. "#endif"
  8004. ].join("\n"),
  8005. // ENVIRONMENT MAP
  8006. envmap_pars_fragment: [
  8007. "#ifdef USE_ENVMAP",
  8008. "uniform float reflectivity;",
  8009. "uniform samplerCube envMap;",
  8010. "uniform float flipEnvMap;",
  8011. "uniform int combine;",
  8012. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8013. "uniform bool useRefract;",
  8014. "uniform float refractionRatio;",
  8015. "#else",
  8016. "varying vec3 vReflect;",
  8017. "#endif",
  8018. "#endif"
  8019. ].join("\n"),
  8020. envmap_fragment: [
  8021. "#ifdef USE_ENVMAP",
  8022. "vec3 reflectVec;",
  8023. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8024. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8025. "if ( useRefract ) {",
  8026. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8027. "} else { ",
  8028. "reflectVec = reflect( cameraToVertex, normal );",
  8029. "}",
  8030. "#else",
  8031. "reflectVec = vReflect;",
  8032. "#endif",
  8033. "#ifdef DOUBLE_SIDED",
  8034. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8035. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8036. "#else",
  8037. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8038. "#endif",
  8039. "#ifdef GAMMA_INPUT",
  8040. "cubeColor.xyz *= cubeColor.xyz;",
  8041. "#endif",
  8042. "if ( combine == 1 ) {",
  8043. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8044. "} else if ( combine == 2 ) {",
  8045. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8046. "} else {",
  8047. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8048. "}",
  8049. "#endif"
  8050. ].join("\n"),
  8051. envmap_pars_vertex: [
  8052. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8053. "varying vec3 vReflect;",
  8054. "uniform float refractionRatio;",
  8055. "uniform bool useRefract;",
  8056. "#endif"
  8057. ].join("\n"),
  8058. worldpos_vertex : [
  8059. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8060. "#ifdef USE_SKINNING",
  8061. "vec4 worldPosition = modelMatrix * skinned;",
  8062. "#endif",
  8063. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8064. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8065. "#endif",
  8066. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8067. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8068. "#endif",
  8069. "#endif"
  8070. ].join("\n"),
  8071. envmap_vertex : [
  8072. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8073. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8074. "worldNormal = normalize( worldNormal );",
  8075. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8076. "if ( useRefract ) {",
  8077. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8078. "} else {",
  8079. "vReflect = reflect( cameraToVertex, worldNormal );",
  8080. "}",
  8081. "#endif"
  8082. ].join("\n"),
  8083. // COLOR MAP (particles)
  8084. map_particle_pars_fragment: [
  8085. "#ifdef USE_MAP",
  8086. "uniform sampler2D map;",
  8087. "#endif"
  8088. ].join("\n"),
  8089. map_particle_fragment: [
  8090. "#ifdef USE_MAP",
  8091. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8092. "#endif"
  8093. ].join("\n"),
  8094. // COLOR MAP (triangles)
  8095. map_pars_vertex: [
  8096. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8097. "varying vec2 vUv;",
  8098. "uniform vec4 offsetRepeat;",
  8099. "#endif"
  8100. ].join("\n"),
  8101. map_pars_fragment: [
  8102. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8103. "varying vec2 vUv;",
  8104. "#endif",
  8105. "#ifdef USE_MAP",
  8106. "uniform sampler2D map;",
  8107. "#endif",
  8108. ].join("\n"),
  8109. map_vertex: [
  8110. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8111. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8112. "#endif"
  8113. ].join("\n"),
  8114. map_fragment: [
  8115. "#ifdef USE_MAP",
  8116. "#ifdef GAMMA_INPUT",
  8117. "vec4 texelColor = texture2D( map, vUv );",
  8118. "texelColor.xyz *= texelColor.xyz;",
  8119. "gl_FragColor = gl_FragColor * texelColor;",
  8120. "#else",
  8121. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  8122. "#endif",
  8123. "#endif"
  8124. ].join("\n"),
  8125. // LIGHT MAP
  8126. lightmap_pars_fragment: [
  8127. "#ifdef USE_LIGHTMAP",
  8128. "varying vec2 vUv2;",
  8129. "uniform sampler2D lightMap;",
  8130. "#endif"
  8131. ].join("\n"),
  8132. lightmap_pars_vertex: [
  8133. "#ifdef USE_LIGHTMAP",
  8134. "varying vec2 vUv2;",
  8135. "#endif"
  8136. ].join("\n"),
  8137. lightmap_fragment: [
  8138. "#ifdef USE_LIGHTMAP",
  8139. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8140. "#endif"
  8141. ].join("\n"),
  8142. lightmap_vertex: [
  8143. "#ifdef USE_LIGHTMAP",
  8144. "vUv2 = uv2;",
  8145. "#endif"
  8146. ].join("\n"),
  8147. // BUMP MAP
  8148. bumpmap_pars_fragment: [
  8149. "#ifdef USE_BUMPMAP",
  8150. "uniform sampler2D bumpMap;",
  8151. "uniform float bumpScale;",
  8152. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8153. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8154. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8155. "vec2 dHdxy_fwd() {",
  8156. "vec2 dSTdx = dFdx( vUv );",
  8157. "vec2 dSTdy = dFdy( vUv );",
  8158. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8159. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8160. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8161. "return vec2( dBx, dBy );",
  8162. "}",
  8163. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8164. "vec3 vSigmaX = dFdx( surf_pos );",
  8165. "vec3 vSigmaY = dFdy( surf_pos );",
  8166. "vec3 vN = surf_norm;", // normalized
  8167. "vec3 R1 = cross( vSigmaY, vN );",
  8168. "vec3 R2 = cross( vN, vSigmaX );",
  8169. "float fDet = dot( vSigmaX, R1 );",
  8170. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8171. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8172. "}",
  8173. "#endif"
  8174. ].join("\n"),
  8175. // NORMAL MAP
  8176. normalmap_pars_fragment: [
  8177. "#ifdef USE_NORMALMAP",
  8178. "uniform sampler2D normalMap;",
  8179. "uniform vec2 normalScale;",
  8180. // Per-Pixel Tangent Space Normal Mapping
  8181. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8182. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8183. "vec3 q0 = dFdx( eye_pos.xyz );",
  8184. "vec3 q1 = dFdy( eye_pos.xyz );",
  8185. "vec2 st0 = dFdx( vUv.st );",
  8186. "vec2 st1 = dFdy( vUv.st );",
  8187. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8188. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8189. "vec3 N = normalize( surf_norm );",
  8190. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8191. "mapN.xy = normalScale * mapN.xy;",
  8192. "mat3 tsn = mat3( S, T, N );",
  8193. "return normalize( tsn * mapN );",
  8194. "}",
  8195. "#endif"
  8196. ].join("\n"),
  8197. // SPECULAR MAP
  8198. specularmap_pars_fragment: [
  8199. "#ifdef USE_SPECULARMAP",
  8200. "uniform sampler2D specularMap;",
  8201. "#endif"
  8202. ].join("\n"),
  8203. specularmap_fragment: [
  8204. "float specularStrength;",
  8205. "#ifdef USE_SPECULARMAP",
  8206. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8207. "specularStrength = texelSpecular.r;",
  8208. "#else",
  8209. "specularStrength = 1.0;",
  8210. "#endif"
  8211. ].join("\n"),
  8212. // LIGHTS LAMBERT
  8213. lights_lambert_pars_vertex: [
  8214. "uniform vec3 ambient;",
  8215. "uniform vec3 diffuse;",
  8216. "uniform vec3 emissive;",
  8217. "uniform vec3 ambientLightColor;",
  8218. "#if MAX_DIR_LIGHTS > 0",
  8219. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8220. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8221. "#endif",
  8222. "#if MAX_HEMI_LIGHTS > 0",
  8223. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8224. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8225. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8226. "#endif",
  8227. "#if MAX_POINT_LIGHTS > 0",
  8228. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8229. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8230. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8231. "#endif",
  8232. "#if MAX_SPOT_LIGHTS > 0",
  8233. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8234. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8235. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8236. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8237. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8238. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8239. "#endif",
  8240. "#ifdef WRAP_AROUND",
  8241. "uniform vec3 wrapRGB;",
  8242. "#endif"
  8243. ].join("\n"),
  8244. lights_lambert_vertex: [
  8245. "vLightFront = vec3( 0.0 );",
  8246. "#ifdef DOUBLE_SIDED",
  8247. "vLightBack = vec3( 0.0 );",
  8248. "#endif",
  8249. "transformedNormal = normalize( transformedNormal );",
  8250. "#if MAX_DIR_LIGHTS > 0",
  8251. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8252. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8253. "vec3 dirVector = normalize( lDirection.xyz );",
  8254. "float dotProduct = dot( transformedNormal, dirVector );",
  8255. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8256. "#ifdef DOUBLE_SIDED",
  8257. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8258. "#ifdef WRAP_AROUND",
  8259. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8260. "#endif",
  8261. "#endif",
  8262. "#ifdef WRAP_AROUND",
  8263. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8264. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  8265. "#ifdef DOUBLE_SIDED",
  8266. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  8267. "#endif",
  8268. "#endif",
  8269. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  8270. "#ifdef DOUBLE_SIDED",
  8271. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  8272. "#endif",
  8273. "}",
  8274. "#endif",
  8275. "#if MAX_POINT_LIGHTS > 0",
  8276. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8277. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8278. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8279. "float lDistance = 1.0;",
  8280. "if ( pointLightDistance[ i ] > 0.0 )",
  8281. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8282. "lVector = normalize( lVector );",
  8283. "float dotProduct = dot( transformedNormal, lVector );",
  8284. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8285. "#ifdef DOUBLE_SIDED",
  8286. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8287. "#ifdef WRAP_AROUND",
  8288. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8289. "#endif",
  8290. "#endif",
  8291. "#ifdef WRAP_AROUND",
  8292. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8293. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  8294. "#ifdef DOUBLE_SIDED",
  8295. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  8296. "#endif",
  8297. "#endif",
  8298. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  8299. "#ifdef DOUBLE_SIDED",
  8300. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  8301. "#endif",
  8302. "}",
  8303. "#endif",
  8304. "#if MAX_SPOT_LIGHTS > 0",
  8305. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8306. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8307. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8308. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  8309. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8310. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8311. "float lDistance = 1.0;",
  8312. "if ( spotLightDistance[ i ] > 0.0 )",
  8313. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8314. "lVector = normalize( lVector );",
  8315. "float dotProduct = dot( transformedNormal, lVector );",
  8316. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8317. "#ifdef DOUBLE_SIDED",
  8318. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8319. "#ifdef WRAP_AROUND",
  8320. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8321. "#endif",
  8322. "#endif",
  8323. "#ifdef WRAP_AROUND",
  8324. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8325. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  8326. "#ifdef DOUBLE_SIDED",
  8327. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  8328. "#endif",
  8329. "#endif",
  8330. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  8331. "#ifdef DOUBLE_SIDED",
  8332. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  8333. "#endif",
  8334. "}",
  8335. "}",
  8336. "#endif",
  8337. "#if MAX_HEMI_LIGHTS > 0",
  8338. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8339. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8340. "vec3 lVector = normalize( lDirection.xyz );",
  8341. "float dotProduct = dot( transformedNormal, lVector );",
  8342. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8343. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  8344. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8345. "#ifdef DOUBLE_SIDED",
  8346. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  8347. "#endif",
  8348. "}",
  8349. "#endif",
  8350. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  8351. "#ifdef DOUBLE_SIDED",
  8352. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  8353. "#endif"
  8354. ].join("\n"),
  8355. // LIGHTS PHONG
  8356. lights_phong_pars_vertex: [
  8357. "#ifndef PHONG_PER_PIXEL",
  8358. "#if MAX_POINT_LIGHTS > 0",
  8359. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8360. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8361. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8362. "#endif",
  8363. "#if MAX_SPOT_LIGHTS > 0",
  8364. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8365. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8366. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8367. "#endif",
  8368. "#endif",
  8369. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8370. "varying vec3 vWorldPosition;",
  8371. "#endif"
  8372. ].join("\n"),
  8373. lights_phong_vertex: [
  8374. "#ifndef PHONG_PER_PIXEL",
  8375. "#if MAX_POINT_LIGHTS > 0",
  8376. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8377. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8378. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8379. "float lDistance = 1.0;",
  8380. "if ( pointLightDistance[ i ] > 0.0 )",
  8381. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8382. "vPointLight[ i ] = vec4( lVector, lDistance );",
  8383. "}",
  8384. "#endif",
  8385. "#if MAX_SPOT_LIGHTS > 0",
  8386. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8387. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8388. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8389. "float lDistance = 1.0;",
  8390. "if ( spotLightDistance[ i ] > 0.0 )",
  8391. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8392. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  8393. "}",
  8394. "#endif",
  8395. "#endif",
  8396. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8397. "vWorldPosition = worldPosition.xyz;",
  8398. "#endif"
  8399. ].join("\n"),
  8400. lights_phong_pars_fragment: [
  8401. "uniform vec3 ambientLightColor;",
  8402. "#if MAX_DIR_LIGHTS > 0",
  8403. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8404. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8405. "#endif",
  8406. "#if MAX_HEMI_LIGHTS > 0",
  8407. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8408. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8409. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8410. "#endif",
  8411. "#if MAX_POINT_LIGHTS > 0",
  8412. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8413. "#ifdef PHONG_PER_PIXEL",
  8414. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8415. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8416. "#else",
  8417. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8418. "#endif",
  8419. "#endif",
  8420. "#if MAX_SPOT_LIGHTS > 0",
  8421. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8422. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8423. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8424. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8425. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8426. "#ifdef PHONG_PER_PIXEL",
  8427. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8428. "#else",
  8429. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8430. "#endif",
  8431. "#endif",
  8432. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8433. "varying vec3 vWorldPosition;",
  8434. "#endif",
  8435. "#ifdef WRAP_AROUND",
  8436. "uniform vec3 wrapRGB;",
  8437. "#endif",
  8438. "varying vec3 vViewPosition;",
  8439. "varying vec3 vNormal;"
  8440. ].join("\n"),
  8441. lights_phong_fragment: [
  8442. "vec3 normal = normalize( vNormal );",
  8443. "vec3 viewPosition = normalize( vViewPosition );",
  8444. "#ifdef DOUBLE_SIDED",
  8445. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8446. "#endif",
  8447. "#ifdef USE_NORMALMAP",
  8448. "normal = perturbNormal2Arb( -viewPosition, normal );",
  8449. "#elif defined( USE_BUMPMAP )",
  8450. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  8451. "#endif",
  8452. "#if MAX_POINT_LIGHTS > 0",
  8453. "vec3 pointDiffuse = vec3( 0.0 );",
  8454. "vec3 pointSpecular = vec3( 0.0 );",
  8455. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8456. "#ifdef PHONG_PER_PIXEL",
  8457. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8458. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8459. "float lDistance = 1.0;",
  8460. "if ( pointLightDistance[ i ] > 0.0 )",
  8461. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8462. "lVector = normalize( lVector );",
  8463. "#else",
  8464. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  8465. "float lDistance = vPointLight[ i ].w;",
  8466. "#endif",
  8467. // diffuse
  8468. "float dotProduct = dot( normal, lVector );",
  8469. "#ifdef WRAP_AROUND",
  8470. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  8471. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8472. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  8473. "#else",
  8474. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  8475. "#endif",
  8476. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  8477. // specular
  8478. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  8479. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  8480. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  8481. "#ifdef PHYSICALLY_BASED_SHADING",
  8482. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8483. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8484. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  8485. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  8486. "#else",
  8487. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  8488. "#endif",
  8489. "}",
  8490. "#endif",
  8491. "#if MAX_SPOT_LIGHTS > 0",
  8492. "vec3 spotDiffuse = vec3( 0.0 );",
  8493. "vec3 spotSpecular = vec3( 0.0 );",
  8494. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8495. "#ifdef PHONG_PER_PIXEL",
  8496. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8497. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8498. "float lDistance = 1.0;",
  8499. "if ( spotLightDistance[ i ] > 0.0 )",
  8500. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8501. "lVector = normalize( lVector );",
  8502. "#else",
  8503. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  8504. "float lDistance = vSpotLight[ i ].w;",
  8505. "#endif",
  8506. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  8507. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8508. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8509. // diffuse
  8510. "float dotProduct = dot( normal, lVector );",
  8511. "#ifdef WRAP_AROUND",
  8512. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  8513. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8514. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  8515. "#else",
  8516. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  8517. "#endif",
  8518. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  8519. // specular
  8520. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  8521. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  8522. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  8523. "#ifdef PHYSICALLY_BASED_SHADING",
  8524. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8525. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8526. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  8527. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  8528. "#else",
  8529. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  8530. "#endif",
  8531. "}",
  8532. "}",
  8533. "#endif",
  8534. "#if MAX_DIR_LIGHTS > 0",
  8535. "vec3 dirDiffuse = vec3( 0.0 );",
  8536. "vec3 dirSpecular = vec3( 0.0 );" ,
  8537. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8538. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8539. "vec3 dirVector = normalize( lDirection.xyz );",
  8540. // diffuse
  8541. "float dotProduct = dot( normal, dirVector );",
  8542. "#ifdef WRAP_AROUND",
  8543. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  8544. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8545. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  8546. "#else",
  8547. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  8548. "#endif",
  8549. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  8550. // specular
  8551. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  8552. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  8553. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  8554. "#ifdef PHYSICALLY_BASED_SHADING",
  8555. /*
  8556. // fresnel term from skin shader
  8557. "const float F0 = 0.128;",
  8558. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  8559. "float exponential = pow( base, 5.0 );",
  8560. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  8561. */
  8562. /*
  8563. // fresnel term from fresnel shader
  8564. "const float mFresnelBias = 0.08;",
  8565. "const float mFresnelScale = 0.3;",
  8566. "const float mFresnelPower = 5.0;",
  8567. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  8568. */
  8569. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8570. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8571. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  8572. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  8573. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  8574. "#else",
  8575. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  8576. "#endif",
  8577. "}",
  8578. "#endif",
  8579. "#if MAX_HEMI_LIGHTS > 0",
  8580. "vec3 hemiDiffuse = vec3( 0.0 );",
  8581. "vec3 hemiSpecular = vec3( 0.0 );" ,
  8582. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8583. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8584. "vec3 lVector = normalize( lDirection.xyz );",
  8585. // diffuse
  8586. "float dotProduct = dot( normal, lVector );",
  8587. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8588. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8589. "hemiDiffuse += diffuse * hemiColor;",
  8590. // specular (sky light)
  8591. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  8592. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  8593. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  8594. // specular (ground light)
  8595. "vec3 lVectorGround = -lVector;",
  8596. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  8597. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  8598. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  8599. "#ifdef PHYSICALLY_BASED_SHADING",
  8600. "float dotProductGround = dot( normal, lVectorGround );",
  8601. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8602. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8603. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  8604. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  8605. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  8606. "#else",
  8607. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  8608. "#endif",
  8609. "}",
  8610. "#endif",
  8611. "vec3 totalDiffuse = vec3( 0.0 );",
  8612. "vec3 totalSpecular = vec3( 0.0 );",
  8613. "#if MAX_DIR_LIGHTS > 0",
  8614. "totalDiffuse += dirDiffuse;",
  8615. "totalSpecular += dirSpecular;",
  8616. "#endif",
  8617. "#if MAX_HEMI_LIGHTS > 0",
  8618. "totalDiffuse += hemiDiffuse;",
  8619. "totalSpecular += hemiSpecular;",
  8620. "#endif",
  8621. "#if MAX_POINT_LIGHTS > 0",
  8622. "totalDiffuse += pointDiffuse;",
  8623. "totalSpecular += pointSpecular;",
  8624. "#endif",
  8625. "#if MAX_SPOT_LIGHTS > 0",
  8626. "totalDiffuse += spotDiffuse;",
  8627. "totalSpecular += spotSpecular;",
  8628. "#endif",
  8629. "#ifdef METAL",
  8630. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  8631. "#else",
  8632. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  8633. "#endif"
  8634. ].join("\n"),
  8635. // VERTEX COLORS
  8636. color_pars_fragment: [
  8637. "#ifdef USE_COLOR",
  8638. "varying vec3 vColor;",
  8639. "#endif"
  8640. ].join("\n"),
  8641. color_fragment: [
  8642. "#ifdef USE_COLOR",
  8643. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  8644. "#endif"
  8645. ].join("\n"),
  8646. color_pars_vertex: [
  8647. "#ifdef USE_COLOR",
  8648. "varying vec3 vColor;",
  8649. "#endif"
  8650. ].join("\n"),
  8651. color_vertex: [
  8652. "#ifdef USE_COLOR",
  8653. "#ifdef GAMMA_INPUT",
  8654. "vColor = color * color;",
  8655. "#else",
  8656. "vColor = color;",
  8657. "#endif",
  8658. "#endif"
  8659. ].join("\n"),
  8660. // SKINNING
  8661. skinning_pars_vertex: [
  8662. "#ifdef USE_SKINNING",
  8663. "#ifdef BONE_TEXTURE",
  8664. "uniform sampler2D boneTexture;",
  8665. "mat4 getBoneMatrix( const in float i ) {",
  8666. "float j = i * 4.0;",
  8667. "float x = mod( j, N_BONE_PIXEL_X );",
  8668. "float y = floor( j / N_BONE_PIXEL_X );",
  8669. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  8670. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  8671. "y = dy * ( y + 0.5 );",
  8672. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  8673. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  8674. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  8675. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  8676. "mat4 bone = mat4( v1, v2, v3, v4 );",
  8677. "return bone;",
  8678. "}",
  8679. "#else",
  8680. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  8681. "mat4 getBoneMatrix( const in float i ) {",
  8682. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  8683. "return bone;",
  8684. "}",
  8685. "#endif",
  8686. "#endif"
  8687. ].join("\n"),
  8688. skinbase_vertex: [
  8689. "#ifdef USE_SKINNING",
  8690. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  8691. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  8692. "#endif"
  8693. ].join("\n"),
  8694. skinning_vertex: [
  8695. "#ifdef USE_SKINNING",
  8696. "#ifdef USE_MORPHTARGETS",
  8697. "vec4 skinVertex = vec4( morphed, 1.0 );",
  8698. "#else",
  8699. "vec4 skinVertex = vec4( position, 1.0 );",
  8700. "#endif",
  8701. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  8702. "skinned += boneMatY * skinVertex * skinWeight.y;",
  8703. "#endif"
  8704. ].join("\n"),
  8705. // MORPHING
  8706. morphtarget_pars_vertex: [
  8707. "#ifdef USE_MORPHTARGETS",
  8708. "#ifndef USE_MORPHNORMALS",
  8709. "uniform float morphTargetInfluences[ 8 ];",
  8710. "#else",
  8711. "uniform float morphTargetInfluences[ 4 ];",
  8712. "#endif",
  8713. "#endif"
  8714. ].join("\n"),
  8715. morphtarget_vertex: [
  8716. "#ifdef USE_MORPHTARGETS",
  8717. "vec3 morphed = vec3( 0.0 );",
  8718. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  8719. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  8720. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  8721. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  8722. "#ifndef USE_MORPHNORMALS",
  8723. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  8724. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  8725. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  8726. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  8727. "#endif",
  8728. "morphed += position;",
  8729. "#endif"
  8730. ].join("\n"),
  8731. default_vertex : [
  8732. "vec4 mvPosition;",
  8733. "#ifdef USE_SKINNING",
  8734. "mvPosition = modelViewMatrix * skinned;",
  8735. "#endif",
  8736. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  8737. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  8738. "#endif",
  8739. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  8740. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8741. "#endif",
  8742. "gl_Position = projectionMatrix * mvPosition;",
  8743. ].join("\n"),
  8744. morphnormal_vertex: [
  8745. "#ifdef USE_MORPHNORMALS",
  8746. "vec3 morphedNormal = vec3( 0.0 );",
  8747. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  8748. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  8749. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  8750. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  8751. "morphedNormal += normal;",
  8752. "#endif"
  8753. ].join("\n"),
  8754. skinnormal_vertex: [
  8755. "#ifdef USE_SKINNING",
  8756. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  8757. "skinMatrix += skinWeight.y * boneMatY;",
  8758. "#ifdef USE_MORPHNORMALS",
  8759. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  8760. "#else",
  8761. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  8762. "#endif",
  8763. "#endif"
  8764. ].join("\n"),
  8765. defaultnormal_vertex: [
  8766. "vec3 objectNormal;",
  8767. "#ifdef USE_SKINNING",
  8768. "objectNormal = skinnedNormal.xyz;",
  8769. "#endif",
  8770. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  8771. "objectNormal = morphedNormal;",
  8772. "#endif",
  8773. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  8774. "objectNormal = normal;",
  8775. "#endif",
  8776. "#ifdef FLIP_SIDED",
  8777. "objectNormal = -objectNormal;",
  8778. "#endif",
  8779. "vec3 transformedNormal = normalMatrix * objectNormal;",
  8780. ].join("\n"),
  8781. // SHADOW MAP
  8782. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  8783. // http://spidergl.org/example.php?id=6
  8784. // http://fabiensanglard.net/shadowmapping
  8785. shadowmap_pars_fragment: [
  8786. "#ifdef USE_SHADOWMAP",
  8787. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  8788. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  8789. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  8790. "uniform float shadowBias[ MAX_SHADOWS ];",
  8791. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8792. "float unpackDepth( const in vec4 rgba_depth ) {",
  8793. "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 );",
  8794. "float depth = dot( rgba_depth, bit_shift );",
  8795. "return depth;",
  8796. "}",
  8797. "#endif"
  8798. ].join("\n"),
  8799. shadowmap_fragment: [
  8800. "#ifdef USE_SHADOWMAP",
  8801. "#ifdef SHADOWMAP_DEBUG",
  8802. "vec3 frustumColors[3];",
  8803. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  8804. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  8805. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  8806. "#endif",
  8807. "#ifdef SHADOWMAP_CASCADE",
  8808. "int inFrustumCount = 0;",
  8809. "#endif",
  8810. "float fDepth;",
  8811. "vec3 shadowColor = vec3( 1.0 );",
  8812. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8813. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  8814. // "if ( something && something )" breaks ATI OpenGL shader compiler
  8815. // "if ( all( something, something ) )" using this instead
  8816. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  8817. "bool inFrustum = all( inFrustumVec );",
  8818. // don't shadow pixels outside of light frustum
  8819. // use just first frustum (for cascades)
  8820. // don't shadow pixels behind far plane of light frustum
  8821. "#ifdef SHADOWMAP_CASCADE",
  8822. "inFrustumCount += int( inFrustum );",
  8823. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  8824. "#else",
  8825. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  8826. "#endif",
  8827. "bool frustumTest = all( frustumTestVec );",
  8828. "if ( frustumTest ) {",
  8829. "shadowCoord.z += shadowBias[ i ];",
  8830. "#ifdef SHADOWMAP_SOFT",
  8831. // Percentage-close filtering
  8832. // (9 pixel kernel)
  8833. // http://fabiensanglard.net/shadowmappingPCF/
  8834. "float shadow = 0.0;",
  8835. /*
  8836. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  8837. // must enroll loop manually
  8838. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  8839. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  8840. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  8841. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  8842. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  8843. "float fDepth = unpackDepth( rgbaDepth );",
  8844. "if ( fDepth < shadowCoord.z )",
  8845. "shadow += 1.0;",
  8846. "}",
  8847. "shadow /= 9.0;",
  8848. */
  8849. "const float shadowDelta = 1.0 / 9.0;",
  8850. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  8851. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  8852. "float dx0 = -1.25 * xPixelOffset;",
  8853. "float dy0 = -1.25 * yPixelOffset;",
  8854. "float dx1 = 1.25 * xPixelOffset;",
  8855. "float dy1 = 1.25 * yPixelOffset;",
  8856. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  8857. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8858. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  8859. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8860. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  8861. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8862. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  8863. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8864. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  8865. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8866. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  8867. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8868. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  8869. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8870. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  8871. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8872. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  8873. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8874. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  8875. "#else",
  8876. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  8877. "float fDepth = unpackDepth( rgbaDepth );",
  8878. "if ( fDepth < shadowCoord.z )",
  8879. // spot with multiple shadows is darker
  8880. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  8881. // spot with multiple shadows has the same color as single shadow spot
  8882. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  8883. "#endif",
  8884. "}",
  8885. "#ifdef SHADOWMAP_DEBUG",
  8886. "#ifdef SHADOWMAP_CASCADE",
  8887. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  8888. "#else",
  8889. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  8890. "#endif",
  8891. "#endif",
  8892. "}",
  8893. "#ifdef GAMMA_OUTPUT",
  8894. "shadowColor *= shadowColor;",
  8895. "#endif",
  8896. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  8897. "#endif"
  8898. ].join("\n"),
  8899. shadowmap_pars_vertex: [
  8900. "#ifdef USE_SHADOWMAP",
  8901. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8902. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  8903. "#endif"
  8904. ].join("\n"),
  8905. shadowmap_vertex: [
  8906. "#ifdef USE_SHADOWMAP",
  8907. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8908. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  8909. "}",
  8910. "#endif"
  8911. ].join("\n"),
  8912. // ALPHATEST
  8913. alphatest_fragment: [
  8914. "#ifdef ALPHATEST",
  8915. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  8916. "#endif"
  8917. ].join("\n"),
  8918. // LINEAR SPACE
  8919. linear_to_gamma_fragment: [
  8920. "#ifdef GAMMA_OUTPUT",
  8921. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  8922. "#endif"
  8923. ].join("\n"),
  8924. };
  8925. THREE.UniformsUtils = {
  8926. merge: function ( uniforms ) {
  8927. var u, p, tmp, merged = {};
  8928. for ( u = 0; u < uniforms.length; u ++ ) {
  8929. tmp = this.clone( uniforms[ u ] );
  8930. for ( p in tmp ) {
  8931. merged[ p ] = tmp[ p ];
  8932. }
  8933. }
  8934. return merged;
  8935. },
  8936. clone: function ( uniforms_src ) {
  8937. var u, p, parameter, parameter_src, uniforms_dst = {};
  8938. for ( u in uniforms_src ) {
  8939. uniforms_dst[ u ] = {};
  8940. for ( p in uniforms_src[ u ] ) {
  8941. parameter_src = uniforms_src[ u ][ p ];
  8942. if ( parameter_src instanceof THREE.Color ||
  8943. parameter_src instanceof THREE.Vector2 ||
  8944. parameter_src instanceof THREE.Vector3 ||
  8945. parameter_src instanceof THREE.Vector4 ||
  8946. parameter_src instanceof THREE.Matrix4 ||
  8947. parameter_src instanceof THREE.Texture ) {
  8948. uniforms_dst[ u ][ p ] = parameter_src.clone();
  8949. } else if ( parameter_src instanceof Array ) {
  8950. uniforms_dst[ u ][ p ] = parameter_src.slice();
  8951. } else {
  8952. uniforms_dst[ u ][ p ] = parameter_src;
  8953. }
  8954. }
  8955. }
  8956. return uniforms_dst;
  8957. }
  8958. };
  8959. THREE.UniformsLib = {
  8960. common: {
  8961. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  8962. "opacity" : { type: "f", value: 1.0 },
  8963. "map" : { type: "t", value: null },
  8964. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  8965. "lightMap" : { type: "t", value: null },
  8966. "specularMap" : { type: "t", value: null },
  8967. "envMap" : { type: "t", value: null },
  8968. "flipEnvMap" : { type: "f", value: -1 },
  8969. "useRefract" : { type: "i", value: 0 },
  8970. "reflectivity" : { type: "f", value: 1.0 },
  8971. "refractionRatio" : { type: "f", value: 0.98 },
  8972. "combine" : { type: "i", value: 0 },
  8973. "morphTargetInfluences" : { type: "f", value: 0 }
  8974. },
  8975. bump: {
  8976. "bumpMap" : { type: "t", value: null },
  8977. "bumpScale" : { type: "f", value: 1 }
  8978. },
  8979. normalmap: {
  8980. "normalMap" : { type: "t", value: null },
  8981. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  8982. },
  8983. fog : {
  8984. "fogDensity" : { type: "f", value: 0.00025 },
  8985. "fogNear" : { type: "f", value: 1 },
  8986. "fogFar" : { type: "f", value: 2000 },
  8987. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  8988. },
  8989. lights: {
  8990. "ambientLightColor" : { type: "fv", value: [] },
  8991. "directionalLightDirection" : { type: "fv", value: [] },
  8992. "directionalLightColor" : { type: "fv", value: [] },
  8993. "hemisphereLightDirection" : { type: "fv", value: [] },
  8994. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  8995. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  8996. "pointLightColor" : { type: "fv", value: [] },
  8997. "pointLightPosition" : { type: "fv", value: [] },
  8998. "pointLightDistance" : { type: "fv1", value: [] },
  8999. "spotLightColor" : { type: "fv", value: [] },
  9000. "spotLightPosition" : { type: "fv", value: [] },
  9001. "spotLightDirection" : { type: "fv", value: [] },
  9002. "spotLightDistance" : { type: "fv1", value: [] },
  9003. "spotLightAngleCos" : { type: "fv1", value: [] },
  9004. "spotLightExponent" : { type: "fv1", value: [] }
  9005. },
  9006. particle: {
  9007. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9008. "opacity" : { type: "f", value: 1.0 },
  9009. "size" : { type: "f", value: 1.0 },
  9010. "scale" : { type: "f", value: 1.0 },
  9011. "map" : { type: "t", value: null },
  9012. "fogDensity" : { type: "f", value: 0.00025 },
  9013. "fogNear" : { type: "f", value: 1 },
  9014. "fogFar" : { type: "f", value: 2000 },
  9015. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9016. },
  9017. shadowmap: {
  9018. "shadowMap": { type: "tv", value: [] },
  9019. "shadowMapSize": { type: "v2v", value: [] },
  9020. "shadowBias" : { type: "fv1", value: [] },
  9021. "shadowDarkness": { type: "fv1", value: [] },
  9022. "shadowMatrix" : { type: "m4v", value: [] },
  9023. }
  9024. };
  9025. THREE.ShaderLib = {
  9026. 'depth': {
  9027. uniforms: {
  9028. "mNear": { type: "f", value: 1.0 },
  9029. "mFar" : { type: "f", value: 2000.0 },
  9030. "opacity" : { type: "f", value: 1.0 }
  9031. },
  9032. vertexShader: [
  9033. "void main() {",
  9034. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  9035. "}"
  9036. ].join("\n"),
  9037. fragmentShader: [
  9038. "uniform float mNear;",
  9039. "uniform float mFar;",
  9040. "uniform float opacity;",
  9041. "void main() {",
  9042. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9043. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  9044. "gl_FragColor = vec4( vec3( color ), opacity );",
  9045. "}"
  9046. ].join("\n")
  9047. },
  9048. 'normal': {
  9049. uniforms: {
  9050. "opacity" : { type: "f", value: 1.0 }
  9051. },
  9052. vertexShader: [
  9053. "varying vec3 vNormal;",
  9054. "void main() {",
  9055. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9056. "vNormal = normalize( normalMatrix * normal );",
  9057. "gl_Position = projectionMatrix * mvPosition;",
  9058. "}"
  9059. ].join("\n"),
  9060. fragmentShader: [
  9061. "uniform float opacity;",
  9062. "varying vec3 vNormal;",
  9063. "void main() {",
  9064. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  9065. "}"
  9066. ].join("\n")
  9067. },
  9068. 'basic': {
  9069. uniforms: THREE.UniformsUtils.merge( [
  9070. THREE.UniformsLib[ "common" ],
  9071. THREE.UniformsLib[ "fog" ],
  9072. THREE.UniformsLib[ "shadowmap" ]
  9073. ] ),
  9074. vertexShader: [
  9075. THREE.ShaderChunk[ "map_pars_vertex" ],
  9076. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9077. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9078. THREE.ShaderChunk[ "color_pars_vertex" ],
  9079. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9080. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9081. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9082. "void main() {",
  9083. THREE.ShaderChunk[ "map_vertex" ],
  9084. THREE.ShaderChunk[ "lightmap_vertex" ],
  9085. THREE.ShaderChunk[ "color_vertex" ],
  9086. "#ifdef USE_ENVMAP",
  9087. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9088. THREE.ShaderChunk[ "skinbase_vertex" ],
  9089. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9090. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9091. "#endif",
  9092. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9093. THREE.ShaderChunk[ "skinning_vertex" ],
  9094. THREE.ShaderChunk[ "default_vertex" ],
  9095. THREE.ShaderChunk[ "worldpos_vertex" ],
  9096. THREE.ShaderChunk[ "envmap_vertex" ],
  9097. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9098. "}"
  9099. ].join("\n"),
  9100. fragmentShader: [
  9101. "uniform vec3 diffuse;",
  9102. "uniform float opacity;",
  9103. THREE.ShaderChunk[ "color_pars_fragment" ],
  9104. THREE.ShaderChunk[ "map_pars_fragment" ],
  9105. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9106. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9107. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9108. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9109. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9110. "void main() {",
  9111. "gl_FragColor = vec4( diffuse, opacity );",
  9112. THREE.ShaderChunk[ "map_fragment" ],
  9113. THREE.ShaderChunk[ "alphatest_fragment" ],
  9114. THREE.ShaderChunk[ "specularmap_fragment" ],
  9115. THREE.ShaderChunk[ "lightmap_fragment" ],
  9116. THREE.ShaderChunk[ "color_fragment" ],
  9117. THREE.ShaderChunk[ "envmap_fragment" ],
  9118. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9119. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9120. THREE.ShaderChunk[ "fog_fragment" ],
  9121. "}"
  9122. ].join("\n")
  9123. },
  9124. 'lambert': {
  9125. uniforms: THREE.UniformsUtils.merge( [
  9126. THREE.UniformsLib[ "common" ],
  9127. THREE.UniformsLib[ "fog" ],
  9128. THREE.UniformsLib[ "lights" ],
  9129. THREE.UniformsLib[ "shadowmap" ],
  9130. {
  9131. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9132. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9133. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9134. }
  9135. ] ),
  9136. vertexShader: [
  9137. "#define LAMBERT",
  9138. "varying vec3 vLightFront;",
  9139. "#ifdef DOUBLE_SIDED",
  9140. "varying vec3 vLightBack;",
  9141. "#endif",
  9142. THREE.ShaderChunk[ "map_pars_vertex" ],
  9143. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9144. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9145. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9146. THREE.ShaderChunk[ "color_pars_vertex" ],
  9147. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9148. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9149. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9150. "void main() {",
  9151. THREE.ShaderChunk[ "map_vertex" ],
  9152. THREE.ShaderChunk[ "lightmap_vertex" ],
  9153. THREE.ShaderChunk[ "color_vertex" ],
  9154. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9155. THREE.ShaderChunk[ "skinbase_vertex" ],
  9156. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9157. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9158. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9159. THREE.ShaderChunk[ "skinning_vertex" ],
  9160. THREE.ShaderChunk[ "default_vertex" ],
  9161. THREE.ShaderChunk[ "worldpos_vertex" ],
  9162. THREE.ShaderChunk[ "envmap_vertex" ],
  9163. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9164. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9165. "}"
  9166. ].join("\n"),
  9167. fragmentShader: [
  9168. "uniform float opacity;",
  9169. "varying vec3 vLightFront;",
  9170. "#ifdef DOUBLE_SIDED",
  9171. "varying vec3 vLightBack;",
  9172. "#endif",
  9173. THREE.ShaderChunk[ "color_pars_fragment" ],
  9174. THREE.ShaderChunk[ "map_pars_fragment" ],
  9175. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9176. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9177. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9178. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9179. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9180. "void main() {",
  9181. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9182. THREE.ShaderChunk[ "map_fragment" ],
  9183. THREE.ShaderChunk[ "alphatest_fragment" ],
  9184. THREE.ShaderChunk[ "specularmap_fragment" ],
  9185. "#ifdef DOUBLE_SIDED",
  9186. //"float isFront = float( gl_FrontFacing );",
  9187. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9188. "if ( gl_FrontFacing )",
  9189. "gl_FragColor.xyz *= vLightFront;",
  9190. "else",
  9191. "gl_FragColor.xyz *= vLightBack;",
  9192. "#else",
  9193. "gl_FragColor.xyz *= vLightFront;",
  9194. "#endif",
  9195. THREE.ShaderChunk[ "lightmap_fragment" ],
  9196. THREE.ShaderChunk[ "color_fragment" ],
  9197. THREE.ShaderChunk[ "envmap_fragment" ],
  9198. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9199. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9200. THREE.ShaderChunk[ "fog_fragment" ],
  9201. "}"
  9202. ].join("\n")
  9203. },
  9204. 'phong': {
  9205. uniforms: THREE.UniformsUtils.merge( [
  9206. THREE.UniformsLib[ "common" ],
  9207. THREE.UniformsLib[ "bump" ],
  9208. THREE.UniformsLib[ "normalmap" ],
  9209. THREE.UniformsLib[ "fog" ],
  9210. THREE.UniformsLib[ "lights" ],
  9211. THREE.UniformsLib[ "shadowmap" ],
  9212. {
  9213. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9214. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9215. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  9216. "shininess": { type: "f", value: 30 },
  9217. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9218. }
  9219. ] ),
  9220. vertexShader: [
  9221. "#define PHONG",
  9222. "varying vec3 vViewPosition;",
  9223. "varying vec3 vNormal;",
  9224. THREE.ShaderChunk[ "map_pars_vertex" ],
  9225. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9226. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9227. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  9228. THREE.ShaderChunk[ "color_pars_vertex" ],
  9229. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9230. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9231. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9232. "void main() {",
  9233. THREE.ShaderChunk[ "map_vertex" ],
  9234. THREE.ShaderChunk[ "lightmap_vertex" ],
  9235. THREE.ShaderChunk[ "color_vertex" ],
  9236. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9237. THREE.ShaderChunk[ "skinbase_vertex" ],
  9238. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9239. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9240. "vNormal = normalize( transformedNormal );",
  9241. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9242. THREE.ShaderChunk[ "skinning_vertex" ],
  9243. THREE.ShaderChunk[ "default_vertex" ],
  9244. "vViewPosition = -mvPosition.xyz;",
  9245. THREE.ShaderChunk[ "worldpos_vertex" ],
  9246. THREE.ShaderChunk[ "envmap_vertex" ],
  9247. THREE.ShaderChunk[ "lights_phong_vertex" ],
  9248. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9249. "}"
  9250. ].join("\n"),
  9251. fragmentShader: [
  9252. "uniform vec3 diffuse;",
  9253. "uniform float opacity;",
  9254. "uniform vec3 ambient;",
  9255. "uniform vec3 emissive;",
  9256. "uniform vec3 specular;",
  9257. "uniform float shininess;",
  9258. THREE.ShaderChunk[ "color_pars_fragment" ],
  9259. THREE.ShaderChunk[ "map_pars_fragment" ],
  9260. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9261. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9262. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9263. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  9264. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9265. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  9266. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  9267. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9268. "void main() {",
  9269. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9270. THREE.ShaderChunk[ "map_fragment" ],
  9271. THREE.ShaderChunk[ "alphatest_fragment" ],
  9272. THREE.ShaderChunk[ "specularmap_fragment" ],
  9273. THREE.ShaderChunk[ "lights_phong_fragment" ],
  9274. THREE.ShaderChunk[ "lightmap_fragment" ],
  9275. THREE.ShaderChunk[ "color_fragment" ],
  9276. THREE.ShaderChunk[ "envmap_fragment" ],
  9277. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9278. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9279. THREE.ShaderChunk[ "fog_fragment" ],
  9280. "}"
  9281. ].join("\n")
  9282. },
  9283. 'particle_basic': {
  9284. uniforms: THREE.UniformsUtils.merge( [
  9285. THREE.UniformsLib[ "particle" ],
  9286. THREE.UniformsLib[ "shadowmap" ]
  9287. ] ),
  9288. vertexShader: [
  9289. "uniform float size;",
  9290. "uniform float scale;",
  9291. THREE.ShaderChunk[ "color_pars_vertex" ],
  9292. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9293. "void main() {",
  9294. THREE.ShaderChunk[ "color_vertex" ],
  9295. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9296. "#ifdef USE_SIZEATTENUATION",
  9297. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  9298. "#else",
  9299. "gl_PointSize = size;",
  9300. "#endif",
  9301. "gl_Position = projectionMatrix * mvPosition;",
  9302. THREE.ShaderChunk[ "worldpos_vertex" ],
  9303. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9304. "}"
  9305. ].join("\n"),
  9306. fragmentShader: [
  9307. "uniform vec3 psColor;",
  9308. "uniform float opacity;",
  9309. THREE.ShaderChunk[ "color_pars_fragment" ],
  9310. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  9311. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9312. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9313. "void main() {",
  9314. "gl_FragColor = vec4( psColor, opacity );",
  9315. THREE.ShaderChunk[ "map_particle_fragment" ],
  9316. THREE.ShaderChunk[ "alphatest_fragment" ],
  9317. THREE.ShaderChunk[ "color_fragment" ],
  9318. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9319. THREE.ShaderChunk[ "fog_fragment" ],
  9320. "}"
  9321. ].join("\n")
  9322. },
  9323. 'dashed': {
  9324. uniforms: THREE.UniformsUtils.merge( [
  9325. THREE.UniformsLib[ "common" ],
  9326. THREE.UniformsLib[ "fog" ],
  9327. {
  9328. "scale": { type: "f", value: 1 },
  9329. "dashSize": { type: "f", value: 1 },
  9330. "totalSize": { type: "f", value: 2 }
  9331. }
  9332. ] ),
  9333. vertexShader: [
  9334. "uniform float scale;",
  9335. "attribute float lineDistance;",
  9336. "varying float vLineDistance;",
  9337. THREE.ShaderChunk[ "color_pars_vertex" ],
  9338. "void main() {",
  9339. THREE.ShaderChunk[ "color_vertex" ],
  9340. "vLineDistance = scale * lineDistance;",
  9341. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9342. "gl_Position = projectionMatrix * mvPosition;",
  9343. "}"
  9344. ].join("\n"),
  9345. fragmentShader: [
  9346. "uniform vec3 diffuse;",
  9347. "uniform float opacity;",
  9348. "uniform float dashSize;",
  9349. "uniform float totalSize;",
  9350. "varying float vLineDistance;",
  9351. THREE.ShaderChunk[ "color_pars_fragment" ],
  9352. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9353. "void main() {",
  9354. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  9355. "discard;",
  9356. "}",
  9357. "gl_FragColor = vec4( diffuse, opacity );",
  9358. THREE.ShaderChunk[ "color_fragment" ],
  9359. THREE.ShaderChunk[ "fog_fragment" ],
  9360. "}"
  9361. ].join("\n")
  9362. },
  9363. // Depth encoding into RGBA texture
  9364. // based on SpiderGL shadow map example
  9365. // http://spidergl.org/example.php?id=6
  9366. // originally from
  9367. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  9368. // see also here:
  9369. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  9370. 'depthRGBA': {
  9371. uniforms: {},
  9372. vertexShader: [
  9373. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9374. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9375. "void main() {",
  9376. THREE.ShaderChunk[ "skinbase_vertex" ],
  9377. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9378. THREE.ShaderChunk[ "skinning_vertex" ],
  9379. THREE.ShaderChunk[ "default_vertex" ],
  9380. "}"
  9381. ].join("\n"),
  9382. fragmentShader: [
  9383. "vec4 pack_depth( const in float depth ) {",
  9384. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  9385. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  9386. "vec4 res = fract( depth * bit_shift );",
  9387. "res -= res.xxyz * bit_mask;",
  9388. "return res;",
  9389. "}",
  9390. "void main() {",
  9391. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  9392. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  9393. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  9394. //"gl_FragData[ 0 ] = pack_depth( z );",
  9395. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  9396. "}"
  9397. ].join("\n")
  9398. }
  9399. };
  9400. /**
  9401. * @author supereggbert / http://www.paulbrunt.co.uk/
  9402. * @author mrdoob / http://mrdoob.com/
  9403. * @author alteredq / http://alteredqualia.com/
  9404. * @author szimek / https://github.com/szimek/
  9405. */
  9406. THREE.WebGLRenderer = function ( parameters ) {
  9407. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  9408. parameters = parameters || {};
  9409. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  9410. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  9411. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  9412. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  9413. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  9414. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  9415. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  9416. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  9417. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  9418. // public properties
  9419. this.domElement = _canvas;
  9420. this.context = null;
  9421. // clearing
  9422. this.autoClear = true;
  9423. this.autoClearColor = true;
  9424. this.autoClearDepth = true;
  9425. this.autoClearStencil = true;
  9426. // scene graph
  9427. this.sortObjects = true;
  9428. this.autoUpdateObjects = true;
  9429. this.autoUpdateScene = true;
  9430. // physically based shading
  9431. this.gammaInput = false;
  9432. this.gammaOutput = false;
  9433. this.physicallyBasedShading = false;
  9434. // shadow map
  9435. this.shadowMapEnabled = false;
  9436. this.shadowMapAutoUpdate = true;
  9437. this.shadowMapSoft = true;
  9438. this.shadowMapCullFrontFaces = true;
  9439. this.shadowMapDebug = false;
  9440. this.shadowMapCascade = false;
  9441. // morphs
  9442. this.maxMorphTargets = 8;
  9443. this.maxMorphNormals = 4;
  9444. // flags
  9445. this.autoScaleCubemaps = true;
  9446. // custom render plugins
  9447. this.renderPluginsPre = [];
  9448. this.renderPluginsPost = [];
  9449. // info
  9450. this.info = {
  9451. memory: {
  9452. programs: 0,
  9453. geometries: 0,
  9454. textures: 0
  9455. },
  9456. render: {
  9457. calls: 0,
  9458. vertices: 0,
  9459. faces: 0,
  9460. points: 0
  9461. }
  9462. };
  9463. // internal properties
  9464. var _this = this,
  9465. _programs = [],
  9466. _programs_counter = 0,
  9467. // internal state cache
  9468. _currentProgram = null,
  9469. _currentFramebuffer = null,
  9470. _currentMaterialId = -1,
  9471. _currentGeometryGroupHash = null,
  9472. _currentCamera = null,
  9473. _geometryGroupCounter = 0,
  9474. _usedTextureUnits = 0,
  9475. // GL state cache
  9476. _oldDoubleSided = -1,
  9477. _oldFlipSided = -1,
  9478. _oldBlending = -1,
  9479. _oldBlendEquation = -1,
  9480. _oldBlendSrc = -1,
  9481. _oldBlendDst = -1,
  9482. _oldDepthTest = -1,
  9483. _oldDepthWrite = -1,
  9484. _oldPolygonOffset = null,
  9485. _oldPolygonOffsetFactor = null,
  9486. _oldPolygonOffsetUnits = null,
  9487. _oldLineWidth = null,
  9488. _viewportX = 0,
  9489. _viewportY = 0,
  9490. _viewportWidth = 0,
  9491. _viewportHeight = 0,
  9492. _currentWidth = 0,
  9493. _currentHeight = 0,
  9494. _enabledAttributes = {},
  9495. // frustum
  9496. _frustum = new THREE.Frustum(),
  9497. // camera matrices cache
  9498. _projScreenMatrix = new THREE.Matrix4(),
  9499. _projScreenMatrixPS = new THREE.Matrix4(),
  9500. _vector3 = new THREE.Vector4(),
  9501. // light arrays cache
  9502. _direction = new THREE.Vector3(),
  9503. _lightsNeedUpdate = true,
  9504. _lights = {
  9505. ambient: [ 0, 0, 0 ],
  9506. directional: { length: 0, colors: new Array(), positions: new Array() },
  9507. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  9508. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  9509. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  9510. };
  9511. // initialize
  9512. var _gl;
  9513. var _glExtensionTextureFloat;
  9514. var _glExtensionStandardDerivatives;
  9515. var _glExtensionTextureFilterAnisotropic;
  9516. var _glExtensionCompressedTextureS3TC;
  9517. initGL();
  9518. setDefaultGLState();
  9519. this.context = _gl;
  9520. // GPU capabilities
  9521. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  9522. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9523. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  9524. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9525. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  9526. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  9527. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  9528. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  9529. // API
  9530. this.getContext = function () {
  9531. return _gl;
  9532. };
  9533. this.supportsVertexTextures = function () {
  9534. return _supportsVertexTextures;
  9535. };
  9536. this.getMaxAnisotropy = function () {
  9537. return _maxAnisotropy;
  9538. };
  9539. this.setSize = function ( width, height ) {
  9540. _canvas.width = width;
  9541. _canvas.height = height;
  9542. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  9543. };
  9544. this.setViewport = function ( x, y, width, height ) {
  9545. _viewportX = x !== undefined ? x : 0;
  9546. _viewportY = y !== undefined ? y : 0;
  9547. _viewportWidth = width !== undefined ? width : _canvas.width;
  9548. _viewportHeight = height !== undefined ? height : _canvas.height;
  9549. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  9550. };
  9551. this.setScissor = function ( x, y, width, height ) {
  9552. _gl.scissor( x, y, width, height );
  9553. };
  9554. this.enableScissorTest = function ( enable ) {
  9555. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  9556. };
  9557. // Clearing
  9558. this.setClearColorHex = function ( hex, alpha ) {
  9559. _clearColor.setHex( hex );
  9560. _clearAlpha = alpha;
  9561. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9562. };
  9563. this.setClearColor = function ( color, alpha ) {
  9564. _clearColor.copy( color );
  9565. _clearAlpha = alpha;
  9566. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9567. };
  9568. this.getClearColor = function () {
  9569. return _clearColor;
  9570. };
  9571. this.getClearAlpha = function () {
  9572. return _clearAlpha;
  9573. };
  9574. this.clear = function ( color, depth, stencil ) {
  9575. var bits = 0;
  9576. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  9577. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  9578. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  9579. _gl.clear( bits );
  9580. };
  9581. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  9582. this.setRenderTarget( renderTarget );
  9583. this.clear( color, depth, stencil );
  9584. };
  9585. // Plugins
  9586. this.addPostPlugin = function ( plugin ) {
  9587. plugin.init( this );
  9588. this.renderPluginsPost.push( plugin );
  9589. };
  9590. this.addPrePlugin = function ( plugin ) {
  9591. plugin.init( this );
  9592. this.renderPluginsPre.push( plugin );
  9593. };
  9594. // Deallocation
  9595. this.deallocateObject = function ( object ) {
  9596. if ( ! object.__webglInit ) return;
  9597. object.__webglInit = false;
  9598. delete object._modelViewMatrix;
  9599. delete object._normalMatrix;
  9600. delete object._normalMatrixArray;
  9601. delete object._modelViewMatrixArray;
  9602. delete object._modelMatrixArray;
  9603. if ( object instanceof THREE.Mesh ) {
  9604. for ( var g in object.geometry.geometryGroups ) {
  9605. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  9606. }
  9607. } else if ( object instanceof THREE.Ribbon ) {
  9608. deleteRibbonBuffers( object.geometry );
  9609. } else if ( object instanceof THREE.Line ) {
  9610. deleteLineBuffers( object.geometry );
  9611. } else if ( object instanceof THREE.ParticleSystem ) {
  9612. deleteParticleBuffers( object.geometry );
  9613. }
  9614. };
  9615. this.deallocateTexture = function ( texture ) {
  9616. if ( ! texture.__webglInit ) return;
  9617. texture.__webglInit = false;
  9618. _gl.deleteTexture( texture.__webglTexture );
  9619. _this.info.memory.textures --;
  9620. };
  9621. this.deallocateRenderTarget = function ( renderTarget ) {
  9622. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  9623. _gl.deleteTexture( renderTarget.__webglTexture );
  9624. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9625. for ( var i = 0; i < 6; i ++ ) {
  9626. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  9627. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  9628. }
  9629. } else {
  9630. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  9631. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  9632. }
  9633. };
  9634. this.deallocateMaterial = function ( material ) {
  9635. var program = material.program;
  9636. if ( ! program ) return;
  9637. material.program = undefined;
  9638. // only deallocate GL program if this was the last use of shared program
  9639. // assumed there is only single copy of any program in the _programs list
  9640. // (that's how it's constructed)
  9641. var i, il, programInfo;
  9642. var deleteProgram = false;
  9643. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9644. programInfo = _programs[ i ];
  9645. if ( programInfo.program === program ) {
  9646. programInfo.usedTimes --;
  9647. if ( programInfo.usedTimes === 0 ) {
  9648. deleteProgram = true;
  9649. }
  9650. break;
  9651. }
  9652. }
  9653. if ( deleteProgram ) {
  9654. // avoid using array.splice, this is costlier than creating new array from scratch
  9655. var newPrograms = [];
  9656. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9657. programInfo = _programs[ i ];
  9658. if ( programInfo.program !== program ) {
  9659. newPrograms.push( programInfo );
  9660. }
  9661. }
  9662. _programs = newPrograms;
  9663. _gl.deleteProgram( program );
  9664. _this.info.memory.programs --;
  9665. }
  9666. };
  9667. // Rendering
  9668. this.updateShadowMap = function ( scene, camera ) {
  9669. _currentProgram = null;
  9670. _oldBlending = -1;
  9671. _oldDepthTest = -1;
  9672. _oldDepthWrite = -1;
  9673. _currentGeometryGroupHash = -1;
  9674. _currentMaterialId = -1;
  9675. _lightsNeedUpdate = true;
  9676. _oldDoubleSided = -1;
  9677. _oldFlipSided = -1;
  9678. this.shadowMapPlugin.update( scene, camera );
  9679. };
  9680. // Internal functions
  9681. // Buffer allocation
  9682. function createParticleBuffers ( geometry ) {
  9683. geometry.__webglVertexBuffer = _gl.createBuffer();
  9684. geometry.__webglColorBuffer = _gl.createBuffer();
  9685. _this.info.memory.geometries ++;
  9686. };
  9687. function createLineBuffers ( geometry ) {
  9688. geometry.__webglVertexBuffer = _gl.createBuffer();
  9689. geometry.__webglColorBuffer = _gl.createBuffer();
  9690. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  9691. _this.info.memory.geometries ++;
  9692. };
  9693. function createRibbonBuffers ( geometry ) {
  9694. geometry.__webglVertexBuffer = _gl.createBuffer();
  9695. geometry.__webglColorBuffer = _gl.createBuffer();
  9696. geometry.__webglNormalBuffer = _gl.createBuffer();
  9697. _this.info.memory.geometries ++;
  9698. };
  9699. function createMeshBuffers ( geometryGroup ) {
  9700. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  9701. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  9702. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  9703. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  9704. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  9705. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  9706. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  9707. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  9708. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  9709. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  9710. var m, ml;
  9711. if ( geometryGroup.numMorphTargets ) {
  9712. geometryGroup.__webglMorphTargetsBuffers = [];
  9713. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9714. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  9715. }
  9716. }
  9717. if ( geometryGroup.numMorphNormals ) {
  9718. geometryGroup.__webglMorphNormalsBuffers = [];
  9719. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9720. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  9721. }
  9722. }
  9723. _this.info.memory.geometries ++;
  9724. };
  9725. // Buffer deallocation
  9726. function deleteParticleBuffers ( geometry ) {
  9727. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9728. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9729. deleteCustomAttributesBuffers( geometry );
  9730. _this.info.memory.geometries --;
  9731. };
  9732. function deleteLineBuffers ( geometry ) {
  9733. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9734. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9735. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  9736. deleteCustomAttributesBuffers( geometry );
  9737. _this.info.memory.geometries --;
  9738. };
  9739. function deleteRibbonBuffers ( geometry ) {
  9740. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9741. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9742. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  9743. deleteCustomAttributesBuffers( geometry );
  9744. _this.info.memory.geometries --;
  9745. };
  9746. function deleteMeshBuffers ( geometryGroup ) {
  9747. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  9748. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  9749. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  9750. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  9751. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  9752. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  9753. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  9754. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  9755. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  9756. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  9757. var m, ml;
  9758. if ( geometryGroup.numMorphTargets ) {
  9759. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9760. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  9761. }
  9762. }
  9763. if ( geometryGroup.numMorphNormals ) {
  9764. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9765. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  9766. }
  9767. }
  9768. deleteCustomAttributesBuffers( geometryGroup );
  9769. _this.info.memory.geometries --;
  9770. };
  9771. function deleteCustomAttributesBuffers( geometry ) {
  9772. if ( geometry.__webglCustomAttributesList ) {
  9773. for ( var id in geometry.__webglCustomAttributesList ) {
  9774. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  9775. }
  9776. }
  9777. };
  9778. // Buffer initialization
  9779. function initCustomAttributes ( geometry, object ) {
  9780. var nvertices = geometry.vertices.length;
  9781. var material = object.material;
  9782. if ( material.attributes ) {
  9783. if ( geometry.__webglCustomAttributesList === undefined ) {
  9784. geometry.__webglCustomAttributesList = [];
  9785. }
  9786. for ( var a in material.attributes ) {
  9787. var attribute = material.attributes[ a ];
  9788. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9789. attribute.__webglInitialized = true;
  9790. var size = 1; // "f" and "i"
  9791. if ( attribute.type === "v2" ) size = 2;
  9792. else if ( attribute.type === "v3" ) size = 3;
  9793. else if ( attribute.type === "v4" ) size = 4;
  9794. else if ( attribute.type === "c" ) size = 3;
  9795. attribute.size = size;
  9796. attribute.array = new Float32Array( nvertices * size );
  9797. attribute.buffer = _gl.createBuffer();
  9798. attribute.buffer.belongsToAttribute = a;
  9799. attribute.needsUpdate = true;
  9800. }
  9801. geometry.__webglCustomAttributesList.push( attribute );
  9802. }
  9803. }
  9804. };
  9805. function initParticleBuffers ( geometry, object ) {
  9806. var nvertices = geometry.vertices.length;
  9807. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9808. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9809. geometry.__sortArray = [];
  9810. geometry.__webglParticleCount = nvertices;
  9811. initCustomAttributes ( geometry, object );
  9812. };
  9813. function initLineBuffers ( geometry, object ) {
  9814. var nvertices = geometry.vertices.length;
  9815. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9816. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9817. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  9818. geometry.__webglLineCount = nvertices;
  9819. initCustomAttributes ( geometry, object );
  9820. };
  9821. function initRibbonBuffers ( geometry, object ) {
  9822. var nvertices = geometry.vertices.length;
  9823. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9824. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9825. geometry.__normalArray = new Float32Array( nvertices * 3 );
  9826. geometry.__webglVertexCount = nvertices;
  9827. initCustomAttributes ( geometry, object );
  9828. };
  9829. function initMeshBuffers ( geometryGroup, object ) {
  9830. var geometry = object.geometry,
  9831. faces3 = geometryGroup.faces3,
  9832. faces4 = geometryGroup.faces4,
  9833. nvertices = faces3.length * 3 + faces4.length * 4,
  9834. ntris = faces3.length * 1 + faces4.length * 2,
  9835. nlines = faces3.length * 3 + faces4.length * 4,
  9836. material = getBufferMaterial( object, geometryGroup ),
  9837. uvType = bufferGuessUVType( material ),
  9838. normalType = bufferGuessNormalType( material ),
  9839. vertexColorType = bufferGuessVertexColorType( material );
  9840. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  9841. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  9842. if ( normalType ) {
  9843. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  9844. }
  9845. if ( geometry.hasTangents ) {
  9846. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  9847. }
  9848. if ( vertexColorType ) {
  9849. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  9850. }
  9851. if ( uvType ) {
  9852. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  9853. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  9854. }
  9855. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  9856. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  9857. }
  9858. }
  9859. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  9860. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  9861. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  9862. }
  9863. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  9864. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  9865. var m, ml;
  9866. if ( geometryGroup.numMorphTargets ) {
  9867. geometryGroup.__morphTargetsArrays = [];
  9868. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9869. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  9870. }
  9871. }
  9872. if ( geometryGroup.numMorphNormals ) {
  9873. geometryGroup.__morphNormalsArrays = [];
  9874. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9875. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  9876. }
  9877. }
  9878. geometryGroup.__webglFaceCount = ntris * 3;
  9879. geometryGroup.__webglLineCount = nlines * 2;
  9880. // custom attributes
  9881. if ( material.attributes ) {
  9882. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  9883. geometryGroup.__webglCustomAttributesList = [];
  9884. }
  9885. for ( var a in material.attributes ) {
  9886. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  9887. // attribute buffers which are correctly indexed in the setMeshBuffers function
  9888. var originalAttribute = material.attributes[ a ];
  9889. var attribute = {};
  9890. for ( var property in originalAttribute ) {
  9891. attribute[ property ] = originalAttribute[ property ];
  9892. }
  9893. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9894. attribute.__webglInitialized = true;
  9895. var size = 1; // "f" and "i"
  9896. if( attribute.type === "v2" ) size = 2;
  9897. else if( attribute.type === "v3" ) size = 3;
  9898. else if( attribute.type === "v4" ) size = 4;
  9899. else if( attribute.type === "c" ) size = 3;
  9900. attribute.size = size;
  9901. attribute.array = new Float32Array( nvertices * size );
  9902. attribute.buffer = _gl.createBuffer();
  9903. attribute.buffer.belongsToAttribute = a;
  9904. originalAttribute.needsUpdate = true;
  9905. attribute.__original = originalAttribute;
  9906. }
  9907. geometryGroup.__webglCustomAttributesList.push( attribute );
  9908. }
  9909. }
  9910. geometryGroup.__inittedArrays = true;
  9911. };
  9912. function getBufferMaterial( object, geometryGroup ) {
  9913. return object.material instanceof THREE.MeshFaceMaterial
  9914. ? object.material.materials[ geometryGroup.materialIndex ]
  9915. : object.material;
  9916. };
  9917. function materialNeedsSmoothNormals ( material ) {
  9918. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  9919. };
  9920. function bufferGuessNormalType ( material ) {
  9921. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  9922. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  9923. return false;
  9924. }
  9925. if ( materialNeedsSmoothNormals( material ) ) {
  9926. return THREE.SmoothShading;
  9927. } else {
  9928. return THREE.FlatShading;
  9929. }
  9930. };
  9931. function bufferGuessVertexColorType ( material ) {
  9932. if ( material.vertexColors ) {
  9933. return material.vertexColors;
  9934. }
  9935. return false;
  9936. };
  9937. function bufferGuessUVType ( material ) {
  9938. // material must use some texture to require uvs
  9939. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  9940. return true;
  9941. }
  9942. return false;
  9943. };
  9944. //
  9945. function initDirectBuffers( geometry ) {
  9946. var a, attribute, type;
  9947. for ( a in geometry.attributes ) {
  9948. if ( a === "index" ) {
  9949. type = _gl.ELEMENT_ARRAY_BUFFER;
  9950. } else {
  9951. type = _gl.ARRAY_BUFFER;
  9952. }
  9953. attribute = geometry.attributes[ a ];
  9954. attribute.buffer = _gl.createBuffer();
  9955. _gl.bindBuffer( type, attribute.buffer );
  9956. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  9957. }
  9958. };
  9959. // Buffer setting
  9960. function setParticleBuffers ( geometry, hint, object ) {
  9961. var v, c, vertex, offset, index, color,
  9962. vertices = geometry.vertices,
  9963. vl = vertices.length,
  9964. colors = geometry.colors,
  9965. cl = colors.length,
  9966. vertexArray = geometry.__vertexArray,
  9967. colorArray = geometry.__colorArray,
  9968. sortArray = geometry.__sortArray,
  9969. dirtyVertices = geometry.verticesNeedUpdate,
  9970. dirtyElements = geometry.elementsNeedUpdate,
  9971. dirtyColors = geometry.colorsNeedUpdate,
  9972. customAttributes = geometry.__webglCustomAttributesList,
  9973. i, il,
  9974. a, ca, cal, value,
  9975. customAttribute;
  9976. if ( object.sortParticles ) {
  9977. _projScreenMatrixPS.copy( _projScreenMatrix );
  9978. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  9979. for ( v = 0; v < vl; v ++ ) {
  9980. vertex = vertices[ v ];
  9981. _vector3.copy( vertex );
  9982. _projScreenMatrixPS.multiplyVector3( _vector3 );
  9983. sortArray[ v ] = [ _vector3.z, v ];
  9984. }
  9985. sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
  9986. for ( v = 0; v < vl; v ++ ) {
  9987. vertex = vertices[ sortArray[v][1] ];
  9988. offset = v * 3;
  9989. vertexArray[ offset ] = vertex.x;
  9990. vertexArray[ offset + 1 ] = vertex.y;
  9991. vertexArray[ offset + 2 ] = vertex.z;
  9992. }
  9993. for ( c = 0; c < cl; c ++ ) {
  9994. offset = c * 3;
  9995. color = colors[ sortArray[c][1] ];
  9996. colorArray[ offset ] = color.r;
  9997. colorArray[ offset + 1 ] = color.g;
  9998. colorArray[ offset + 2 ] = color.b;
  9999. }
  10000. if ( customAttributes ) {
  10001. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10002. customAttribute = customAttributes[ i ];
  10003. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  10004. offset = 0;
  10005. cal = customAttribute.value.length;
  10006. if ( customAttribute.size === 1 ) {
  10007. for ( ca = 0; ca < cal; ca ++ ) {
  10008. index = sortArray[ ca ][ 1 ];
  10009. customAttribute.array[ ca ] = customAttribute.value[ index ];
  10010. }
  10011. } else if ( customAttribute.size === 2 ) {
  10012. for ( ca = 0; ca < cal; ca ++ ) {
  10013. index = sortArray[ ca ][ 1 ];
  10014. value = customAttribute.value[ index ];
  10015. customAttribute.array[ offset ] = value.x;
  10016. customAttribute.array[ offset + 1 ] = value.y;
  10017. offset += 2;
  10018. }
  10019. } else if ( customAttribute.size === 3 ) {
  10020. if ( customAttribute.type === "c" ) {
  10021. for ( ca = 0; ca < cal; ca ++ ) {
  10022. index = sortArray[ ca ][ 1 ];
  10023. value = customAttribute.value[ index ];
  10024. customAttribute.array[ offset ] = value.r;
  10025. customAttribute.array[ offset + 1 ] = value.g;
  10026. customAttribute.array[ offset + 2 ] = value.b;
  10027. offset += 3;
  10028. }
  10029. } else {
  10030. for ( ca = 0; ca < cal; ca ++ ) {
  10031. index = sortArray[ ca ][ 1 ];
  10032. value = customAttribute.value[ index ];
  10033. customAttribute.array[ offset ] = value.x;
  10034. customAttribute.array[ offset + 1 ] = value.y;
  10035. customAttribute.array[ offset + 2 ] = value.z;
  10036. offset += 3;
  10037. }
  10038. }
  10039. } else if ( customAttribute.size === 4 ) {
  10040. for ( ca = 0; ca < cal; ca ++ ) {
  10041. index = sortArray[ ca ][ 1 ];
  10042. value = customAttribute.value[ index ];
  10043. customAttribute.array[ offset ] = value.x;
  10044. customAttribute.array[ offset + 1 ] = value.y;
  10045. customAttribute.array[ offset + 2 ] = value.z;
  10046. customAttribute.array[ offset + 3 ] = value.w;
  10047. offset += 4;
  10048. }
  10049. }
  10050. }
  10051. }
  10052. } else {
  10053. if ( dirtyVertices ) {
  10054. for ( v = 0; v < vl; v ++ ) {
  10055. vertex = vertices[ v ];
  10056. offset = v * 3;
  10057. vertexArray[ offset ] = vertex.x;
  10058. vertexArray[ offset + 1 ] = vertex.y;
  10059. vertexArray[ offset + 2 ] = vertex.z;
  10060. }
  10061. }
  10062. if ( dirtyColors ) {
  10063. for ( c = 0; c < cl; c ++ ) {
  10064. color = colors[ c ];
  10065. offset = c * 3;
  10066. colorArray[ offset ] = color.r;
  10067. colorArray[ offset + 1 ] = color.g;
  10068. colorArray[ offset + 2 ] = color.b;
  10069. }
  10070. }
  10071. if ( customAttributes ) {
  10072. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10073. customAttribute = customAttributes[ i ];
  10074. if ( customAttribute.needsUpdate &&
  10075. ( customAttribute.boundTo === undefined ||
  10076. customAttribute.boundTo === "vertices") ) {
  10077. cal = customAttribute.value.length;
  10078. offset = 0;
  10079. if ( customAttribute.size === 1 ) {
  10080. for ( ca = 0; ca < cal; ca ++ ) {
  10081. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10082. }
  10083. } else if ( customAttribute.size === 2 ) {
  10084. for ( ca = 0; ca < cal; ca ++ ) {
  10085. value = customAttribute.value[ ca ];
  10086. customAttribute.array[ offset ] = value.x;
  10087. customAttribute.array[ offset + 1 ] = value.y;
  10088. offset += 2;
  10089. }
  10090. } else if ( customAttribute.size === 3 ) {
  10091. if ( customAttribute.type === "c" ) {
  10092. for ( ca = 0; ca < cal; ca ++ ) {
  10093. value = customAttribute.value[ ca ];
  10094. customAttribute.array[ offset ] = value.r;
  10095. customAttribute.array[ offset + 1 ] = value.g;
  10096. customAttribute.array[ offset + 2 ] = value.b;
  10097. offset += 3;
  10098. }
  10099. } else {
  10100. for ( ca = 0; ca < cal; ca ++ ) {
  10101. value = customAttribute.value[ ca ];
  10102. customAttribute.array[ offset ] = value.x;
  10103. customAttribute.array[ offset + 1 ] = value.y;
  10104. customAttribute.array[ offset + 2 ] = value.z;
  10105. offset += 3;
  10106. }
  10107. }
  10108. } else if ( customAttribute.size === 4 ) {
  10109. for ( ca = 0; ca < cal; ca ++ ) {
  10110. value = customAttribute.value[ ca ];
  10111. customAttribute.array[ offset ] = value.x;
  10112. customAttribute.array[ offset + 1 ] = value.y;
  10113. customAttribute.array[ offset + 2 ] = value.z;
  10114. customAttribute.array[ offset + 3 ] = value.w;
  10115. offset += 4;
  10116. }
  10117. }
  10118. }
  10119. }
  10120. }
  10121. }
  10122. if ( dirtyVertices || object.sortParticles ) {
  10123. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10124. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10125. }
  10126. if ( dirtyColors || object.sortParticles ) {
  10127. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10128. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10129. }
  10130. if ( customAttributes ) {
  10131. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10132. customAttribute = customAttributes[ i ];
  10133. if ( customAttribute.needsUpdate || object.sortParticles ) {
  10134. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10135. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10136. }
  10137. }
  10138. }
  10139. };
  10140. function setLineBuffers ( geometry, hint ) {
  10141. var v, c, d, vertex, offset, color,
  10142. vertices = geometry.vertices,
  10143. colors = geometry.colors,
  10144. lineDistances = geometry.lineDistances,
  10145. vl = vertices.length,
  10146. cl = colors.length,
  10147. dl = lineDistances.length,
  10148. vertexArray = geometry.__vertexArray,
  10149. colorArray = geometry.__colorArray,
  10150. lineDistanceArray = geometry.__lineDistanceArray,
  10151. dirtyVertices = geometry.verticesNeedUpdate,
  10152. dirtyColors = geometry.colorsNeedUpdate,
  10153. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  10154. customAttributes = geometry.__webglCustomAttributesList,
  10155. i, il,
  10156. a, ca, cal, value,
  10157. customAttribute;
  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. if ( dirtyLineDistances ) {
  10181. for ( d = 0; d < dl; d ++ ) {
  10182. lineDistanceArray[ d ] = lineDistances[ d ];
  10183. }
  10184. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  10185. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  10186. }
  10187. if ( customAttributes ) {
  10188. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10189. customAttribute = customAttributes[ i ];
  10190. if ( customAttribute.needsUpdate &&
  10191. ( customAttribute.boundTo === undefined ||
  10192. customAttribute.boundTo === "vertices" ) ) {
  10193. offset = 0;
  10194. cal = customAttribute.value.length;
  10195. if ( customAttribute.size === 1 ) {
  10196. for ( ca = 0; ca < cal; ca ++ ) {
  10197. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10198. }
  10199. } else if ( customAttribute.size === 2 ) {
  10200. for ( ca = 0; ca < cal; ca ++ ) {
  10201. value = customAttribute.value[ ca ];
  10202. customAttribute.array[ offset ] = value.x;
  10203. customAttribute.array[ offset + 1 ] = value.y;
  10204. offset += 2;
  10205. }
  10206. } else if ( customAttribute.size === 3 ) {
  10207. if ( customAttribute.type === "c" ) {
  10208. for ( ca = 0; ca < cal; ca ++ ) {
  10209. value = customAttribute.value[ ca ];
  10210. customAttribute.array[ offset ] = value.r;
  10211. customAttribute.array[ offset + 1 ] = value.g;
  10212. customAttribute.array[ offset + 2 ] = value.b;
  10213. offset += 3;
  10214. }
  10215. } else {
  10216. for ( ca = 0; ca < cal; ca ++ ) {
  10217. value = customAttribute.value[ ca ];
  10218. customAttribute.array[ offset ] = value.x;
  10219. customAttribute.array[ offset + 1 ] = value.y;
  10220. customAttribute.array[ offset + 2 ] = value.z;
  10221. offset += 3;
  10222. }
  10223. }
  10224. } else if ( customAttribute.size === 4 ) {
  10225. for ( ca = 0; ca < cal; ca ++ ) {
  10226. value = customAttribute.value[ ca ];
  10227. customAttribute.array[ offset ] = value.x;
  10228. customAttribute.array[ offset + 1 ] = value.y;
  10229. customAttribute.array[ offset + 2 ] = value.z;
  10230. customAttribute.array[ offset + 3 ] = value.w;
  10231. offset += 4;
  10232. }
  10233. }
  10234. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10235. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10236. }
  10237. }
  10238. }
  10239. };
  10240. function setRibbonBuffers ( geometry, hint ) {
  10241. var v, c, n, vertex, offset, color, normal,
  10242. i, il, ca, cal, customAttribute, value,
  10243. vertices = geometry.vertices,
  10244. colors = geometry.colors,
  10245. normals = geometry.normals,
  10246. vl = vertices.length,
  10247. cl = colors.length,
  10248. nl = normals.length,
  10249. vertexArray = geometry.__vertexArray,
  10250. colorArray = geometry.__colorArray,
  10251. normalArray = geometry.__normalArray,
  10252. dirtyVertices = geometry.verticesNeedUpdate,
  10253. dirtyColors = geometry.colorsNeedUpdate,
  10254. dirtyNormals = geometry.normalsNeedUpdate,
  10255. customAttributes = geometry.__webglCustomAttributesList;
  10256. if ( dirtyVertices ) {
  10257. for ( v = 0; v < vl; v ++ ) {
  10258. vertex = vertices[ v ];
  10259. offset = v * 3;
  10260. vertexArray[ offset ] = vertex.x;
  10261. vertexArray[ offset + 1 ] = vertex.y;
  10262. vertexArray[ offset + 2 ] = vertex.z;
  10263. }
  10264. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10265. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10266. }
  10267. if ( dirtyColors ) {
  10268. for ( c = 0; c < cl; c ++ ) {
  10269. color = colors[ c ];
  10270. offset = c * 3;
  10271. colorArray[ offset ] = color.r;
  10272. colorArray[ offset + 1 ] = color.g;
  10273. colorArray[ offset + 2 ] = color.b;
  10274. }
  10275. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10276. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10277. }
  10278. if ( dirtyNormals ) {
  10279. for ( n = 0; n < nl; n ++ ) {
  10280. normal = normals[ n ];
  10281. offset = n * 3;
  10282. normalArray[ offset ] = normal.x;
  10283. normalArray[ offset + 1 ] = normal.y;
  10284. normalArray[ offset + 2 ] = normal.z;
  10285. }
  10286. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  10287. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10288. }
  10289. if ( customAttributes ) {
  10290. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10291. customAttribute = customAttributes[ i ];
  10292. if ( customAttribute.needsUpdate &&
  10293. ( customAttribute.boundTo === undefined ||
  10294. customAttribute.boundTo === "vertices" ) ) {
  10295. offset = 0;
  10296. cal = customAttribute.value.length;
  10297. if ( customAttribute.size === 1 ) {
  10298. for ( ca = 0; ca < cal; ca ++ ) {
  10299. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10300. }
  10301. } else if ( customAttribute.size === 2 ) {
  10302. for ( ca = 0; ca < cal; ca ++ ) {
  10303. value = customAttribute.value[ ca ];
  10304. customAttribute.array[ offset ] = value.x;
  10305. customAttribute.array[ offset + 1 ] = value.y;
  10306. offset += 2;
  10307. }
  10308. } else if ( customAttribute.size === 3 ) {
  10309. if ( customAttribute.type === "c" ) {
  10310. for ( ca = 0; ca < cal; ca ++ ) {
  10311. value = customAttribute.value[ ca ];
  10312. customAttribute.array[ offset ] = value.r;
  10313. customAttribute.array[ offset + 1 ] = value.g;
  10314. customAttribute.array[ offset + 2 ] = value.b;
  10315. offset += 3;
  10316. }
  10317. } else {
  10318. for ( ca = 0; ca < cal; ca ++ ) {
  10319. value = customAttribute.value[ ca ];
  10320. customAttribute.array[ offset ] = value.x;
  10321. customAttribute.array[ offset + 1 ] = value.y;
  10322. customAttribute.array[ offset + 2 ] = value.z;
  10323. offset += 3;
  10324. }
  10325. }
  10326. } else if ( customAttribute.size === 4 ) {
  10327. for ( ca = 0; ca < cal; ca ++ ) {
  10328. value = customAttribute.value[ ca ];
  10329. customAttribute.array[ offset ] = value.x;
  10330. customAttribute.array[ offset + 1 ] = value.y;
  10331. customAttribute.array[ offset + 2 ] = value.z;
  10332. customAttribute.array[ offset + 3 ] = value.w;
  10333. offset += 4;
  10334. }
  10335. }
  10336. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10337. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10338. }
  10339. }
  10340. }
  10341. };
  10342. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  10343. if ( ! geometryGroup.__inittedArrays ) {
  10344. return;
  10345. }
  10346. var normalType = bufferGuessNormalType( material ),
  10347. vertexColorType = bufferGuessVertexColorType( material ),
  10348. uvType = bufferGuessUVType( material ),
  10349. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  10350. var f, fl, fi, face,
  10351. vertexNormals, faceNormal, normal,
  10352. vertexColors, faceColor,
  10353. vertexTangents,
  10354. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  10355. c1, c2, c3, c4,
  10356. sw1, sw2, sw3, sw4,
  10357. si1, si2, si3, si4,
  10358. sa1, sa2, sa3, sa4,
  10359. sb1, sb2, sb3, sb4,
  10360. m, ml, i, il,
  10361. vn, uvi, uv2i,
  10362. vk, vkl, vka,
  10363. nka, chf, faceVertexNormals,
  10364. a,
  10365. vertexIndex = 0,
  10366. offset = 0,
  10367. offset_uv = 0,
  10368. offset_uv2 = 0,
  10369. offset_face = 0,
  10370. offset_normal = 0,
  10371. offset_tangent = 0,
  10372. offset_line = 0,
  10373. offset_color = 0,
  10374. offset_skin = 0,
  10375. offset_morphTarget = 0,
  10376. offset_custom = 0,
  10377. offset_customSrc = 0,
  10378. value,
  10379. vertexArray = geometryGroup.__vertexArray,
  10380. uvArray = geometryGroup.__uvArray,
  10381. uv2Array = geometryGroup.__uv2Array,
  10382. normalArray = geometryGroup.__normalArray,
  10383. tangentArray = geometryGroup.__tangentArray,
  10384. colorArray = geometryGroup.__colorArray,
  10385. skinIndexArray = geometryGroup.__skinIndexArray,
  10386. skinWeightArray = geometryGroup.__skinWeightArray,
  10387. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  10388. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  10389. customAttributes = geometryGroup.__webglCustomAttributesList,
  10390. customAttribute,
  10391. faceArray = geometryGroup.__faceArray,
  10392. lineArray = geometryGroup.__lineArray,
  10393. geometry = object.geometry, // this is shared for all chunks
  10394. dirtyVertices = geometry.verticesNeedUpdate,
  10395. dirtyElements = geometry.elementsNeedUpdate,
  10396. dirtyUvs = geometry.uvsNeedUpdate,
  10397. dirtyNormals = geometry.normalsNeedUpdate,
  10398. dirtyTangents = geometry.tangentsNeedUpdate,
  10399. dirtyColors = geometry.colorsNeedUpdate,
  10400. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  10401. vertices = geometry.vertices,
  10402. chunk_faces3 = geometryGroup.faces3,
  10403. chunk_faces4 = geometryGroup.faces4,
  10404. obj_faces = geometry.faces,
  10405. obj_uvs = geometry.faceVertexUvs[ 0 ],
  10406. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  10407. obj_colors = geometry.colors,
  10408. obj_skinIndices = geometry.skinIndices,
  10409. obj_skinWeights = geometry.skinWeights,
  10410. morphTargets = geometry.morphTargets,
  10411. morphNormals = geometry.morphNormals;
  10412. if ( dirtyVertices ) {
  10413. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10414. face = obj_faces[ chunk_faces3[ f ] ];
  10415. v1 = vertices[ face.a ];
  10416. v2 = vertices[ face.b ];
  10417. v3 = vertices[ face.c ];
  10418. vertexArray[ offset ] = v1.x;
  10419. vertexArray[ offset + 1 ] = v1.y;
  10420. vertexArray[ offset + 2 ] = v1.z;
  10421. vertexArray[ offset + 3 ] = v2.x;
  10422. vertexArray[ offset + 4 ] = v2.y;
  10423. vertexArray[ offset + 5 ] = v2.z;
  10424. vertexArray[ offset + 6 ] = v3.x;
  10425. vertexArray[ offset + 7 ] = v3.y;
  10426. vertexArray[ offset + 8 ] = v3.z;
  10427. offset += 9;
  10428. }
  10429. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10430. face = obj_faces[ chunk_faces4[ f ] ];
  10431. v1 = vertices[ face.a ];
  10432. v2 = vertices[ face.b ];
  10433. v3 = vertices[ face.c ];
  10434. v4 = vertices[ face.d ];
  10435. vertexArray[ offset ] = v1.x;
  10436. vertexArray[ offset + 1 ] = v1.y;
  10437. vertexArray[ offset + 2 ] = v1.z;
  10438. vertexArray[ offset + 3 ] = v2.x;
  10439. vertexArray[ offset + 4 ] = v2.y;
  10440. vertexArray[ offset + 5 ] = v2.z;
  10441. vertexArray[ offset + 6 ] = v3.x;
  10442. vertexArray[ offset + 7 ] = v3.y;
  10443. vertexArray[ offset + 8 ] = v3.z;
  10444. vertexArray[ offset + 9 ] = v4.x;
  10445. vertexArray[ offset + 10 ] = v4.y;
  10446. vertexArray[ offset + 11 ] = v4.z;
  10447. offset += 12;
  10448. }
  10449. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  10450. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10451. }
  10452. if ( dirtyMorphTargets ) {
  10453. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  10454. offset_morphTarget = 0;
  10455. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10456. chf = chunk_faces3[ f ];
  10457. face = obj_faces[ chf ];
  10458. // morph positions
  10459. v1 = morphTargets[ vk ].vertices[ face.a ];
  10460. v2 = morphTargets[ vk ].vertices[ face.b ];
  10461. v3 = morphTargets[ vk ].vertices[ face.c ];
  10462. vka = morphTargetsArrays[ vk ];
  10463. vka[ offset_morphTarget ] = v1.x;
  10464. vka[ offset_morphTarget + 1 ] = v1.y;
  10465. vka[ offset_morphTarget + 2 ] = v1.z;
  10466. vka[ offset_morphTarget + 3 ] = v2.x;
  10467. vka[ offset_morphTarget + 4 ] = v2.y;
  10468. vka[ offset_morphTarget + 5 ] = v2.z;
  10469. vka[ offset_morphTarget + 6 ] = v3.x;
  10470. vka[ offset_morphTarget + 7 ] = v3.y;
  10471. vka[ offset_morphTarget + 8 ] = v3.z;
  10472. // morph normals
  10473. if ( material.morphNormals ) {
  10474. if ( needsSmoothNormals ) {
  10475. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10476. n1 = faceVertexNormals.a;
  10477. n2 = faceVertexNormals.b;
  10478. n3 = faceVertexNormals.c;
  10479. } else {
  10480. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10481. n2 = n1;
  10482. n3 = n1;
  10483. }
  10484. nka = morphNormalsArrays[ vk ];
  10485. nka[ offset_morphTarget ] = n1.x;
  10486. nka[ offset_morphTarget + 1 ] = n1.y;
  10487. nka[ offset_morphTarget + 2 ] = n1.z;
  10488. nka[ offset_morphTarget + 3 ] = n2.x;
  10489. nka[ offset_morphTarget + 4 ] = n2.y;
  10490. nka[ offset_morphTarget + 5 ] = n2.z;
  10491. nka[ offset_morphTarget + 6 ] = n3.x;
  10492. nka[ offset_morphTarget + 7 ] = n3.y;
  10493. nka[ offset_morphTarget + 8 ] = n3.z;
  10494. }
  10495. //
  10496. offset_morphTarget += 9;
  10497. }
  10498. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10499. chf = chunk_faces4[ f ];
  10500. face = obj_faces[ chf ];
  10501. // morph positions
  10502. v1 = morphTargets[ vk ].vertices[ face.a ];
  10503. v2 = morphTargets[ vk ].vertices[ face.b ];
  10504. v3 = morphTargets[ vk ].vertices[ face.c ];
  10505. v4 = morphTargets[ vk ].vertices[ face.d ];
  10506. vka = morphTargetsArrays[ vk ];
  10507. vka[ offset_morphTarget ] = v1.x;
  10508. vka[ offset_morphTarget + 1 ] = v1.y;
  10509. vka[ offset_morphTarget + 2 ] = v1.z;
  10510. vka[ offset_morphTarget + 3 ] = v2.x;
  10511. vka[ offset_morphTarget + 4 ] = v2.y;
  10512. vka[ offset_morphTarget + 5 ] = v2.z;
  10513. vka[ offset_morphTarget + 6 ] = v3.x;
  10514. vka[ offset_morphTarget + 7 ] = v3.y;
  10515. vka[ offset_morphTarget + 8 ] = v3.z;
  10516. vka[ offset_morphTarget + 9 ] = v4.x;
  10517. vka[ offset_morphTarget + 10 ] = v4.y;
  10518. vka[ offset_morphTarget + 11 ] = v4.z;
  10519. // morph normals
  10520. if ( material.morphNormals ) {
  10521. if ( needsSmoothNormals ) {
  10522. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10523. n1 = faceVertexNormals.a;
  10524. n2 = faceVertexNormals.b;
  10525. n3 = faceVertexNormals.c;
  10526. n4 = faceVertexNormals.d;
  10527. } else {
  10528. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10529. n2 = n1;
  10530. n3 = n1;
  10531. n4 = n1;
  10532. }
  10533. nka = morphNormalsArrays[ vk ];
  10534. nka[ offset_morphTarget ] = n1.x;
  10535. nka[ offset_morphTarget + 1 ] = n1.y;
  10536. nka[ offset_morphTarget + 2 ] = n1.z;
  10537. nka[ offset_morphTarget + 3 ] = n2.x;
  10538. nka[ offset_morphTarget + 4 ] = n2.y;
  10539. nka[ offset_morphTarget + 5 ] = n2.z;
  10540. nka[ offset_morphTarget + 6 ] = n3.x;
  10541. nka[ offset_morphTarget + 7 ] = n3.y;
  10542. nka[ offset_morphTarget + 8 ] = n3.z;
  10543. nka[ offset_morphTarget + 9 ] = n4.x;
  10544. nka[ offset_morphTarget + 10 ] = n4.y;
  10545. nka[ offset_morphTarget + 11 ] = n4.z;
  10546. }
  10547. //
  10548. offset_morphTarget += 12;
  10549. }
  10550. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  10551. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  10552. if ( material.morphNormals ) {
  10553. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  10554. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  10555. }
  10556. }
  10557. }
  10558. if ( obj_skinWeights.length ) {
  10559. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10560. face = obj_faces[ chunk_faces3[ f ] ];
  10561. // weights
  10562. sw1 = obj_skinWeights[ face.a ];
  10563. sw2 = obj_skinWeights[ face.b ];
  10564. sw3 = obj_skinWeights[ face.c ];
  10565. skinWeightArray[ offset_skin ] = sw1.x;
  10566. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10567. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10568. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10569. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10570. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10571. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10572. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10573. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10574. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10575. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10576. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10577. // indices
  10578. si1 = obj_skinIndices[ face.a ];
  10579. si2 = obj_skinIndices[ face.b ];
  10580. si3 = obj_skinIndices[ face.c ];
  10581. skinIndexArray[ offset_skin ] = si1.x;
  10582. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10583. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10584. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10585. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10586. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10587. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10588. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10589. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10590. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10591. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10592. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10593. offset_skin += 12;
  10594. }
  10595. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10596. face = obj_faces[ chunk_faces4[ f ] ];
  10597. // weights
  10598. sw1 = obj_skinWeights[ face.a ];
  10599. sw2 = obj_skinWeights[ face.b ];
  10600. sw3 = obj_skinWeights[ face.c ];
  10601. sw4 = obj_skinWeights[ face.d ];
  10602. skinWeightArray[ offset_skin ] = sw1.x;
  10603. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10604. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10605. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10606. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10607. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10608. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10609. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10610. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10611. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10612. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10613. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10614. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  10615. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  10616. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  10617. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  10618. // indices
  10619. si1 = obj_skinIndices[ face.a ];
  10620. si2 = obj_skinIndices[ face.b ];
  10621. si3 = obj_skinIndices[ face.c ];
  10622. si4 = obj_skinIndices[ face.d ];
  10623. skinIndexArray[ offset_skin ] = si1.x;
  10624. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10625. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10626. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10627. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10628. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10629. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10630. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10631. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10632. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10633. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10634. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10635. skinIndexArray[ offset_skin + 12 ] = si4.x;
  10636. skinIndexArray[ offset_skin + 13 ] = si4.y;
  10637. skinIndexArray[ offset_skin + 14 ] = si4.z;
  10638. skinIndexArray[ offset_skin + 15 ] = si4.w;
  10639. offset_skin += 16;
  10640. }
  10641. if ( offset_skin > 0 ) {
  10642. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10643. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  10644. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10645. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  10646. }
  10647. }
  10648. if ( dirtyColors && vertexColorType ) {
  10649. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10650. face = obj_faces[ chunk_faces3[ f ] ];
  10651. vertexColors = face.vertexColors;
  10652. faceColor = face.color;
  10653. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  10654. c1 = vertexColors[ 0 ];
  10655. c2 = vertexColors[ 1 ];
  10656. c3 = vertexColors[ 2 ];
  10657. } else {
  10658. c1 = faceColor;
  10659. c2 = faceColor;
  10660. c3 = faceColor;
  10661. }
  10662. colorArray[ offset_color ] = c1.r;
  10663. colorArray[ offset_color + 1 ] = c1.g;
  10664. colorArray[ offset_color + 2 ] = c1.b;
  10665. colorArray[ offset_color + 3 ] = c2.r;
  10666. colorArray[ offset_color + 4 ] = c2.g;
  10667. colorArray[ offset_color + 5 ] = c2.b;
  10668. colorArray[ offset_color + 6 ] = c3.r;
  10669. colorArray[ offset_color + 7 ] = c3.g;
  10670. colorArray[ offset_color + 8 ] = c3.b;
  10671. offset_color += 9;
  10672. }
  10673. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10674. face = obj_faces[ chunk_faces4[ f ] ];
  10675. vertexColors = face.vertexColors;
  10676. faceColor = face.color;
  10677. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  10678. c1 = vertexColors[ 0 ];
  10679. c2 = vertexColors[ 1 ];
  10680. c3 = vertexColors[ 2 ];
  10681. c4 = vertexColors[ 3 ];
  10682. } else {
  10683. c1 = faceColor;
  10684. c2 = faceColor;
  10685. c3 = faceColor;
  10686. c4 = faceColor;
  10687. }
  10688. colorArray[ offset_color ] = c1.r;
  10689. colorArray[ offset_color + 1 ] = c1.g;
  10690. colorArray[ offset_color + 2 ] = c1.b;
  10691. colorArray[ offset_color + 3 ] = c2.r;
  10692. colorArray[ offset_color + 4 ] = c2.g;
  10693. colorArray[ offset_color + 5 ] = c2.b;
  10694. colorArray[ offset_color + 6 ] = c3.r;
  10695. colorArray[ offset_color + 7 ] = c3.g;
  10696. colorArray[ offset_color + 8 ] = c3.b;
  10697. colorArray[ offset_color + 9 ] = c4.r;
  10698. colorArray[ offset_color + 10 ] = c4.g;
  10699. colorArray[ offset_color + 11 ] = c4.b;
  10700. offset_color += 12;
  10701. }
  10702. if ( offset_color > 0 ) {
  10703. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  10704. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10705. }
  10706. }
  10707. if ( dirtyTangents && geometry.hasTangents ) {
  10708. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10709. face = obj_faces[ chunk_faces3[ f ] ];
  10710. vertexTangents = face.vertexTangents;
  10711. t1 = vertexTangents[ 0 ];
  10712. t2 = vertexTangents[ 1 ];
  10713. t3 = vertexTangents[ 2 ];
  10714. tangentArray[ offset_tangent ] = t1.x;
  10715. tangentArray[ offset_tangent + 1 ] = t1.y;
  10716. tangentArray[ offset_tangent + 2 ] = t1.z;
  10717. tangentArray[ offset_tangent + 3 ] = t1.w;
  10718. tangentArray[ offset_tangent + 4 ] = t2.x;
  10719. tangentArray[ offset_tangent + 5 ] = t2.y;
  10720. tangentArray[ offset_tangent + 6 ] = t2.z;
  10721. tangentArray[ offset_tangent + 7 ] = t2.w;
  10722. tangentArray[ offset_tangent + 8 ] = t3.x;
  10723. tangentArray[ offset_tangent + 9 ] = t3.y;
  10724. tangentArray[ offset_tangent + 10 ] = t3.z;
  10725. tangentArray[ offset_tangent + 11 ] = t3.w;
  10726. offset_tangent += 12;
  10727. }
  10728. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10729. face = obj_faces[ chunk_faces4[ f ] ];
  10730. vertexTangents = face.vertexTangents;
  10731. t1 = vertexTangents[ 0 ];
  10732. t2 = vertexTangents[ 1 ];
  10733. t3 = vertexTangents[ 2 ];
  10734. t4 = vertexTangents[ 3 ];
  10735. tangentArray[ offset_tangent ] = t1.x;
  10736. tangentArray[ offset_tangent + 1 ] = t1.y;
  10737. tangentArray[ offset_tangent + 2 ] = t1.z;
  10738. tangentArray[ offset_tangent + 3 ] = t1.w;
  10739. tangentArray[ offset_tangent + 4 ] = t2.x;
  10740. tangentArray[ offset_tangent + 5 ] = t2.y;
  10741. tangentArray[ offset_tangent + 6 ] = t2.z;
  10742. tangentArray[ offset_tangent + 7 ] = t2.w;
  10743. tangentArray[ offset_tangent + 8 ] = t3.x;
  10744. tangentArray[ offset_tangent + 9 ] = t3.y;
  10745. tangentArray[ offset_tangent + 10 ] = t3.z;
  10746. tangentArray[ offset_tangent + 11 ] = t3.w;
  10747. tangentArray[ offset_tangent + 12 ] = t4.x;
  10748. tangentArray[ offset_tangent + 13 ] = t4.y;
  10749. tangentArray[ offset_tangent + 14 ] = t4.z;
  10750. tangentArray[ offset_tangent + 15 ] = t4.w;
  10751. offset_tangent += 16;
  10752. }
  10753. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  10754. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  10755. }
  10756. if ( dirtyNormals && normalType ) {
  10757. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10758. face = obj_faces[ chunk_faces3[ f ] ];
  10759. vertexNormals = face.vertexNormals;
  10760. faceNormal = face.normal;
  10761. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  10762. for ( i = 0; i < 3; i ++ ) {
  10763. vn = vertexNormals[ i ];
  10764. normalArray[ offset_normal ] = vn.x;
  10765. normalArray[ offset_normal + 1 ] = vn.y;
  10766. normalArray[ offset_normal + 2 ] = vn.z;
  10767. offset_normal += 3;
  10768. }
  10769. } else {
  10770. for ( i = 0; i < 3; i ++ ) {
  10771. normalArray[ offset_normal ] = faceNormal.x;
  10772. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10773. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10774. offset_normal += 3;
  10775. }
  10776. }
  10777. }
  10778. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10779. face = obj_faces[ chunk_faces4[ f ] ];
  10780. vertexNormals = face.vertexNormals;
  10781. faceNormal = face.normal;
  10782. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  10783. for ( i = 0; i < 4; i ++ ) {
  10784. vn = vertexNormals[ i ];
  10785. normalArray[ offset_normal ] = vn.x;
  10786. normalArray[ offset_normal + 1 ] = vn.y;
  10787. normalArray[ offset_normal + 2 ] = vn.z;
  10788. offset_normal += 3;
  10789. }
  10790. } else {
  10791. for ( i = 0; i < 4; i ++ ) {
  10792. normalArray[ offset_normal ] = faceNormal.x;
  10793. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10794. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10795. offset_normal += 3;
  10796. }
  10797. }
  10798. }
  10799. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  10800. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10801. }
  10802. if ( dirtyUvs && obj_uvs && uvType ) {
  10803. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10804. fi = chunk_faces3[ f ];
  10805. uv = obj_uvs[ fi ];
  10806. if ( uv === undefined ) continue;
  10807. for ( i = 0; i < 3; i ++ ) {
  10808. uvi = uv[ i ];
  10809. uvArray[ offset_uv ] = uvi.u;
  10810. uvArray[ offset_uv + 1 ] = uvi.v;
  10811. offset_uv += 2;
  10812. }
  10813. }
  10814. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10815. fi = chunk_faces4[ f ];
  10816. uv = obj_uvs[ fi ];
  10817. if ( uv === undefined ) continue;
  10818. for ( i = 0; i < 4; i ++ ) {
  10819. uvi = uv[ i ];
  10820. uvArray[ offset_uv ] = uvi.u;
  10821. uvArray[ offset_uv + 1 ] = uvi.v;
  10822. offset_uv += 2;
  10823. }
  10824. }
  10825. if ( offset_uv > 0 ) {
  10826. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  10827. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  10828. }
  10829. }
  10830. if ( dirtyUvs && obj_uvs2 && uvType ) {
  10831. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10832. fi = chunk_faces3[ f ];
  10833. uv2 = obj_uvs2[ fi ];
  10834. if ( uv2 === undefined ) continue;
  10835. for ( i = 0; i < 3; i ++ ) {
  10836. uv2i = uv2[ i ];
  10837. uv2Array[ offset_uv2 ] = uv2i.u;
  10838. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10839. offset_uv2 += 2;
  10840. }
  10841. }
  10842. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10843. fi = chunk_faces4[ f ];
  10844. uv2 = obj_uvs2[ fi ];
  10845. if ( uv2 === undefined ) continue;
  10846. for ( i = 0; i < 4; i ++ ) {
  10847. uv2i = uv2[ i ];
  10848. uv2Array[ offset_uv2 ] = uv2i.u;
  10849. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10850. offset_uv2 += 2;
  10851. }
  10852. }
  10853. if ( offset_uv2 > 0 ) {
  10854. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  10855. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  10856. }
  10857. }
  10858. if ( dirtyElements ) {
  10859. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10860. faceArray[ offset_face ] = vertexIndex;
  10861. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10862. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  10863. offset_face += 3;
  10864. lineArray[ offset_line ] = vertexIndex;
  10865. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10866. lineArray[ offset_line + 2 ] = vertexIndex;
  10867. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  10868. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10869. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10870. offset_line += 6;
  10871. vertexIndex += 3;
  10872. }
  10873. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10874. faceArray[ offset_face ] = vertexIndex;
  10875. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10876. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  10877. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  10878. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  10879. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  10880. offset_face += 6;
  10881. lineArray[ offset_line ] = vertexIndex;
  10882. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10883. lineArray[ offset_line + 2 ] = vertexIndex;
  10884. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  10885. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10886. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10887. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  10888. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  10889. offset_line += 8;
  10890. vertexIndex += 4;
  10891. }
  10892. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  10893. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  10894. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  10895. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  10896. }
  10897. if ( customAttributes ) {
  10898. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10899. customAttribute = customAttributes[ i ];
  10900. if ( ! customAttribute.__original.needsUpdate ) continue;
  10901. offset_custom = 0;
  10902. offset_customSrc = 0;
  10903. if ( customAttribute.size === 1 ) {
  10904. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10905. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10906. face = obj_faces[ chunk_faces3[ f ] ];
  10907. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10908. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10909. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10910. offset_custom += 3;
  10911. }
  10912. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10913. face = obj_faces[ chunk_faces4[ f ] ];
  10914. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10915. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10916. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10917. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  10918. offset_custom += 4;
  10919. }
  10920. } else if ( customAttribute.boundTo === "faces" ) {
  10921. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10922. value = customAttribute.value[ chunk_faces3[ f ] ];
  10923. customAttribute.array[ offset_custom ] = value;
  10924. customAttribute.array[ offset_custom + 1 ] = value;
  10925. customAttribute.array[ offset_custom + 2 ] = value;
  10926. offset_custom += 3;
  10927. }
  10928. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10929. value = customAttribute.value[ chunk_faces4[ f ] ];
  10930. customAttribute.array[ offset_custom ] = value;
  10931. customAttribute.array[ offset_custom + 1 ] = value;
  10932. customAttribute.array[ offset_custom + 2 ] = value;
  10933. customAttribute.array[ offset_custom + 3 ] = value;
  10934. offset_custom += 4;
  10935. }
  10936. }
  10937. } else if ( customAttribute.size === 2 ) {
  10938. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10939. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10940. face = obj_faces[ chunk_faces3[ f ] ];
  10941. v1 = customAttribute.value[ face.a ];
  10942. v2 = customAttribute.value[ face.b ];
  10943. v3 = customAttribute.value[ face.c ];
  10944. customAttribute.array[ offset_custom ] = v1.x;
  10945. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10946. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10947. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10948. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10949. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10950. offset_custom += 6;
  10951. }
  10952. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10953. face = obj_faces[ chunk_faces4[ f ] ];
  10954. v1 = customAttribute.value[ face.a ];
  10955. v2 = customAttribute.value[ face.b ];
  10956. v3 = customAttribute.value[ face.c ];
  10957. v4 = customAttribute.value[ face.d ];
  10958. customAttribute.array[ offset_custom ] = v1.x;
  10959. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10960. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10961. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10962. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10963. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10964. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10965. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10966. offset_custom += 8;
  10967. }
  10968. } else if ( customAttribute.boundTo === "faces" ) {
  10969. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10970. value = customAttribute.value[ chunk_faces3[ f ] ];
  10971. v1 = value;
  10972. v2 = value;
  10973. v3 = value;
  10974. customAttribute.array[ offset_custom ] = v1.x;
  10975. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10976. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10977. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10978. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10979. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10980. offset_custom += 6;
  10981. }
  10982. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10983. value = customAttribute.value[ chunk_faces4[ f ] ];
  10984. v1 = value;
  10985. v2 = value;
  10986. v3 = value;
  10987. v4 = value;
  10988. customAttribute.array[ offset_custom ] = v1.x;
  10989. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10990. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10991. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10992. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10993. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10994. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10995. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10996. offset_custom += 8;
  10997. }
  10998. }
  10999. } else if ( customAttribute.size === 3 ) {
  11000. var pp;
  11001. if ( customAttribute.type === "c" ) {
  11002. pp = [ "r", "g", "b" ];
  11003. } else {
  11004. pp = [ "x", "y", "z" ];
  11005. }
  11006. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11007. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11008. face = obj_faces[ chunk_faces3[ f ] ];
  11009. v1 = customAttribute.value[ face.a ];
  11010. v2 = customAttribute.value[ face.b ];
  11011. v3 = customAttribute.value[ face.c ];
  11012. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11013. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11014. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11015. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11016. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11017. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11018. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11019. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11020. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11021. offset_custom += 9;
  11022. }
  11023. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11024. face = obj_faces[ chunk_faces4[ f ] ];
  11025. v1 = customAttribute.value[ face.a ];
  11026. v2 = customAttribute.value[ face.b ];
  11027. v3 = customAttribute.value[ face.c ];
  11028. v4 = customAttribute.value[ face.d ];
  11029. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11030. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11031. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11032. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11033. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11034. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11035. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11036. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11037. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11038. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11039. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11040. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11041. offset_custom += 12;
  11042. }
  11043. } else if ( customAttribute.boundTo === "faces" ) {
  11044. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11045. value = customAttribute.value[ chunk_faces3[ f ] ];
  11046. v1 = value;
  11047. v2 = value;
  11048. v3 = value;
  11049. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11050. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11051. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11052. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11053. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11054. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11055. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11056. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11057. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11058. offset_custom += 9;
  11059. }
  11060. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11061. value = customAttribute.value[ chunk_faces4[ f ] ];
  11062. v1 = value;
  11063. v2 = value;
  11064. v3 = value;
  11065. v4 = value;
  11066. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11067. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11068. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11069. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11070. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11071. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11072. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11073. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11074. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11075. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11076. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11077. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11078. offset_custom += 12;
  11079. }
  11080. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11081. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11082. value = customAttribute.value[ chunk_faces3[ f ] ];
  11083. v1 = value[ 0 ];
  11084. v2 = value[ 1 ];
  11085. v3 = value[ 2 ];
  11086. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11087. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11088. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11089. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11090. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11091. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11092. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11093. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11094. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11095. offset_custom += 9;
  11096. }
  11097. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11098. value = customAttribute.value[ chunk_faces4[ f ] ];
  11099. v1 = value[ 0 ];
  11100. v2 = value[ 1 ];
  11101. v3 = value[ 2 ];
  11102. v4 = value[ 3 ];
  11103. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11104. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11105. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11106. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11107. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11108. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11109. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11110. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11111. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11112. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11113. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11114. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11115. offset_custom += 12;
  11116. }
  11117. }
  11118. } else if ( customAttribute.size === 4 ) {
  11119. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11120. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11121. face = obj_faces[ chunk_faces3[ f ] ];
  11122. v1 = customAttribute.value[ face.a ];
  11123. v2 = customAttribute.value[ face.b ];
  11124. v3 = customAttribute.value[ face.c ];
  11125. customAttribute.array[ offset_custom ] = v1.x;
  11126. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11127. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11128. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11129. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11130. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11131. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11132. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11133. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11134. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11135. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11136. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11137. offset_custom += 12;
  11138. }
  11139. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11140. face = obj_faces[ chunk_faces4[ f ] ];
  11141. v1 = customAttribute.value[ face.a ];
  11142. v2 = customAttribute.value[ face.b ];
  11143. v3 = customAttribute.value[ face.c ];
  11144. v4 = customAttribute.value[ face.d ];
  11145. customAttribute.array[ offset_custom ] = v1.x;
  11146. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11147. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11148. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11149. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11150. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11151. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11152. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11153. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11154. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11155. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11156. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11157. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11158. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11159. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11160. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11161. offset_custom += 16;
  11162. }
  11163. } else if ( customAttribute.boundTo === "faces" ) {
  11164. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11165. value = customAttribute.value[ chunk_faces3[ f ] ];
  11166. v1 = value;
  11167. v2 = value;
  11168. v3 = value;
  11169. customAttribute.array[ offset_custom ] = v1.x;
  11170. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11171. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11172. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11173. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11174. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11175. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11176. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11177. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11178. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11179. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11180. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11181. offset_custom += 12;
  11182. }
  11183. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11184. value = customAttribute.value[ chunk_faces4[ f ] ];
  11185. v1 = value;
  11186. v2 = value;
  11187. v3 = value;
  11188. v4 = value;
  11189. customAttribute.array[ offset_custom ] = v1.x;
  11190. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11191. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11192. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11193. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11194. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11195. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11196. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11197. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11198. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11199. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11200. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11201. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11202. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11203. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11204. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11205. offset_custom += 16;
  11206. }
  11207. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11208. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11209. value = customAttribute.value[ chunk_faces3[ f ] ];
  11210. v1 = value[ 0 ];
  11211. v2 = value[ 1 ];
  11212. v3 = value[ 2 ];
  11213. customAttribute.array[ offset_custom ] = v1.x;
  11214. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11215. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11216. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11217. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11218. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11219. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11220. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11221. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11222. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11223. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11224. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11225. offset_custom += 12;
  11226. }
  11227. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11228. value = customAttribute.value[ chunk_faces4[ f ] ];
  11229. v1 = value[ 0 ];
  11230. v2 = value[ 1 ];
  11231. v3 = value[ 2 ];
  11232. v4 = value[ 3 ];
  11233. customAttribute.array[ offset_custom ] = v1.x;
  11234. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11235. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11236. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11237. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11238. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11239. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11240. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11241. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11242. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11243. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11244. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11245. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11246. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11247. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11248. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11249. offset_custom += 16;
  11250. }
  11251. }
  11252. }
  11253. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11254. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11255. }
  11256. }
  11257. if ( dispose ) {
  11258. delete geometryGroup.__inittedArrays;
  11259. delete geometryGroup.__colorArray;
  11260. delete geometryGroup.__normalArray;
  11261. delete geometryGroup.__tangentArray;
  11262. delete geometryGroup.__uvArray;
  11263. delete geometryGroup.__uv2Array;
  11264. delete geometryGroup.__faceArray;
  11265. delete geometryGroup.__vertexArray;
  11266. delete geometryGroup.__lineArray;
  11267. delete geometryGroup.__skinIndexArray;
  11268. delete geometryGroup.__skinWeightArray;
  11269. }
  11270. };
  11271. function setDirectBuffers ( geometry, hint, dispose ) {
  11272. var attributes = geometry.attributes;
  11273. var index = attributes[ "index" ];
  11274. var position = attributes[ "position" ];
  11275. var normal = attributes[ "normal" ];
  11276. var uv = attributes[ "uv" ];
  11277. var color = attributes[ "color" ];
  11278. var tangent = attributes[ "tangent" ];
  11279. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  11280. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11281. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  11282. }
  11283. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  11284. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11285. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  11286. }
  11287. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  11288. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11289. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  11290. }
  11291. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  11292. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11293. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  11294. }
  11295. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  11296. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11297. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  11298. }
  11299. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  11300. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11301. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  11302. }
  11303. if ( dispose ) {
  11304. for ( var i in geometry.attributes ) {
  11305. delete geometry.attributes[ i ].array;
  11306. }
  11307. }
  11308. };
  11309. // Buffer rendering
  11310. this.renderBufferImmediate = function ( object, program, material ) {
  11311. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  11312. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  11313. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  11314. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  11315. if ( object.hasPositions ) {
  11316. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  11317. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11318. _gl.enableVertexAttribArray( program.attributes.position );
  11319. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11320. }
  11321. if ( object.hasNormals ) {
  11322. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  11323. if ( material.shading === THREE.FlatShading ) {
  11324. var nx, ny, nz,
  11325. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  11326. normalArray,
  11327. i, il = object.count * 3;
  11328. for( i = 0; i < il; i += 9 ) {
  11329. normalArray = object.normalArray;
  11330. nax = normalArray[ i ];
  11331. nay = normalArray[ i + 1 ];
  11332. naz = normalArray[ i + 2 ];
  11333. nbx = normalArray[ i + 3 ];
  11334. nby = normalArray[ i + 4 ];
  11335. nbz = normalArray[ i + 5 ];
  11336. ncx = normalArray[ i + 6 ];
  11337. ncy = normalArray[ i + 7 ];
  11338. ncz = normalArray[ i + 8 ];
  11339. nx = ( nax + nbx + ncx ) / 3;
  11340. ny = ( nay + nby + ncy ) / 3;
  11341. nz = ( naz + nbz + ncz ) / 3;
  11342. normalArray[ i ] = nx;
  11343. normalArray[ i + 1 ] = ny;
  11344. normalArray[ i + 2 ] = nz;
  11345. normalArray[ i + 3 ] = nx;
  11346. normalArray[ i + 4 ] = ny;
  11347. normalArray[ i + 5 ] = nz;
  11348. normalArray[ i + 6 ] = nx;
  11349. normalArray[ i + 7 ] = ny;
  11350. normalArray[ i + 8 ] = nz;
  11351. }
  11352. }
  11353. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11354. _gl.enableVertexAttribArray( program.attributes.normal );
  11355. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11356. }
  11357. if ( object.hasUvs && material.map ) {
  11358. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  11359. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11360. _gl.enableVertexAttribArray( program.attributes.uv );
  11361. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11362. }
  11363. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  11364. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  11365. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11366. _gl.enableVertexAttribArray( program.attributes.color );
  11367. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11368. }
  11369. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11370. object.count = 0;
  11371. };
  11372. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  11373. if ( material.visible === false ) return;
  11374. var program, attributes, linewidth, primitives, a, attribute;
  11375. program = setProgram( camera, lights, fog, material, object );
  11376. attributes = program.attributes;
  11377. var updateBuffers = false,
  11378. wireframeBit = material.wireframe ? 1 : 0,
  11379. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11380. if ( geometryHash !== _currentGeometryGroupHash ) {
  11381. _currentGeometryGroupHash = geometryHash;
  11382. updateBuffers = true;
  11383. }
  11384. if ( updateBuffers ) {
  11385. disableAttributes();
  11386. }
  11387. // render mesh
  11388. if ( object instanceof THREE.Mesh ) {
  11389. var offsets = geometry.offsets;
  11390. // if there is more than 1 chunk
  11391. // must set attribute pointers to use new offsets for each chunk
  11392. // even if geometry and materials didn't change
  11393. if ( offsets.length > 1 ) updateBuffers = true;
  11394. for ( var i = 0, il = offsets.length; i < il; ++ i ) {
  11395. var startIndex = offsets[ i ].index;
  11396. if ( updateBuffers ) {
  11397. // vertices
  11398. var position = geometry.attributes[ "position" ];
  11399. var positionSize = position.itemSize;
  11400. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11401. enableAttribute( attributes.position );
  11402. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  11403. // normals
  11404. var normal = geometry.attributes[ "normal" ];
  11405. if ( attributes.normal >= 0 && normal ) {
  11406. var normalSize = normal.itemSize;
  11407. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11408. enableAttribute( attributes.normal );
  11409. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  11410. }
  11411. // uvs
  11412. var uv = geometry.attributes[ "uv" ];
  11413. if ( attributes.uv >= 0 && uv ) {
  11414. var uvSize = uv.itemSize;
  11415. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11416. enableAttribute( attributes.uv );
  11417. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  11418. }
  11419. // colors
  11420. var color = geometry.attributes[ "color" ];
  11421. if ( attributes.color >= 0 && color ) {
  11422. var colorSize = color.itemSize;
  11423. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11424. enableAttribute( attributes.color );
  11425. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  11426. }
  11427. // tangents
  11428. var tangent = geometry.attributes[ "tangent" ];
  11429. if ( attributes.tangent >= 0 && tangent ) {
  11430. var tangentSize = tangent.itemSize;
  11431. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11432. enableAttribute( attributes.tangent );
  11433. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  11434. }
  11435. // indices
  11436. var index = geometry.attributes[ "index" ];
  11437. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11438. }
  11439. // render indexed triangles
  11440. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  11441. _this.info.render.calls ++;
  11442. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  11443. _this.info.render.faces += offsets[ i ].count / 3;
  11444. }
  11445. // render particles
  11446. } else if ( object instanceof THREE.ParticleSystem ) {
  11447. if ( updateBuffers ) {
  11448. // vertices
  11449. var position = geometry.attributes[ "position" ];
  11450. var positionSize = position.itemSize;
  11451. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11452. enableAttribute( attributes.position );
  11453. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  11454. // colors
  11455. var color = geometry.attributes[ "color" ];
  11456. if ( attributes.color >= 0 && color ) {
  11457. var colorSize = color.itemSize;
  11458. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11459. enableAttribute( attributes.color );
  11460. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  11461. }
  11462. // render particles
  11463. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  11464. _this.info.render.calls ++;
  11465. _this.info.render.points += position.numItems / 3;
  11466. }
  11467. }
  11468. };
  11469. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  11470. if ( material.visible === false ) return;
  11471. var program, attributes, linewidth, primitives, a, attribute, i, il;
  11472. program = setProgram( camera, lights, fog, material, object );
  11473. attributes = program.attributes;
  11474. var updateBuffers = false,
  11475. wireframeBit = material.wireframe ? 1 : 0,
  11476. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11477. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  11478. _currentGeometryGroupHash = geometryGroupHash;
  11479. updateBuffers = true;
  11480. }
  11481. if ( updateBuffers ) {
  11482. disableAttributes();
  11483. }
  11484. // vertices
  11485. if ( !material.morphTargets && attributes.position >= 0 ) {
  11486. if ( updateBuffers ) {
  11487. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11488. enableAttribute( attributes.position );
  11489. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11490. }
  11491. } else {
  11492. if ( object.morphTargetBase ) {
  11493. setupMorphTargets( material, geometryGroup, object );
  11494. }
  11495. }
  11496. if ( updateBuffers ) {
  11497. // custom attributes
  11498. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  11499. if ( geometryGroup.__webglCustomAttributesList ) {
  11500. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  11501. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  11502. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  11503. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  11504. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  11505. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  11506. }
  11507. }
  11508. }
  11509. // colors
  11510. if ( attributes.color >= 0 ) {
  11511. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11512. enableAttribute( attributes.color );
  11513. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11514. }
  11515. // normals
  11516. if ( attributes.normal >= 0 ) {
  11517. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11518. enableAttribute( attributes.normal );
  11519. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11520. }
  11521. // tangents
  11522. if ( attributes.tangent >= 0 ) {
  11523. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11524. enableAttribute( attributes.tangent );
  11525. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  11526. }
  11527. // uvs
  11528. if ( attributes.uv >= 0 ) {
  11529. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11530. enableAttribute( attributes.uv );
  11531. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11532. }
  11533. if ( attributes.uv2 >= 0 ) {
  11534. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11535. enableAttribute( attributes.uv2 );
  11536. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  11537. }
  11538. if ( material.skinning &&
  11539. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  11540. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11541. enableAttribute( attributes.skinIndex );
  11542. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  11543. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11544. enableAttribute( attributes.skinWeight );
  11545. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  11546. }
  11547. // line distances
  11548. if ( attributes.lineDistance >= 0 ) {
  11549. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  11550. enableAttribute( attributes.lineDistance );
  11551. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  11552. }
  11553. }
  11554. // render mesh
  11555. if ( object instanceof THREE.Mesh ) {
  11556. // wireframe
  11557. if ( material.wireframe ) {
  11558. setLineWidth( material.wireframeLinewidth );
  11559. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11560. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  11561. // triangles
  11562. } else {
  11563. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11564. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  11565. }
  11566. _this.info.render.calls ++;
  11567. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  11568. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  11569. // render lines
  11570. } else if ( object instanceof THREE.Line ) {
  11571. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  11572. setLineWidth( material.linewidth );
  11573. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  11574. _this.info.render.calls ++;
  11575. // render particles
  11576. } else if ( object instanceof THREE.ParticleSystem ) {
  11577. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  11578. _this.info.render.calls ++;
  11579. _this.info.render.points += geometryGroup.__webglParticleCount;
  11580. // render ribbon
  11581. } else if ( object instanceof THREE.Ribbon ) {
  11582. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  11583. _this.info.render.calls ++;
  11584. }
  11585. };
  11586. function enableAttribute( attribute ) {
  11587. if ( ! _enabledAttributes[ attribute ] ) {
  11588. _gl.enableVertexAttribArray( attribute );
  11589. _enabledAttributes[ attribute ] = true;
  11590. }
  11591. };
  11592. function disableAttributes() {
  11593. for ( var attribute in _enabledAttributes ) {
  11594. if ( _enabledAttributes[ attribute ] ) {
  11595. _gl.disableVertexAttribArray( attribute );
  11596. _enabledAttributes[ attribute ] = false;
  11597. }
  11598. }
  11599. };
  11600. function setupMorphTargets ( material, geometryGroup, object ) {
  11601. // set base
  11602. var attributes = material.program.attributes;
  11603. if ( object.morphTargetBase !== -1 ) {
  11604. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  11605. enableAttribute( attributes.position );
  11606. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11607. } else if ( attributes.position >= 0 ) {
  11608. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11609. enableAttribute( attributes.position );
  11610. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11611. }
  11612. if ( object.morphTargetForcedOrder.length ) {
  11613. // set forced order
  11614. var m = 0;
  11615. var order = object.morphTargetForcedOrder;
  11616. var influences = object.morphTargetInfluences;
  11617. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  11618. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  11619. enableAttribute( attributes[ "morphTarget" + m ] );
  11620. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11621. if ( material.morphNormals ) {
  11622. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  11623. enableAttribute( attributes[ "morphNormal" + m ] );
  11624. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11625. }
  11626. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  11627. m ++;
  11628. }
  11629. } else {
  11630. // find the most influencing
  11631. var influence, activeInfluenceIndices = [];
  11632. var influences = object.morphTargetInfluences;
  11633. var i, il = influences.length;
  11634. for ( i = 0; i < il; i ++ ) {
  11635. influence = influences[ i ];
  11636. if ( influence > 0 ) {
  11637. activeInfluenceIndices.push( [ i, influence ] );
  11638. }
  11639. }
  11640. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  11641. activeInfluenceIndices.sort( numericalSort );
  11642. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  11643. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  11644. activeInfluenceIndices.sort( numericalSort );
  11645. } else if ( activeInfluenceIndices.length === 0 ) {
  11646. activeInfluenceIndices.push( [ 0, 0 ] );
  11647. };
  11648. var influenceIndex, m = 0;
  11649. while ( m < material.numSupportedMorphTargets ) {
  11650. if ( activeInfluenceIndices[ m ] ) {
  11651. influenceIndex = activeInfluenceIndices[ m ][ 0 ];
  11652. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  11653. enableAttribute( attributes[ "morphTarget" + m ] );
  11654. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11655. if ( material.morphNormals ) {
  11656. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  11657. enableAttribute( attributes[ "morphNormal" + m ] );
  11658. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11659. }
  11660. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  11661. } else {
  11662. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11663. if ( material.morphNormals ) {
  11664. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11665. }
  11666. object.__webglMorphTargetInfluences[ m ] = 0;
  11667. }
  11668. m ++;
  11669. }
  11670. }
  11671. // load updated influences uniform
  11672. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  11673. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  11674. }
  11675. };
  11676. // Sorting
  11677. function painterSortStable ( a, b ) {
  11678. if ( a.z !== b.z ) {
  11679. return b.z - a.z;
  11680. } else {
  11681. return b.id - a.id;
  11682. }
  11683. };
  11684. function numericalSort ( a, b ) {
  11685. return b[ 1 ] - a[ 1 ];
  11686. };
  11687. // Rendering
  11688. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11689. if ( camera instanceof THREE.Camera === false ) {
  11690. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  11691. return;
  11692. }
  11693. var i, il,
  11694. webglObject, object,
  11695. renderList,
  11696. lights = scene.__lights,
  11697. fog = scene.fog;
  11698. // reset caching for this frame
  11699. _currentMaterialId = -1;
  11700. _lightsNeedUpdate = true;
  11701. // update scene graph
  11702. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  11703. // update camera matrices and frustum
  11704. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  11705. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  11706. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  11707. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11708. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  11709. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  11710. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  11711. _frustum.setFromMatrix( _projScreenMatrix );
  11712. // update WebGL objects
  11713. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  11714. // custom render plugins (pre pass)
  11715. renderPlugins( this.renderPluginsPre, scene, camera );
  11716. //
  11717. _this.info.render.calls = 0;
  11718. _this.info.render.vertices = 0;
  11719. _this.info.render.faces = 0;
  11720. _this.info.render.points = 0;
  11721. this.setRenderTarget( renderTarget );
  11722. if ( this.autoClear || forceClear ) {
  11723. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  11724. }
  11725. // set matrices for regular objects (frustum culled)
  11726. renderList = scene.__webglObjects;
  11727. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11728. webglObject = renderList[ i ];
  11729. object = webglObject.object;
  11730. webglObject.render = false;
  11731. if ( object.visible ) {
  11732. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  11733. //object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11734. setupMatrices( object, camera );
  11735. unrollBufferMaterial( webglObject );
  11736. webglObject.render = true;
  11737. if ( this.sortObjects === true ) {
  11738. if ( object.renderDepth !== null ) {
  11739. webglObject.z = object.renderDepth;
  11740. } else {
  11741. _vector3.copy( object.matrixWorld.getPosition() );
  11742. _projScreenMatrix.multiplyVector3( _vector3 );
  11743. webglObject.z = _vector3.z;
  11744. }
  11745. webglObject.id = object.id;
  11746. }
  11747. }
  11748. }
  11749. }
  11750. if ( this.sortObjects ) {
  11751. renderList.sort( painterSortStable );
  11752. }
  11753. // set matrices for immediate objects
  11754. renderList = scene.__webglObjectsImmediate;
  11755. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11756. webglObject = renderList[ i ];
  11757. object = webglObject.object;
  11758. if ( object.visible ) {
  11759. /*
  11760. if ( object.matrixAutoUpdate ) {
  11761. object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11762. }
  11763. */
  11764. setupMatrices( object, camera );
  11765. unrollImmediateBufferMaterial( webglObject );
  11766. }
  11767. }
  11768. if ( scene.overrideMaterial ) {
  11769. var material = scene.overrideMaterial;
  11770. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11771. this.setDepthTest( material.depthTest );
  11772. this.setDepthWrite( material.depthWrite );
  11773. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11774. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  11775. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  11776. } else {
  11777. // opaque pass (front-to-back order)
  11778. this.setBlending( THREE.NormalBlending );
  11779. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false );
  11780. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false );
  11781. // transparent pass (back-to-front order)
  11782. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true );
  11783. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true );
  11784. }
  11785. // custom render plugins (post pass)
  11786. renderPlugins( this.renderPluginsPost, scene, camera );
  11787. // Generate mipmap if we're using any kind of mipmap filtering
  11788. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  11789. updateRenderTargetMipmap( renderTarget );
  11790. }
  11791. // Ensure depth buffer writing is enabled so it can be cleared on next render
  11792. this.setDepthTest( true );
  11793. this.setDepthWrite( true );
  11794. // _gl.finish();
  11795. };
  11796. function renderPlugins( plugins, scene, camera ) {
  11797. if ( ! plugins.length ) return;
  11798. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  11799. // reset state for plugin (to start from clean slate)
  11800. _currentProgram = null;
  11801. _currentCamera = null;
  11802. _oldBlending = -1;
  11803. _oldDepthTest = -1;
  11804. _oldDepthWrite = -1;
  11805. _oldDoubleSided = -1;
  11806. _oldFlipSided = -1;
  11807. _currentGeometryGroupHash = -1;
  11808. _currentMaterialId = -1;
  11809. _lightsNeedUpdate = true;
  11810. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  11811. // reset state after plugin (anything could have changed)
  11812. _currentProgram = null;
  11813. _currentCamera = null;
  11814. _oldBlending = -1;
  11815. _oldDepthTest = -1;
  11816. _oldDepthWrite = -1;
  11817. _oldDoubleSided = -1;
  11818. _oldFlipSided = -1;
  11819. _currentGeometryGroupHash = -1;
  11820. _currentMaterialId = -1;
  11821. _lightsNeedUpdate = true;
  11822. }
  11823. };
  11824. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11825. var webglObject, object, buffer, material, start, end, delta;
  11826. if ( reverse ) {
  11827. start = renderList.length - 1;
  11828. end = -1;
  11829. delta = -1;
  11830. } else {
  11831. start = 0;
  11832. end = renderList.length;
  11833. delta = 1;
  11834. }
  11835. for ( var i = start; i !== end; i += delta ) {
  11836. webglObject = renderList[ i ];
  11837. if ( webglObject.render ) {
  11838. object = webglObject.object;
  11839. buffer = webglObject.buffer;
  11840. if ( overrideMaterial ) {
  11841. material = overrideMaterial;
  11842. } else {
  11843. material = webglObject[ materialType ];
  11844. if ( ! material ) continue;
  11845. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11846. _this.setDepthTest( material.depthTest );
  11847. _this.setDepthWrite( material.depthWrite );
  11848. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11849. }
  11850. _this.setMaterialFaces( material );
  11851. if ( buffer instanceof THREE.BufferGeometry ) {
  11852. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  11853. } else {
  11854. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  11855. }
  11856. }
  11857. }
  11858. };
  11859. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11860. var webglObject, object, material, program;
  11861. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  11862. webglObject = renderList[ i ];
  11863. object = webglObject.object;
  11864. if ( object.visible ) {
  11865. if ( overrideMaterial ) {
  11866. material = overrideMaterial;
  11867. } else {
  11868. material = webglObject[ materialType ];
  11869. if ( ! material ) continue;
  11870. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11871. _this.setDepthTest( material.depthTest );
  11872. _this.setDepthWrite( material.depthWrite );
  11873. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11874. }
  11875. _this.renderImmediateObject( camera, lights, fog, material, object );
  11876. }
  11877. }
  11878. };
  11879. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  11880. var program = setProgram( camera, lights, fog, material, object );
  11881. _currentGeometryGroupHash = -1;
  11882. _this.setMaterialFaces( material );
  11883. if ( object.immediateRenderCallback ) {
  11884. object.immediateRenderCallback( program, _gl, _frustum );
  11885. } else {
  11886. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  11887. }
  11888. };
  11889. function unrollImmediateBufferMaterial ( globject ) {
  11890. var object = globject.object,
  11891. material = object.material;
  11892. if ( material.transparent ) {
  11893. globject.transparent = material;
  11894. globject.opaque = null;
  11895. } else {
  11896. globject.opaque = material;
  11897. globject.transparent = null;
  11898. }
  11899. };
  11900. function unrollBufferMaterial ( globject ) {
  11901. var object = globject.object,
  11902. buffer = globject.buffer,
  11903. material, materialIndex, meshMaterial;
  11904. meshMaterial = object.material;
  11905. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  11906. materialIndex = buffer.materialIndex;
  11907. if ( materialIndex >= 0 ) {
  11908. material = meshMaterial.materials[ materialIndex ];
  11909. if ( material.transparent ) {
  11910. globject.transparent = material;
  11911. globject.opaque = null;
  11912. } else {
  11913. globject.opaque = material;
  11914. globject.transparent = null;
  11915. }
  11916. }
  11917. } else {
  11918. material = meshMaterial;
  11919. if ( material ) {
  11920. if ( material.transparent ) {
  11921. globject.transparent = material;
  11922. globject.opaque = null;
  11923. } else {
  11924. globject.opaque = material;
  11925. globject.transparent = null;
  11926. }
  11927. }
  11928. }
  11929. };
  11930. // Geometry splitting
  11931. function sortFacesByMaterial ( geometry, material ) {
  11932. var f, fl, face, materialIndex, vertices,
  11933. materialHash, groupHash,
  11934. hash_map = {};
  11935. var numMorphTargets = geometry.morphTargets.length;
  11936. var numMorphNormals = geometry.morphNormals.length;
  11937. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  11938. geometry.geometryGroups = {};
  11939. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  11940. face = geometry.faces[ f ];
  11941. materialIndex = usesFaceMaterial ? face.materialIndex : undefined;
  11942. materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;
  11943. if ( hash_map[ materialHash ] === undefined ) {
  11944. hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };
  11945. }
  11946. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11947. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11948. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11949. }
  11950. vertices = face instanceof THREE.Face3 ? 3 : 4;
  11951. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  11952. hash_map[ materialHash ].counter += 1;
  11953. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11954. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11955. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11956. }
  11957. }
  11958. if ( face instanceof THREE.Face3 ) {
  11959. geometry.geometryGroups[ groupHash ].faces3.push( f );
  11960. } else {
  11961. geometry.geometryGroups[ groupHash ].faces4.push( f );
  11962. }
  11963. geometry.geometryGroups[ groupHash ].vertices += vertices;
  11964. }
  11965. geometry.geometryGroupsList = [];
  11966. for ( var g in geometry.geometryGroups ) {
  11967. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  11968. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  11969. }
  11970. };
  11971. // Objects refresh
  11972. this.initWebGLObjects = function ( scene ) {
  11973. if ( !scene.__webglObjects ) {
  11974. scene.__webglObjects = [];
  11975. scene.__webglObjectsImmediate = [];
  11976. scene.__webglSprites = [];
  11977. scene.__webglFlares = [];
  11978. }
  11979. while ( scene.__objectsAdded.length ) {
  11980. addObject( scene.__objectsAdded[ 0 ], scene );
  11981. scene.__objectsAdded.splice( 0, 1 );
  11982. }
  11983. while ( scene.__objectsRemoved.length ) {
  11984. removeObject( scene.__objectsRemoved[ 0 ], scene );
  11985. scene.__objectsRemoved.splice( 0, 1 );
  11986. }
  11987. // update must be called after objects adding / removal
  11988. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  11989. updateObject( scene.__webglObjects[ o ].object );
  11990. }
  11991. };
  11992. // Objects adding
  11993. function addObject ( object, scene ) {
  11994. var g, geometry, material, geometryGroup;
  11995. if ( ! object.__webglInit ) {
  11996. object.__webglInit = true;
  11997. object._modelViewMatrix = new THREE.Matrix4();
  11998. object._normalMatrix = new THREE.Matrix3();
  11999. if ( object instanceof THREE.Mesh ) {
  12000. geometry = object.geometry;
  12001. material = object.material;
  12002. if ( geometry instanceof THREE.Geometry ) {
  12003. if ( geometry.geometryGroups === undefined ) {
  12004. sortFacesByMaterial( geometry, material );
  12005. }
  12006. // create separate VBOs per geometry chunk
  12007. for ( g in geometry.geometryGroups ) {
  12008. geometryGroup = geometry.geometryGroups[ g ];
  12009. // initialise VBO on the first access
  12010. if ( ! geometryGroup.__webglVertexBuffer ) {
  12011. createMeshBuffers( geometryGroup );
  12012. initMeshBuffers( geometryGroup, object );
  12013. geometry.verticesNeedUpdate = true;
  12014. geometry.morphTargetsNeedUpdate = true;
  12015. geometry.elementsNeedUpdate = true;
  12016. geometry.uvsNeedUpdate = true;
  12017. geometry.normalsNeedUpdate = true;
  12018. geometry.tangentsNeedUpdate = true;
  12019. geometry.colorsNeedUpdate = true;
  12020. }
  12021. }
  12022. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12023. initDirectBuffers( geometry );
  12024. }
  12025. } else if ( object instanceof THREE.Ribbon ) {
  12026. geometry = object.geometry;
  12027. if ( ! geometry.__webglVertexBuffer ) {
  12028. createRibbonBuffers( geometry );
  12029. initRibbonBuffers( geometry, object );
  12030. geometry.verticesNeedUpdate = true;
  12031. geometry.colorsNeedUpdate = true;
  12032. geometry.normalsNeedUpdate = true;
  12033. }
  12034. } else if ( object instanceof THREE.Line ) {
  12035. geometry = object.geometry;
  12036. if ( ! geometry.__webglVertexBuffer ) {
  12037. createLineBuffers( geometry );
  12038. initLineBuffers( geometry, object );
  12039. geometry.verticesNeedUpdate = true;
  12040. geometry.colorsNeedUpdate = true;
  12041. geometry.lineDistancesNeedUpdate = true;
  12042. }
  12043. } else if ( object instanceof THREE.ParticleSystem ) {
  12044. geometry = object.geometry;
  12045. if ( ! geometry.__webglVertexBuffer ) {
  12046. if ( geometry instanceof THREE.Geometry ) {
  12047. createParticleBuffers( geometry );
  12048. initParticleBuffers( geometry, object );
  12049. geometry.verticesNeedUpdate = true;
  12050. geometry.colorsNeedUpdate = true;
  12051. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12052. initDirectBuffers( geometry );
  12053. }
  12054. }
  12055. }
  12056. }
  12057. if ( ! object.__webglActive ) {
  12058. if ( object instanceof THREE.Mesh ) {
  12059. geometry = object.geometry;
  12060. if ( geometry instanceof THREE.BufferGeometry ) {
  12061. addBuffer( scene.__webglObjects, geometry, object );
  12062. } else {
  12063. for ( g in geometry.geometryGroups ) {
  12064. geometryGroup = geometry.geometryGroups[ g ];
  12065. addBuffer( scene.__webglObjects, geometryGroup, object );
  12066. }
  12067. }
  12068. } else if ( object instanceof THREE.Ribbon ||
  12069. object instanceof THREE.Line ||
  12070. object instanceof THREE.ParticleSystem ) {
  12071. geometry = object.geometry;
  12072. addBuffer( scene.__webglObjects, geometry, object );
  12073. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12074. addBufferImmediate( scene.__webglObjectsImmediate, object );
  12075. } else if ( object instanceof THREE.Sprite ) {
  12076. scene.__webglSprites.push( object );
  12077. } else if ( object instanceof THREE.LensFlare ) {
  12078. scene.__webglFlares.push( object );
  12079. }
  12080. object.__webglActive = true;
  12081. }
  12082. };
  12083. function addBuffer ( objlist, buffer, object ) {
  12084. objlist.push(
  12085. {
  12086. buffer: buffer,
  12087. object: object,
  12088. opaque: null,
  12089. transparent: null
  12090. }
  12091. );
  12092. };
  12093. function addBufferImmediate ( objlist, object ) {
  12094. objlist.push(
  12095. {
  12096. object: object,
  12097. opaque: null,
  12098. transparent: null
  12099. }
  12100. );
  12101. };
  12102. // Objects updates
  12103. function updateObject ( object ) {
  12104. var geometry = object.geometry,
  12105. geometryGroup, customAttributesDirty, material;
  12106. if ( object instanceof THREE.Mesh ) {
  12107. if ( geometry instanceof THREE.BufferGeometry ) {
  12108. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  12109. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12110. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  12111. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12112. }
  12113. geometry.verticesNeedUpdate = false;
  12114. geometry.elementsNeedUpdate = false;
  12115. geometry.uvsNeedUpdate = false;
  12116. geometry.normalsNeedUpdate = false;
  12117. geometry.colorsNeedUpdate = false;
  12118. geometry.tangentsNeedUpdate = false;
  12119. } else {
  12120. // check all geometry groups
  12121. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  12122. geometryGroup = geometry.geometryGroupsList[ i ];
  12123. material = getBufferMaterial( object, geometryGroup );
  12124. if ( geometry.buffersNeedUpdate ) {
  12125. initMeshBuffers( geometryGroup, object );
  12126. }
  12127. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12128. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  12129. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12130. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  12131. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  12132. }
  12133. }
  12134. geometry.verticesNeedUpdate = false;
  12135. geometry.morphTargetsNeedUpdate = false;
  12136. geometry.elementsNeedUpdate = false;
  12137. geometry.uvsNeedUpdate = false;
  12138. geometry.normalsNeedUpdate = false;
  12139. geometry.colorsNeedUpdate = false;
  12140. geometry.tangentsNeedUpdate = false;
  12141. geometry.buffersNeedUpdate = false;
  12142. material.attributes && clearCustomAttributes( material );
  12143. }
  12144. } else if ( object instanceof THREE.Ribbon ) {
  12145. material = getBufferMaterial( object, geometry );
  12146. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12147. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  12148. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  12149. }
  12150. geometry.verticesNeedUpdate = false;
  12151. geometry.colorsNeedUpdate = false;
  12152. geometry.normalsNeedUpdate = false;
  12153. material.attributes && clearCustomAttributes( material );
  12154. } else if ( object instanceof THREE.Line ) {
  12155. material = getBufferMaterial( object, geometry );
  12156. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12157. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  12158. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  12159. }
  12160. geometry.verticesNeedUpdate = false;
  12161. geometry.colorsNeedUpdate = false;
  12162. geometry.lineDistancesNeedUpdate = false;
  12163. material.attributes && clearCustomAttributes( material );
  12164. } else if ( object instanceof THREE.ParticleSystem ) {
  12165. if ( geometry instanceof THREE.BufferGeometry ) {
  12166. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  12167. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12168. }
  12169. geometry.verticesNeedUpdate = false;
  12170. geometry.colorsNeedUpdate = false;
  12171. } else {
  12172. material = getBufferMaterial( object, geometry );
  12173. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12174. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  12175. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  12176. }
  12177. geometry.verticesNeedUpdate = false;
  12178. geometry.colorsNeedUpdate = false;
  12179. material.attributes && clearCustomAttributes( material );
  12180. }
  12181. }
  12182. };
  12183. // Objects updates - custom attributes check
  12184. function areCustomAttributesDirty ( material ) {
  12185. for ( var a in material.attributes ) {
  12186. if ( material.attributes[ a ].needsUpdate ) return true;
  12187. }
  12188. return false;
  12189. };
  12190. function clearCustomAttributes ( material ) {
  12191. for ( var a in material.attributes ) {
  12192. material.attributes[ a ].needsUpdate = false;
  12193. }
  12194. };
  12195. // Objects removal
  12196. function removeObject ( object, scene ) {
  12197. if ( object instanceof THREE.Mesh ||
  12198. object instanceof THREE.ParticleSystem ||
  12199. object instanceof THREE.Ribbon ||
  12200. object instanceof THREE.Line ) {
  12201. removeInstances( scene.__webglObjects, object );
  12202. } else if ( object instanceof THREE.Sprite ) {
  12203. removeInstancesDirect( scene.__webglSprites, object );
  12204. } else if ( object instanceof THREE.LensFlare ) {
  12205. removeInstancesDirect( scene.__webglFlares, object );
  12206. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12207. removeInstances( scene.__webglObjectsImmediate, object );
  12208. }
  12209. object.__webglActive = false;
  12210. };
  12211. function removeInstances ( objlist, object ) {
  12212. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12213. if ( objlist[ o ].object === object ) {
  12214. objlist.splice( o, 1 );
  12215. }
  12216. }
  12217. };
  12218. function removeInstancesDirect ( objlist, object ) {
  12219. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12220. if ( objlist[ o ] === object ) {
  12221. objlist.splice( o, 1 );
  12222. }
  12223. }
  12224. };
  12225. // Materials
  12226. this.initMaterial = function ( material, lights, fog, object ) {
  12227. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  12228. if ( material instanceof THREE.MeshDepthMaterial ) {
  12229. shaderID = 'depth';
  12230. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12231. shaderID = 'normal';
  12232. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  12233. shaderID = 'basic';
  12234. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12235. shaderID = 'lambert';
  12236. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12237. shaderID = 'phong';
  12238. } else if ( material instanceof THREE.LineBasicMaterial ) {
  12239. shaderID = 'basic';
  12240. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12241. shaderID = 'dashed';
  12242. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12243. shaderID = 'particle_basic';
  12244. }
  12245. if ( shaderID ) {
  12246. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  12247. }
  12248. // heuristics to create shader parameters according to lights in the scene
  12249. // (not to blow over maxLights budget)
  12250. maxLightCount = allocateLights( lights );
  12251. maxShadows = allocateShadows( lights );
  12252. maxBones = allocateBones( object );
  12253. parameters = {
  12254. map: !!material.map,
  12255. envMap: !!material.envMap,
  12256. lightMap: !!material.lightMap,
  12257. bumpMap: !!material.bumpMap,
  12258. normalMap: !!material.normalMap,
  12259. specularMap: !!material.specularMap,
  12260. vertexColors: material.vertexColors,
  12261. fog: fog,
  12262. useFog: material.fog,
  12263. fogExp: fog instanceof THREE.FogExp2,
  12264. sizeAttenuation: material.sizeAttenuation,
  12265. skinning: material.skinning,
  12266. maxBones: maxBones,
  12267. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  12268. boneTextureWidth: object && object.boneTextureWidth,
  12269. boneTextureHeight: object && object.boneTextureHeight,
  12270. morphTargets: material.morphTargets,
  12271. morphNormals: material.morphNormals,
  12272. maxMorphTargets: this.maxMorphTargets,
  12273. maxMorphNormals: this.maxMorphNormals,
  12274. maxDirLights: maxLightCount.directional,
  12275. maxPointLights: maxLightCount.point,
  12276. maxSpotLights: maxLightCount.spot,
  12277. maxHemiLights: maxLightCount.hemi,
  12278. maxShadows: maxShadows,
  12279. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  12280. shadowMapSoft: this.shadowMapSoft,
  12281. shadowMapDebug: this.shadowMapDebug,
  12282. shadowMapCascade: this.shadowMapCascade,
  12283. alphaTest: material.alphaTest,
  12284. metal: material.metal,
  12285. perPixel: material.perPixel,
  12286. wrapAround: material.wrapAround,
  12287. doubleSided: material.side === THREE.DoubleSide,
  12288. flipSided: material.side === THREE.BackSide
  12289. };
  12290. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  12291. var attributes = material.program.attributes;
  12292. if ( material.morphTargets ) {
  12293. material.numSupportedMorphTargets = 0;
  12294. var id, base = "morphTarget";
  12295. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  12296. id = base + i;
  12297. if ( attributes[ id ] >= 0 ) {
  12298. material.numSupportedMorphTargets ++;
  12299. }
  12300. }
  12301. }
  12302. if ( material.morphNormals ) {
  12303. material.numSupportedMorphNormals = 0;
  12304. var id, base = "morphNormal";
  12305. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  12306. id = base + i;
  12307. if ( attributes[ id ] >= 0 ) {
  12308. material.numSupportedMorphNormals ++;
  12309. }
  12310. }
  12311. }
  12312. material.uniformsList = [];
  12313. for ( u in material.uniforms ) {
  12314. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  12315. }
  12316. };
  12317. function setMaterialShaders( material, shaders ) {
  12318. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  12319. material.vertexShader = shaders.vertexShader;
  12320. material.fragmentShader = shaders.fragmentShader;
  12321. };
  12322. function setProgram( camera, lights, fog, material, object ) {
  12323. _usedTextureUnits = 0;
  12324. if ( material.needsUpdate ) {
  12325. if ( material.program ) _this.deallocateMaterial( material );
  12326. _this.initMaterial( material, lights, fog, object );
  12327. material.needsUpdate = false;
  12328. }
  12329. if ( material.morphTargets ) {
  12330. if ( ! object.__webglMorphTargetInfluences ) {
  12331. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  12332. }
  12333. }
  12334. var refreshMaterial = false;
  12335. var program = material.program,
  12336. p_uniforms = program.uniforms,
  12337. m_uniforms = material.uniforms;
  12338. if ( program !== _currentProgram ) {
  12339. _gl.useProgram( program );
  12340. _currentProgram = program;
  12341. refreshMaterial = true;
  12342. }
  12343. if ( material.id !== _currentMaterialId ) {
  12344. _currentMaterialId = material.id;
  12345. refreshMaterial = true;
  12346. }
  12347. if ( refreshMaterial || camera !== _currentCamera ) {
  12348. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  12349. if ( camera !== _currentCamera ) _currentCamera = camera;
  12350. }
  12351. // skinning uniforms must be set even if material didn't change
  12352. // auto-setting of texture unit for bone texture must go before other textures
  12353. // not sure why, but otherwise weird things happen
  12354. if ( material.skinning ) {
  12355. if ( _supportsBoneTextures && object.useVertexTexture ) {
  12356. if ( p_uniforms.boneTexture !== null ) {
  12357. var textureUnit = getTextureUnit();
  12358. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  12359. _this.setTexture( object.boneTexture, textureUnit );
  12360. }
  12361. } else {
  12362. if ( p_uniforms.boneGlobalMatrices !== null ) {
  12363. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  12364. }
  12365. }
  12366. }
  12367. if ( refreshMaterial ) {
  12368. // refresh uniforms common to several materials
  12369. if ( fog && material.fog ) {
  12370. refreshUniformsFog( m_uniforms, fog );
  12371. }
  12372. if ( material instanceof THREE.MeshPhongMaterial ||
  12373. material instanceof THREE.MeshLambertMaterial ||
  12374. material.lights ) {
  12375. if ( _lightsNeedUpdate ) {
  12376. setupLights( program, lights );
  12377. _lightsNeedUpdate = false;
  12378. }
  12379. refreshUniformsLights( m_uniforms, _lights );
  12380. }
  12381. if ( material instanceof THREE.MeshBasicMaterial ||
  12382. material instanceof THREE.MeshLambertMaterial ||
  12383. material instanceof THREE.MeshPhongMaterial ) {
  12384. refreshUniformsCommon( m_uniforms, material );
  12385. }
  12386. // refresh single material specific uniforms
  12387. if ( material instanceof THREE.LineBasicMaterial ) {
  12388. refreshUniformsLine( m_uniforms, material );
  12389. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12390. refreshUniformsLine( m_uniforms, material );
  12391. refreshUniformsDash( m_uniforms, material );
  12392. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12393. refreshUniformsParticle( m_uniforms, material );
  12394. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12395. refreshUniformsPhong( m_uniforms, material );
  12396. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12397. refreshUniformsLambert( m_uniforms, material );
  12398. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  12399. m_uniforms.mNear.value = camera.near;
  12400. m_uniforms.mFar.value = camera.far;
  12401. m_uniforms.opacity.value = material.opacity;
  12402. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12403. m_uniforms.opacity.value = material.opacity;
  12404. }
  12405. if ( object.receiveShadow && ! material._shadowPass ) {
  12406. refreshUniformsShadow( m_uniforms, lights );
  12407. }
  12408. // load common uniforms
  12409. loadUniformsGeneric( program, material.uniformsList );
  12410. // load material specific uniforms
  12411. // (shader material also gets them for the sake of genericity)
  12412. if ( material instanceof THREE.ShaderMaterial ||
  12413. material instanceof THREE.MeshPhongMaterial ||
  12414. material.envMap ) {
  12415. if ( p_uniforms.cameraPosition !== null ) {
  12416. var position = camera.matrixWorld.getPosition();
  12417. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  12418. }
  12419. }
  12420. if ( material instanceof THREE.MeshPhongMaterial ||
  12421. material instanceof THREE.MeshLambertMaterial ||
  12422. material instanceof THREE.ShaderMaterial ||
  12423. material.skinning ) {
  12424. if ( p_uniforms.viewMatrix !== null ) {
  12425. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray );
  12426. }
  12427. }
  12428. }
  12429. loadUniformsMatrices( p_uniforms, object );
  12430. if ( p_uniforms.modelMatrix !== null ) {
  12431. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  12432. }
  12433. return program;
  12434. };
  12435. // Uniforms (refresh uniforms objects)
  12436. function refreshUniformsCommon ( uniforms, material ) {
  12437. uniforms.opacity.value = material.opacity;
  12438. if ( _this.gammaInput ) {
  12439. uniforms.diffuse.value.copyGammaToLinear( material.color );
  12440. } else {
  12441. uniforms.diffuse.value = material.color;
  12442. }
  12443. uniforms.map.value = material.map;
  12444. uniforms.lightMap.value = material.lightMap;
  12445. uniforms.specularMap.value = material.specularMap;
  12446. if ( material.bumpMap ) {
  12447. uniforms.bumpMap.value = material.bumpMap;
  12448. uniforms.bumpScale.value = material.bumpScale;
  12449. }
  12450. if ( material.normalMap ) {
  12451. uniforms.normalMap.value = material.normalMap;
  12452. uniforms.normalScale.value.copy( material.normalScale );
  12453. }
  12454. // uv repeat and offset setting priorities
  12455. // 1. color map
  12456. // 2. specular map
  12457. // 3. normal map
  12458. // 4. bump map
  12459. var uvScaleMap;
  12460. if ( material.map ) {
  12461. uvScaleMap = material.map;
  12462. } else if ( material.specularMap ) {
  12463. uvScaleMap = material.specularMap;
  12464. } else if ( material.normalMap ) {
  12465. uvScaleMap = material.normalMap;
  12466. } else if ( material.bumpMap ) {
  12467. uvScaleMap = material.bumpMap;
  12468. }
  12469. if ( uvScaleMap !== undefined ) {
  12470. var offset = uvScaleMap.offset;
  12471. var repeat = uvScaleMap.repeat;
  12472. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12473. }
  12474. uniforms.envMap.value = material.envMap;
  12475. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  12476. if ( _this.gammaInput ) {
  12477. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  12478. uniforms.reflectivity.value = material.reflectivity;
  12479. } else {
  12480. uniforms.reflectivity.value = material.reflectivity;
  12481. }
  12482. uniforms.refractionRatio.value = material.refractionRatio;
  12483. uniforms.combine.value = material.combine;
  12484. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  12485. };
  12486. function refreshUniformsLine ( uniforms, material ) {
  12487. uniforms.diffuse.value = material.color;
  12488. uniforms.opacity.value = material.opacity;
  12489. };
  12490. function refreshUniformsDash ( uniforms, material ) {
  12491. uniforms.dashSize.value = material.dashSize;
  12492. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12493. uniforms.scale.value = material.scale;
  12494. };
  12495. function refreshUniformsParticle ( uniforms, material ) {
  12496. uniforms.psColor.value = material.color;
  12497. uniforms.opacity.value = material.opacity;
  12498. uniforms.size.value = material.size;
  12499. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  12500. uniforms.map.value = material.map;
  12501. };
  12502. function refreshUniformsFog ( uniforms, fog ) {
  12503. uniforms.fogColor.value = fog.color;
  12504. if ( fog instanceof THREE.Fog ) {
  12505. uniforms.fogNear.value = fog.near;
  12506. uniforms.fogFar.value = fog.far;
  12507. } else if ( fog instanceof THREE.FogExp2 ) {
  12508. uniforms.fogDensity.value = fog.density;
  12509. }
  12510. };
  12511. function refreshUniformsPhong ( uniforms, material ) {
  12512. uniforms.shininess.value = material.shininess;
  12513. if ( _this.gammaInput ) {
  12514. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12515. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12516. uniforms.specular.value.copyGammaToLinear( material.specular );
  12517. } else {
  12518. uniforms.ambient.value = material.ambient;
  12519. uniforms.emissive.value = material.emissive;
  12520. uniforms.specular.value = material.specular;
  12521. }
  12522. if ( material.wrapAround ) {
  12523. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12524. }
  12525. };
  12526. function refreshUniformsLambert ( uniforms, material ) {
  12527. if ( _this.gammaInput ) {
  12528. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12529. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12530. } else {
  12531. uniforms.ambient.value = material.ambient;
  12532. uniforms.emissive.value = material.emissive;
  12533. }
  12534. if ( material.wrapAround ) {
  12535. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12536. }
  12537. };
  12538. function refreshUniformsLights ( uniforms, lights ) {
  12539. uniforms.ambientLightColor.value = lights.ambient;
  12540. uniforms.directionalLightColor.value = lights.directional.colors;
  12541. uniforms.directionalLightDirection.value = lights.directional.positions;
  12542. uniforms.pointLightColor.value = lights.point.colors;
  12543. uniforms.pointLightPosition.value = lights.point.positions;
  12544. uniforms.pointLightDistance.value = lights.point.distances;
  12545. uniforms.spotLightColor.value = lights.spot.colors;
  12546. uniforms.spotLightPosition.value = lights.spot.positions;
  12547. uniforms.spotLightDistance.value = lights.spot.distances;
  12548. uniforms.spotLightDirection.value = lights.spot.directions;
  12549. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  12550. uniforms.spotLightExponent.value = lights.spot.exponents;
  12551. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  12552. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  12553. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  12554. };
  12555. function refreshUniformsShadow ( uniforms, lights ) {
  12556. if ( uniforms.shadowMatrix ) {
  12557. var j = 0;
  12558. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  12559. var light = lights[ i ];
  12560. if ( ! light.castShadow ) continue;
  12561. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  12562. uniforms.shadowMap.value[ j ] = light.shadowMap;
  12563. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  12564. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  12565. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  12566. uniforms.shadowBias.value[ j ] = light.shadowBias;
  12567. j ++;
  12568. }
  12569. }
  12570. }
  12571. };
  12572. // Uniforms (load to GPU)
  12573. function loadUniformsMatrices ( uniforms, object ) {
  12574. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  12575. if ( uniforms.normalMatrix ) {
  12576. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  12577. }
  12578. };
  12579. function getTextureUnit() {
  12580. var textureUnit = _usedTextureUnits;
  12581. if ( textureUnit >= _maxTextures ) {
  12582. console.warn( "Trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  12583. }
  12584. _usedTextureUnits += 1;
  12585. return textureUnit;
  12586. };
  12587. function loadUniformsGeneric ( program, uniforms ) {
  12588. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  12589. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  12590. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  12591. if ( !location ) continue;
  12592. uniform = uniforms[ j ][ 0 ];
  12593. type = uniform.type;
  12594. value = uniform.value;
  12595. if ( type === "i" ) { // single integer
  12596. _gl.uniform1i( location, value );
  12597. } else if ( type === "f" ) { // single float
  12598. _gl.uniform1f( location, value );
  12599. } else if ( type === "v2" ) { // single THREE.Vector2
  12600. _gl.uniform2f( location, value.x, value.y );
  12601. } else if ( type === "v3" ) { // single THREE.Vector3
  12602. _gl.uniform3f( location, value.x, value.y, value.z );
  12603. } else if ( type === "v4" ) { // single THREE.Vector4
  12604. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  12605. } else if ( type === "c" ) { // single THREE.Color
  12606. _gl.uniform3f( location, value.r, value.g, value.b );
  12607. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  12608. _gl.uniform1iv( location, value );
  12609. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  12610. _gl.uniform3iv( location, value );
  12611. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  12612. _gl.uniform1fv( location, value );
  12613. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  12614. _gl.uniform3fv( location, value );
  12615. } else if ( type === "v2v" ) { // array of THREE.Vector2
  12616. if ( uniform._array === undefined ) {
  12617. uniform._array = new Float32Array( 2 * value.length );
  12618. }
  12619. for ( i = 0, il = value.length; i < il; i ++ ) {
  12620. offset = i * 2;
  12621. uniform._array[ offset ] = value[ i ].x;
  12622. uniform._array[ offset + 1 ] = value[ i ].y;
  12623. }
  12624. _gl.uniform2fv( location, uniform._array );
  12625. } else if ( type === "v3v" ) { // array of THREE.Vector3
  12626. if ( uniform._array === undefined ) {
  12627. uniform._array = new Float32Array( 3 * value.length );
  12628. }
  12629. for ( i = 0, il = value.length; i < il; i ++ ) {
  12630. offset = i * 3;
  12631. uniform._array[ offset ] = value[ i ].x;
  12632. uniform._array[ offset + 1 ] = value[ i ].y;
  12633. uniform._array[ offset + 2 ] = value[ i ].z;
  12634. }
  12635. _gl.uniform3fv( location, uniform._array );
  12636. } else if ( type === "v4v" ) { // array of THREE.Vector4
  12637. if ( uniform._array === undefined ) {
  12638. uniform._array = new Float32Array( 4 * value.length );
  12639. }
  12640. for ( i = 0, il = value.length; i < il; i ++ ) {
  12641. offset = i * 4;
  12642. uniform._array[ offset ] = value[ i ].x;
  12643. uniform._array[ offset + 1 ] = value[ i ].y;
  12644. uniform._array[ offset + 2 ] = value[ i ].z;
  12645. uniform._array[ offset + 3 ] = value[ i ].w;
  12646. }
  12647. _gl.uniform4fv( location, uniform._array );
  12648. } else if ( type === "m4") { // single THREE.Matrix4
  12649. if ( uniform._array === undefined ) {
  12650. uniform._array = new Float32Array( 16 );
  12651. }
  12652. value.flattenToArray( uniform._array );
  12653. _gl.uniformMatrix4fv( location, false, uniform._array );
  12654. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  12655. if ( uniform._array === undefined ) {
  12656. uniform._array = new Float32Array( 16 * value.length );
  12657. }
  12658. for ( i = 0, il = value.length; i < il; i ++ ) {
  12659. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  12660. }
  12661. _gl.uniformMatrix4fv( location, false, uniform._array );
  12662. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  12663. texture = value;
  12664. textureUnit = getTextureUnit();
  12665. _gl.uniform1i( location, textureUnit );
  12666. if ( !texture ) continue;
  12667. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  12668. setCubeTexture( texture, textureUnit );
  12669. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  12670. setCubeTextureDynamic( texture, textureUnit );
  12671. } else {
  12672. _this.setTexture( texture, textureUnit );
  12673. }
  12674. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  12675. if ( uniform._array === undefined ) {
  12676. uniform._array = [];
  12677. }
  12678. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12679. uniform._array[ i ] = getTextureUnit();
  12680. }
  12681. _gl.uniform1iv( location, uniform._array );
  12682. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12683. texture = uniform.value[ i ];
  12684. textureUnit = uniform._array[ i ];
  12685. if ( !texture ) continue;
  12686. _this.setTexture( texture, textureUnit );
  12687. }
  12688. }
  12689. }
  12690. };
  12691. function setupMatrices ( object, camera ) {
  12692. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  12693. object._normalMatrix.getInverse( object._modelViewMatrix );
  12694. object._normalMatrix.transpose();
  12695. };
  12696. //
  12697. function setColorGamma( array, offset, color, intensitySq ) {
  12698. array[ offset ] = color.r * color.r * intensitySq;
  12699. array[ offset + 1 ] = color.g * color.g * intensitySq;
  12700. array[ offset + 2 ] = color.b * color.b * intensitySq;
  12701. };
  12702. function setColorLinear( array, offset, color, intensity ) {
  12703. array[ offset ] = color.r * intensity;
  12704. array[ offset + 1 ] = color.g * intensity;
  12705. array[ offset + 2 ] = color.b * intensity;
  12706. };
  12707. function setupLights ( program, lights ) {
  12708. var l, ll, light, n,
  12709. r = 0, g = 0, b = 0,
  12710. color, skyColor, groundColor,
  12711. intensity, intensitySq,
  12712. position,
  12713. distance,
  12714. zlights = _lights,
  12715. dirColors = zlights.directional.colors,
  12716. dirPositions = zlights.directional.positions,
  12717. pointColors = zlights.point.colors,
  12718. pointPositions = zlights.point.positions,
  12719. pointDistances = zlights.point.distances,
  12720. spotColors = zlights.spot.colors,
  12721. spotPositions = zlights.spot.positions,
  12722. spotDistances = zlights.spot.distances,
  12723. spotDirections = zlights.spot.directions,
  12724. spotAnglesCos = zlights.spot.anglesCos,
  12725. spotExponents = zlights.spot.exponents,
  12726. hemiSkyColors = zlights.hemi.skyColors,
  12727. hemiGroundColors = zlights.hemi.groundColors,
  12728. hemiPositions = zlights.hemi.positions,
  12729. dirLength = 0,
  12730. pointLength = 0,
  12731. spotLength = 0,
  12732. hemiLength = 0,
  12733. dirCount = 0,
  12734. pointCount = 0,
  12735. spotCount = 0,
  12736. hemiCount = 0,
  12737. dirOffset = 0,
  12738. pointOffset = 0,
  12739. spotOffset = 0,
  12740. hemiOffset = 0;
  12741. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12742. light = lights[ l ];
  12743. if ( light.onlyShadow ) continue;
  12744. color = light.color;
  12745. intensity = light.intensity;
  12746. distance = light.distance;
  12747. if ( light instanceof THREE.AmbientLight ) {
  12748. if ( ! light.visible ) continue;
  12749. if ( _this.gammaInput ) {
  12750. r += color.r * color.r;
  12751. g += color.g * color.g;
  12752. b += color.b * color.b;
  12753. } else {
  12754. r += color.r;
  12755. g += color.g;
  12756. b += color.b;
  12757. }
  12758. } else if ( light instanceof THREE.DirectionalLight ) {
  12759. dirCount += 1;
  12760. if ( ! light.visible ) continue;
  12761. dirOffset = dirLength * 3;
  12762. if ( _this.gammaInput ) {
  12763. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  12764. } else {
  12765. setColorLinear( dirColors, dirOffset, color, intensity );
  12766. }
  12767. _direction.copy( light.matrixWorld.getPosition() );
  12768. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12769. _direction.normalize();
  12770. dirPositions[ dirOffset ] = _direction.x;
  12771. dirPositions[ dirOffset + 1 ] = _direction.y;
  12772. dirPositions[ dirOffset + 2 ] = _direction.z;
  12773. dirLength += 1;
  12774. } else if ( light instanceof THREE.PointLight ) {
  12775. pointCount += 1;
  12776. if ( ! light.visible ) continue;
  12777. pointOffset = pointLength * 3;
  12778. if ( _this.gammaInput ) {
  12779. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  12780. } else {
  12781. setColorLinear( pointColors, pointOffset, color, intensity );
  12782. }
  12783. position = light.matrixWorld.getPosition();
  12784. pointPositions[ pointOffset ] = position.x;
  12785. pointPositions[ pointOffset + 1 ] = position.y;
  12786. pointPositions[ pointOffset + 2 ] = position.z;
  12787. pointDistances[ pointLength ] = distance;
  12788. pointLength += 1;
  12789. } else if ( light instanceof THREE.SpotLight ) {
  12790. spotCount += 1;
  12791. if ( ! light.visible ) continue;
  12792. spotOffset = spotLength * 3;
  12793. if ( _this.gammaInput ) {
  12794. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  12795. } else {
  12796. setColorLinear( spotColors, spotOffset, color, intensity );
  12797. }
  12798. position = light.matrixWorld.getPosition();
  12799. spotPositions[ spotOffset ] = position.x;
  12800. spotPositions[ spotOffset + 1 ] = position.y;
  12801. spotPositions[ spotOffset + 2 ] = position.z;
  12802. spotDistances[ spotLength ] = distance;
  12803. _direction.copy( position );
  12804. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12805. _direction.normalize();
  12806. spotDirections[ spotOffset ] = _direction.x;
  12807. spotDirections[ spotOffset + 1 ] = _direction.y;
  12808. spotDirections[ spotOffset + 2 ] = _direction.z;
  12809. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  12810. spotExponents[ spotLength ] = light.exponent;
  12811. spotLength += 1;
  12812. } else if ( light instanceof THREE.HemisphereLight ) {
  12813. hemiCount += 1;
  12814. if ( ! light.visible ) continue;
  12815. skyColor = light.color;
  12816. groundColor = light.groundColor;
  12817. hemiOffset = hemiLength * 3;
  12818. if ( _this.gammaInput ) {
  12819. intensitySq = intensity * intensity;
  12820. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  12821. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  12822. } else {
  12823. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  12824. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  12825. }
  12826. _direction.copy( light.matrixWorld.getPosition() );
  12827. _direction.normalize();
  12828. hemiPositions[ hemiOffset ] = _direction.x;
  12829. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  12830. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  12831. hemiLength += 1;
  12832. }
  12833. }
  12834. // null eventual remains from removed lights
  12835. // (this is to avoid if in shader)
  12836. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  12837. for ( l = dirLength * 3, ll = Math.max( dirPositions.length, dirCount * 3 ); l < ll; l ++ ) dirPositions[ l ] = 0.0;
  12838. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  12839. for ( l = pointLength * 3, ll = Math.max( pointPositions.length, pointCount * 3 ); l < ll; l ++ ) pointPositions[ l ] = 0.0;
  12840. for ( l = pointLength, ll = Math.max( pointDistances.length, pointCount ); l < ll; l ++ ) pointDistances[ l ] = 0.0;
  12841. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  12842. for ( l = spotLength * 3, ll = Math.max( spotPositions.length, spotCount * 3 ); l < ll; l ++ ) spotPositions[ l ] = 0.0;
  12843. for ( l = spotLength * 3, ll = Math.max( spotDirections.length, spotCount * 3 ); l < ll; l ++ ) spotDirections[ l ] = 0.0;
  12844. for ( l = spotLength, ll = Math.max( spotAnglesCos.length, spotCount ); l < ll; l ++ ) spotAnglesCos[ l ] = 0.0;
  12845. for ( l = spotLength, ll = Math.max( spotExponents.length, spotCount ); l < ll; l ++ ) spotExponents[ l ] = 0.0;
  12846. for ( l = spotLength, ll = Math.max( spotDistances.length, spotCount ); l < ll; l ++ ) spotDistances[ l ] = 0.0;
  12847. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  12848. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  12849. for ( l = hemiLength * 3, ll = Math.max( hemiPositions.length, hemiCount * 3 ); l < ll; l ++ ) hemiPositions[ l ] = 0.0;
  12850. zlights.directional.length = dirLength;
  12851. zlights.point.length = pointLength;
  12852. zlights.spot.length = spotLength;
  12853. zlights.hemi.length = hemiLength;
  12854. zlights.ambient[ 0 ] = r;
  12855. zlights.ambient[ 1 ] = g;
  12856. zlights.ambient[ 2 ] = b;
  12857. };
  12858. // GL state setting
  12859. this.setFaceCulling = function ( cullFace, frontFace ) {
  12860. if ( cullFace ) {
  12861. if ( !frontFace || frontFace === "ccw" ) {
  12862. _gl.frontFace( _gl.CCW );
  12863. } else {
  12864. _gl.frontFace( _gl.CW );
  12865. }
  12866. if( cullFace === "back" ) {
  12867. _gl.cullFace( _gl.BACK );
  12868. } else if( cullFace === "front" ) {
  12869. _gl.cullFace( _gl.FRONT );
  12870. } else {
  12871. _gl.cullFace( _gl.FRONT_AND_BACK );
  12872. }
  12873. _gl.enable( _gl.CULL_FACE );
  12874. } else {
  12875. _gl.disable( _gl.CULL_FACE );
  12876. }
  12877. };
  12878. this.setMaterialFaces = function ( material ) {
  12879. var doubleSided = material.side === THREE.DoubleSide;
  12880. var flipSided = material.side === THREE.BackSide;
  12881. if ( _oldDoubleSided !== doubleSided ) {
  12882. if ( doubleSided ) {
  12883. _gl.disable( _gl.CULL_FACE );
  12884. } else {
  12885. _gl.enable( _gl.CULL_FACE );
  12886. }
  12887. _oldDoubleSided = doubleSided;
  12888. }
  12889. if ( _oldFlipSided !== flipSided ) {
  12890. if ( flipSided ) {
  12891. _gl.frontFace( _gl.CW );
  12892. } else {
  12893. _gl.frontFace( _gl.CCW );
  12894. }
  12895. _oldFlipSided = flipSided;
  12896. }
  12897. };
  12898. this.setDepthTest = function ( depthTest ) {
  12899. if ( _oldDepthTest !== depthTest ) {
  12900. if ( depthTest ) {
  12901. _gl.enable( _gl.DEPTH_TEST );
  12902. } else {
  12903. _gl.disable( _gl.DEPTH_TEST );
  12904. }
  12905. _oldDepthTest = depthTest;
  12906. }
  12907. };
  12908. this.setDepthWrite = function ( depthWrite ) {
  12909. if ( _oldDepthWrite !== depthWrite ) {
  12910. _gl.depthMask( depthWrite );
  12911. _oldDepthWrite = depthWrite;
  12912. }
  12913. };
  12914. function setLineWidth ( width ) {
  12915. if ( width !== _oldLineWidth ) {
  12916. _gl.lineWidth( width );
  12917. _oldLineWidth = width;
  12918. }
  12919. };
  12920. function setPolygonOffset ( polygonoffset, factor, units ) {
  12921. if ( _oldPolygonOffset !== polygonoffset ) {
  12922. if ( polygonoffset ) {
  12923. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  12924. } else {
  12925. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  12926. }
  12927. _oldPolygonOffset = polygonoffset;
  12928. }
  12929. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  12930. _gl.polygonOffset( factor, units );
  12931. _oldPolygonOffsetFactor = factor;
  12932. _oldPolygonOffsetUnits = units;
  12933. }
  12934. };
  12935. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  12936. if ( blending !== _oldBlending ) {
  12937. if ( blending === THREE.NoBlending ) {
  12938. _gl.disable( _gl.BLEND );
  12939. } else if ( blending === THREE.AdditiveBlending ) {
  12940. _gl.enable( _gl.BLEND );
  12941. _gl.blendEquation( _gl.FUNC_ADD );
  12942. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  12943. } else if ( blending === THREE.SubtractiveBlending ) {
  12944. // TODO: Find blendFuncSeparate() combination
  12945. _gl.enable( _gl.BLEND );
  12946. _gl.blendEquation( _gl.FUNC_ADD );
  12947. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  12948. } else if ( blending === THREE.MultiplyBlending ) {
  12949. // TODO: Find blendFuncSeparate() combination
  12950. _gl.enable( _gl.BLEND );
  12951. _gl.blendEquation( _gl.FUNC_ADD );
  12952. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  12953. } else if ( blending === THREE.CustomBlending ) {
  12954. _gl.enable( _gl.BLEND );
  12955. } else {
  12956. _gl.enable( _gl.BLEND );
  12957. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  12958. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  12959. }
  12960. _oldBlending = blending;
  12961. }
  12962. if ( blending === THREE.CustomBlending ) {
  12963. if ( blendEquation !== _oldBlendEquation ) {
  12964. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  12965. _oldBlendEquation = blendEquation;
  12966. }
  12967. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  12968. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  12969. _oldBlendSrc = blendSrc;
  12970. _oldBlendDst = blendDst;
  12971. }
  12972. } else {
  12973. _oldBlendEquation = null;
  12974. _oldBlendSrc = null;
  12975. _oldBlendDst = null;
  12976. }
  12977. };
  12978. // Defines
  12979. function generateDefines ( defines ) {
  12980. var value, chunk, chunks = [];
  12981. for ( var d in defines ) {
  12982. value = defines[ d ];
  12983. if ( value === false ) continue;
  12984. chunk = "#define " + d + " " + value;
  12985. chunks.push( chunk );
  12986. }
  12987. return chunks.join( "\n" );
  12988. };
  12989. // Shaders
  12990. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  12991. var p, pl, d, program, code;
  12992. var chunks = [];
  12993. // Generate code
  12994. if ( shaderID ) {
  12995. chunks.push( shaderID );
  12996. } else {
  12997. chunks.push( fragmentShader );
  12998. chunks.push( vertexShader );
  12999. }
  13000. for ( d in defines ) {
  13001. chunks.push( d );
  13002. chunks.push( defines[ d ] );
  13003. }
  13004. for ( p in parameters ) {
  13005. chunks.push( p );
  13006. chunks.push( parameters[ p ] );
  13007. }
  13008. code = chunks.join();
  13009. // Check if code has been already compiled
  13010. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  13011. var programInfo = _programs[ p ];
  13012. if ( programInfo.code === code ) {
  13013. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  13014. programInfo.usedTimes ++;
  13015. return programInfo.program;
  13016. }
  13017. }
  13018. //console.log( "building new program " );
  13019. //
  13020. var customDefines = generateDefines( defines );
  13021. //
  13022. program = _gl.createProgram();
  13023. var prefix_vertex = [
  13024. "precision " + _precision + " float;",
  13025. customDefines,
  13026. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  13027. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13028. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13029. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13030. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13031. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13032. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13033. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13034. "#define MAX_SHADOWS " + parameters.maxShadows,
  13035. "#define MAX_BONES " + parameters.maxBones,
  13036. parameters.map ? "#define USE_MAP" : "",
  13037. parameters.envMap ? "#define USE_ENVMAP" : "",
  13038. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13039. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13040. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13041. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13042. parameters.vertexColors ? "#define USE_COLOR" : "",
  13043. parameters.skinning ? "#define USE_SKINNING" : "",
  13044. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  13045. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  13046. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  13047. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  13048. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  13049. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13050. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13051. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13052. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13053. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13054. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  13055. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13056. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13057. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  13058. "uniform mat4 modelMatrix;",
  13059. "uniform mat4 modelViewMatrix;",
  13060. "uniform mat4 projectionMatrix;",
  13061. "uniform mat4 viewMatrix;",
  13062. "uniform mat3 normalMatrix;",
  13063. "uniform vec3 cameraPosition;",
  13064. "attribute vec3 position;",
  13065. "attribute vec3 normal;",
  13066. "attribute vec2 uv;",
  13067. "attribute vec2 uv2;",
  13068. "#ifdef USE_COLOR",
  13069. "attribute vec3 color;",
  13070. "#endif",
  13071. "#ifdef USE_MORPHTARGETS",
  13072. "attribute vec3 morphTarget0;",
  13073. "attribute vec3 morphTarget1;",
  13074. "attribute vec3 morphTarget2;",
  13075. "attribute vec3 morphTarget3;",
  13076. "#ifdef USE_MORPHNORMALS",
  13077. "attribute vec3 morphNormal0;",
  13078. "attribute vec3 morphNormal1;",
  13079. "attribute vec3 morphNormal2;",
  13080. "attribute vec3 morphNormal3;",
  13081. "#else",
  13082. "attribute vec3 morphTarget4;",
  13083. "attribute vec3 morphTarget5;",
  13084. "attribute vec3 morphTarget6;",
  13085. "attribute vec3 morphTarget7;",
  13086. "#endif",
  13087. "#endif",
  13088. "#ifdef USE_SKINNING",
  13089. "attribute vec4 skinIndex;",
  13090. "attribute vec4 skinWeight;",
  13091. "#endif",
  13092. ""
  13093. ].join("\n");
  13094. var prefix_fragment = [
  13095. "precision " + _precision + " float;",
  13096. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  13097. customDefines,
  13098. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13099. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13100. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13101. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13102. "#define MAX_SHADOWS " + parameters.maxShadows,
  13103. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  13104. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13105. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13106. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13107. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  13108. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  13109. parameters.map ? "#define USE_MAP" : "",
  13110. parameters.envMap ? "#define USE_ENVMAP" : "",
  13111. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13112. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13113. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13114. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13115. parameters.vertexColors ? "#define USE_COLOR" : "",
  13116. parameters.metal ? "#define METAL" : "",
  13117. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13118. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13119. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13120. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13121. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13122. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  13123. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13124. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13125. "uniform mat4 viewMatrix;",
  13126. "uniform vec3 cameraPosition;",
  13127. ""
  13128. ].join("\n");
  13129. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  13130. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  13131. _gl.attachShader( program, glVertexShader );
  13132. _gl.attachShader( program, glFragmentShader );
  13133. _gl.linkProgram( program );
  13134. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  13135. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  13136. }
  13137. // clean up
  13138. _gl.deleteShader( glFragmentShader );
  13139. _gl.deleteShader( glVertexShader );
  13140. //console.log( prefix_fragment + fragmentShader );
  13141. //console.log( prefix_vertex + vertexShader );
  13142. program.uniforms = {};
  13143. program.attributes = {};
  13144. var identifiers, u, a, i;
  13145. // cache uniform locations
  13146. identifiers = [
  13147. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  13148. 'morphTargetInfluences'
  13149. ];
  13150. if ( parameters.useVertexTexture ) {
  13151. identifiers.push( 'boneTexture' );
  13152. } else {
  13153. identifiers.push( 'boneGlobalMatrices' );
  13154. }
  13155. for ( u in uniforms ) {
  13156. identifiers.push( u );
  13157. }
  13158. cacheUniformLocations( program, identifiers );
  13159. // cache attributes locations
  13160. identifiers = [
  13161. "position", "normal", "uv", "uv2", "tangent", "color",
  13162. "skinIndex", "skinWeight", "lineDistance"
  13163. ];
  13164. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  13165. identifiers.push( "morphTarget" + i );
  13166. }
  13167. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  13168. identifiers.push( "morphNormal" + i );
  13169. }
  13170. for ( a in attributes ) {
  13171. identifiers.push( a );
  13172. }
  13173. cacheAttributeLocations( program, identifiers );
  13174. program.id = _programs_counter ++;
  13175. _programs.push( { program: program, code: code, usedTimes: 1 } );
  13176. _this.info.memory.programs = _programs.length;
  13177. return program;
  13178. };
  13179. // Shader parameters cache
  13180. function cacheUniformLocations ( program, identifiers ) {
  13181. var i, l, id;
  13182. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13183. id = identifiers[ i ];
  13184. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  13185. }
  13186. };
  13187. function cacheAttributeLocations ( program, identifiers ) {
  13188. var i, l, id;
  13189. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13190. id = identifiers[ i ];
  13191. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  13192. }
  13193. };
  13194. function addLineNumbers ( string ) {
  13195. var chunks = string.split( "\n" );
  13196. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  13197. // Chrome reports shader errors on lines
  13198. // starting counting from 1
  13199. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  13200. }
  13201. return chunks.join( "\n" );
  13202. };
  13203. function getShader ( type, string ) {
  13204. var shader;
  13205. if ( type === "fragment" ) {
  13206. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  13207. } else if ( type === "vertex" ) {
  13208. shader = _gl.createShader( _gl.VERTEX_SHADER );
  13209. }
  13210. _gl.shaderSource( shader, string );
  13211. _gl.compileShader( shader );
  13212. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  13213. console.error( _gl.getShaderInfoLog( shader ) );
  13214. console.error( addLineNumbers( string ) );
  13215. return null;
  13216. }
  13217. return shader;
  13218. };
  13219. // Textures
  13220. function isPowerOfTwo ( value ) {
  13221. return ( value & ( value - 1 ) ) === 0;
  13222. };
  13223. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  13224. if ( isImagePowerOfTwo ) {
  13225. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13226. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13227. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13228. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13229. } else {
  13230. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13231. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13232. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13233. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13234. }
  13235. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  13236. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  13237. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  13238. texture.__oldAnisotropy = texture.anisotropy;
  13239. }
  13240. }
  13241. };
  13242. this.setTexture = function ( texture, slot ) {
  13243. if ( texture.needsUpdate ) {
  13244. if ( ! texture.__webglInit ) {
  13245. texture.__webglInit = true;
  13246. texture.__webglTexture = _gl.createTexture();
  13247. _this.info.memory.textures ++;
  13248. }
  13249. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13250. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13251. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13252. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13253. var image = texture.image,
  13254. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13255. glFormat = paramThreeToGL( texture.format ),
  13256. glType = paramThreeToGL( texture.type );
  13257. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  13258. if ( texture instanceof THREE.CompressedTexture ) {
  13259. var mipmap, mipmaps = texture.mipmaps;
  13260. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13261. mipmap = mipmaps[ i ];
  13262. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13263. }
  13264. } else if ( texture instanceof THREE.DataTexture ) {
  13265. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13266. } else {
  13267. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13268. }
  13269. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13270. texture.needsUpdate = false;
  13271. if ( texture.onUpdate ) texture.onUpdate();
  13272. } else {
  13273. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13274. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13275. }
  13276. };
  13277. function clampToMaxSize ( image, maxSize ) {
  13278. if ( image.width <= maxSize && image.height <= maxSize ) {
  13279. return image;
  13280. }
  13281. // Warning: Scaling through the canvas will only work with images that use
  13282. // premultiplied alpha.
  13283. var maxDimension = Math.max( image.width, image.height );
  13284. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  13285. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  13286. var canvas = document.createElement( 'canvas' );
  13287. canvas.width = newWidth;
  13288. canvas.height = newHeight;
  13289. var ctx = canvas.getContext( "2d" );
  13290. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  13291. return canvas;
  13292. }
  13293. function setCubeTexture ( texture, slot ) {
  13294. if ( texture.image.length === 6 ) {
  13295. if ( texture.needsUpdate ) {
  13296. if ( ! texture.image.__webglTextureCube ) {
  13297. texture.image.__webglTextureCube = _gl.createTexture();
  13298. }
  13299. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13300. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13301. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13302. var isCompressed = texture instanceof THREE.CompressedTexture;
  13303. var cubeImage = [];
  13304. for ( var i = 0; i < 6; i ++ ) {
  13305. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  13306. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  13307. } else {
  13308. cubeImage[ i ] = texture.image[ i ];
  13309. }
  13310. }
  13311. var image = cubeImage[ 0 ],
  13312. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13313. glFormat = paramThreeToGL( texture.format ),
  13314. glType = paramThreeToGL( texture.type );
  13315. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  13316. for ( var i = 0; i < 6; i ++ ) {
  13317. if ( isCompressed ) {
  13318. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13319. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13320. mipmap = mipmaps[ j ];
  13321. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13322. }
  13323. } else {
  13324. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13325. }
  13326. }
  13327. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  13328. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13329. }
  13330. texture.needsUpdate = false;
  13331. if ( texture.onUpdate ) texture.onUpdate();
  13332. } else {
  13333. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13334. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13335. }
  13336. }
  13337. };
  13338. function setCubeTextureDynamic ( texture, slot ) {
  13339. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13340. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  13341. };
  13342. // Render targets
  13343. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  13344. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13345. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  13346. };
  13347. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  13348. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13349. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13350. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13351. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13352. /* For some reason this is not working. Defaulting to RGBA4.
  13353. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13354. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  13355. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13356. */
  13357. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13358. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  13359. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13360. } else {
  13361. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  13362. }
  13363. };
  13364. this.setRenderTarget = function ( renderTarget ) {
  13365. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  13366. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  13367. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  13368. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  13369. renderTarget.__webglTexture = _gl.createTexture();
  13370. // Setup texture, create render and frame buffers
  13371. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  13372. glFormat = paramThreeToGL( renderTarget.format ),
  13373. glType = paramThreeToGL( renderTarget.type );
  13374. if ( isCube ) {
  13375. renderTarget.__webglFramebuffer = [];
  13376. renderTarget.__webglRenderbuffer = [];
  13377. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13378. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  13379. for ( var i = 0; i < 6; i ++ ) {
  13380. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13381. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  13382. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13383. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  13384. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  13385. }
  13386. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13387. } else {
  13388. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  13389. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  13390. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13391. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  13392. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13393. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  13394. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  13395. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13396. }
  13397. // Release everything
  13398. if ( isCube ) {
  13399. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13400. } else {
  13401. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13402. }
  13403. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  13404. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
  13405. }
  13406. var framebuffer, width, height, vx, vy;
  13407. if ( renderTarget ) {
  13408. if ( isCube ) {
  13409. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13410. } else {
  13411. framebuffer = renderTarget.__webglFramebuffer;
  13412. }
  13413. width = renderTarget.width;
  13414. height = renderTarget.height;
  13415. vx = 0;
  13416. vy = 0;
  13417. } else {
  13418. framebuffer = null;
  13419. width = _viewportWidth;
  13420. height = _viewportHeight;
  13421. vx = _viewportX;
  13422. vy = _viewportY;
  13423. }
  13424. if ( framebuffer !== _currentFramebuffer ) {
  13425. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13426. _gl.viewport( vx, vy, width, height );
  13427. _currentFramebuffer = framebuffer;
  13428. }
  13429. _currentWidth = width;
  13430. _currentHeight = height;
  13431. };
  13432. function updateRenderTargetMipmap ( renderTarget ) {
  13433. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  13434. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13435. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13436. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13437. } else {
  13438. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13439. _gl.generateMipmap( _gl.TEXTURE_2D );
  13440. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13441. }
  13442. };
  13443. // Fallback filters for non-power-of-2 textures
  13444. function filterFallback ( f ) {
  13445. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  13446. return _gl.NEAREST;
  13447. }
  13448. return _gl.LINEAR;
  13449. };
  13450. // Map three.js constants to WebGL constants
  13451. function paramThreeToGL ( p ) {
  13452. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  13453. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13454. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13455. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  13456. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13457. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13458. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  13459. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13460. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13461. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13462. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13463. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13464. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13465. if ( p === THREE.ByteType ) return _gl.BYTE;
  13466. if ( p === THREE.ShortType ) return _gl.SHORT;
  13467. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13468. if ( p === THREE.IntType ) return _gl.INT;
  13469. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  13470. if ( p === THREE.FloatType ) return _gl.FLOAT;
  13471. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  13472. if ( p === THREE.RGBFormat ) return _gl.RGB;
  13473. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  13474. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  13475. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13476. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  13477. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13478. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13479. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  13480. if ( p === THREE.OneFactor ) return _gl.ONE;
  13481. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  13482. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13483. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13484. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13485. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  13486. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13487. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  13488. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13489. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13490. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  13491. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13492. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13493. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13494. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13495. }
  13496. return 0;
  13497. };
  13498. // Allocations
  13499. function allocateBones ( object ) {
  13500. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  13501. return 1024;
  13502. } else {
  13503. // default for when object is not specified
  13504. // ( for example when prebuilding shader
  13505. // to be used with multiple objects )
  13506. //
  13507. // - leave some extra space for other uniforms
  13508. // - limit here is ANGLE's 254 max uniform vectors
  13509. // (up to 54 should be safe)
  13510. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  13511. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  13512. var maxBones = nVertexMatrices;
  13513. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  13514. maxBones = Math.min( object.bones.length, maxBones );
  13515. if ( maxBones < object.bones.length ) {
  13516. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  13517. }
  13518. }
  13519. return maxBones;
  13520. }
  13521. };
  13522. function allocateLights ( lights ) {
  13523. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  13524. dirLights = pointLights = spotLights = hemiLights = 0;
  13525. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13526. light = lights[ l ];
  13527. if ( light.onlyShadow ) continue;
  13528. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  13529. if ( light instanceof THREE.PointLight ) pointLights ++;
  13530. if ( light instanceof THREE.SpotLight ) spotLights ++;
  13531. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  13532. }
  13533. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  13534. };
  13535. function allocateShadows ( lights ) {
  13536. var l, ll, light, maxShadows = 0;
  13537. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  13538. light = lights[ l ];
  13539. if ( ! light.castShadow ) continue;
  13540. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  13541. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  13542. }
  13543. return maxShadows;
  13544. };
  13545. // Initialization
  13546. function initGL () {
  13547. try {
  13548. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  13549. throw 'Error creating WebGL context.';
  13550. }
  13551. } catch ( error ) {
  13552. console.error( error );
  13553. }
  13554. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  13555. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  13556. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  13557. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  13558. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  13559. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  13560. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  13561. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  13562. if ( ! _glExtensionTextureFloat ) {
  13563. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  13564. }
  13565. if ( ! _glExtensionStandardDerivatives ) {
  13566. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  13567. }
  13568. if ( ! _glExtensionTextureFilterAnisotropic ) {
  13569. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  13570. }
  13571. if ( ! _glExtensionCompressedTextureS3TC ) {
  13572. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  13573. }
  13574. };
  13575. function setDefaultGLState () {
  13576. _gl.clearColor( 0, 0, 0, 1 );
  13577. _gl.clearDepth( 1 );
  13578. _gl.clearStencil( 0 );
  13579. _gl.enable( _gl.DEPTH_TEST );
  13580. _gl.depthFunc( _gl.LEQUAL );
  13581. _gl.frontFace( _gl.CCW );
  13582. _gl.cullFace( _gl.BACK );
  13583. _gl.enable( _gl.CULL_FACE );
  13584. _gl.enable( _gl.BLEND );
  13585. _gl.blendEquation( _gl.FUNC_ADD );
  13586. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  13587. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  13588. };
  13589. // default plugins (order is important)
  13590. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  13591. this.addPrePlugin( this.shadowMapPlugin );
  13592. this.addPostPlugin( new THREE.SpritePlugin() );
  13593. this.addPostPlugin( new THREE.LensFlarePlugin() );
  13594. };
  13595. /**
  13596. * @author szimek / https://github.com/szimek/
  13597. * @author alteredq / http://alteredqualia.com/
  13598. */
  13599. THREE.WebGLRenderTarget = function ( width, height, options ) {
  13600. this.width = width;
  13601. this.height = height;
  13602. options = options || {};
  13603. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  13604. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  13605. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  13606. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  13607. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  13608. this.offset = new THREE.Vector2( 0, 0 );
  13609. this.repeat = new THREE.Vector2( 1, 1 );
  13610. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  13611. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  13612. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  13613. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  13614. this.generateMipmaps = true;
  13615. };
  13616. THREE.WebGLRenderTarget.prototype.clone = function() {
  13617. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  13618. tmp.wrapS = this.wrapS;
  13619. tmp.wrapT = this.wrapT;
  13620. tmp.magFilter = this.magFilter;
  13621. tmp.anisotropy = this.anisotropy;
  13622. tmp.minFilter = this.minFilter;
  13623. tmp.offset.copy( this.offset );
  13624. tmp.repeat.copy( this.repeat );
  13625. tmp.format = this.format;
  13626. tmp.type = this.type;
  13627. tmp.depthBuffer = this.depthBuffer;
  13628. tmp.stencilBuffer = this.stencilBuffer;
  13629. tmp.generateMipmaps = this.generateMipmaps;
  13630. return tmp;
  13631. };
  13632. /**
  13633. * @author alteredq / http://alteredqualia.com
  13634. */
  13635. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  13636. THREE.WebGLRenderTarget.call( this, width, height, options );
  13637. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  13638. };
  13639. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  13640. /**
  13641. * @author mrdoob / http://mrdoob.com/
  13642. */
  13643. THREE.RenderableVertex = function () {
  13644. this.positionWorld = new THREE.Vector3();
  13645. this.positionScreen = new THREE.Vector4();
  13646. this.visible = true;
  13647. };
  13648. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  13649. this.positionWorld.copy( vertex.positionWorld );
  13650. this.positionScreen.copy( vertex.positionScreen );
  13651. }
  13652. /**
  13653. * @author mrdoob / http://mrdoob.com/
  13654. */
  13655. THREE.RenderableFace3 = function () {
  13656. this.v1 = new THREE.RenderableVertex();
  13657. this.v2 = new THREE.RenderableVertex();
  13658. this.v3 = new THREE.RenderableVertex();
  13659. this.centroidWorld = new THREE.Vector3();
  13660. this.centroidScreen = new THREE.Vector3();
  13661. this.normalWorld = new THREE.Vector3();
  13662. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13663. this.vertexNormalsLength = 0;
  13664. this.color = null;
  13665. this.material = null;
  13666. this.uvs = [[]];
  13667. this.z = null;
  13668. };
  13669. /**
  13670. * @author mrdoob / http://mrdoob.com/
  13671. */
  13672. THREE.RenderableFace4 = function () {
  13673. this.v1 = new THREE.RenderableVertex();
  13674. this.v2 = new THREE.RenderableVertex();
  13675. this.v3 = new THREE.RenderableVertex();
  13676. this.v4 = new THREE.RenderableVertex();
  13677. this.centroidWorld = new THREE.Vector3();
  13678. this.centroidScreen = new THREE.Vector3();
  13679. this.normalWorld = new THREE.Vector3();
  13680. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13681. this.vertexNormalsLength = 0;
  13682. this.color = null;
  13683. this.material = null;
  13684. this.uvs = [[]];
  13685. this.z = null;
  13686. };
  13687. /**
  13688. * @author mrdoob / http://mrdoob.com/
  13689. */
  13690. THREE.RenderableObject = function () {
  13691. this.object = null;
  13692. this.z = null;
  13693. };
  13694. /**
  13695. * @author mrdoob / http://mrdoob.com/
  13696. */
  13697. THREE.RenderableParticle = function () {
  13698. this.object = null;
  13699. this.x = null;
  13700. this.y = null;
  13701. this.z = null;
  13702. this.rotation = null;
  13703. this.scale = new THREE.Vector2();
  13704. this.material = null;
  13705. };
  13706. /**
  13707. * @author mrdoob / http://mrdoob.com/
  13708. */
  13709. THREE.RenderableLine = function () {
  13710. this.z = null;
  13711. this.v1 = new THREE.RenderableVertex();
  13712. this.v2 = new THREE.RenderableVertex();
  13713. this.material = null;
  13714. };
  13715. /**
  13716. * @author alteredq / http://alteredqualia.com/
  13717. */
  13718. THREE.ColorUtils = {
  13719. adjustHSV : function ( color, h, s, v ) {
  13720. var hsv = THREE.ColorUtils.__hsv;
  13721. color.getHSV( hsv );
  13722. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  13723. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  13724. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  13725. color.setHSV( hsv.h, hsv.s, hsv.v );
  13726. }
  13727. };
  13728. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  13729. * @author mrdoob / http://mrdoob.com/
  13730. * @author alteredq / http://alteredqualia.com/
  13731. */
  13732. THREE.GeometryUtils = {
  13733. // Merge two geometries or geometry and geometry from object (using object's transform)
  13734. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  13735. var matrix, matrixRotation,
  13736. vertexOffset = geometry1.vertices.length,
  13737. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  13738. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  13739. vertices1 = geometry1.vertices,
  13740. vertices2 = geometry2.vertices,
  13741. faces1 = geometry1.faces,
  13742. faces2 = geometry2.faces,
  13743. uvs1 = geometry1.faceVertexUvs[ 0 ],
  13744. uvs2 = geometry2.faceVertexUvs[ 0 ];
  13745. if ( object2 instanceof THREE.Mesh ) {
  13746. object2.matrixAutoUpdate && object2.updateMatrix();
  13747. matrix = object2.matrix;
  13748. matrixRotation = new THREE.Matrix4();
  13749. matrixRotation.extractRotation( matrix, object2.scale );
  13750. }
  13751. // vertices
  13752. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  13753. var vertex = vertices2[ i ];
  13754. var vertexCopy = vertex.clone();
  13755. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  13756. vertices1.push( vertexCopy );
  13757. }
  13758. // faces
  13759. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  13760. var face = faces2[ i ], faceCopy, normal, color,
  13761. faceVertexNormals = face.vertexNormals,
  13762. faceVertexColors = face.vertexColors;
  13763. if ( face instanceof THREE.Face3 ) {
  13764. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  13765. } else if ( face instanceof THREE.Face4 ) {
  13766. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  13767. }
  13768. faceCopy.normal.copy( face.normal );
  13769. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  13770. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  13771. normal = faceVertexNormals[ j ].clone();
  13772. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  13773. faceCopy.vertexNormals.push( normal );
  13774. }
  13775. faceCopy.color.copy( face.color );
  13776. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  13777. color = faceVertexColors[ j ];
  13778. faceCopy.vertexColors.push( color.clone() );
  13779. }
  13780. faceCopy.materialIndex = face.materialIndex;
  13781. faceCopy.centroid.copy( face.centroid );
  13782. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  13783. faces1.push( faceCopy );
  13784. }
  13785. // uvs
  13786. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  13787. var uv = uvs2[ i ], uvCopy = [];
  13788. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13789. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13790. }
  13791. uvs1.push( uvCopy );
  13792. }
  13793. },
  13794. removeMaterials: function ( geometry, materialIndexArray ) {
  13795. var materialIndexMap = {};
  13796. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  13797. materialIndexMap[ materialIndexArray[i] ] = true;
  13798. }
  13799. var face, newFaces = [];
  13800. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13801. face = geometry.faces[ i ];
  13802. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  13803. }
  13804. geometry.faces = newFaces;
  13805. },
  13806. // Get random point in triangle (via barycentric coordinates)
  13807. // (uniform distribution)
  13808. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  13809. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  13810. var a, b, c,
  13811. point = new THREE.Vector3(),
  13812. tmp = THREE.GeometryUtils.__v1;
  13813. a = THREE.GeometryUtils.random();
  13814. b = THREE.GeometryUtils.random();
  13815. if ( ( a + b ) > 1 ) {
  13816. a = 1 - a;
  13817. b = 1 - b;
  13818. }
  13819. c = 1 - a - b;
  13820. point.copy( vectorA );
  13821. point.multiplyScalar( a );
  13822. tmp.copy( vectorB );
  13823. tmp.multiplyScalar( b );
  13824. point.addSelf( tmp );
  13825. tmp.copy( vectorC );
  13826. tmp.multiplyScalar( c );
  13827. point.addSelf( tmp );
  13828. return point;
  13829. },
  13830. // Get random point in face (triangle / quad)
  13831. // (uniform distribution)
  13832. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  13833. var vA, vB, vC, vD;
  13834. if ( face instanceof THREE.Face3 ) {
  13835. vA = geometry.vertices[ face.a ];
  13836. vB = geometry.vertices[ face.b ];
  13837. vC = geometry.vertices[ face.c ];
  13838. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  13839. } else if ( face instanceof THREE.Face4 ) {
  13840. vA = geometry.vertices[ face.a ];
  13841. vB = geometry.vertices[ face.b ];
  13842. vC = geometry.vertices[ face.c ];
  13843. vD = geometry.vertices[ face.d ];
  13844. var area1, area2;
  13845. if ( useCachedAreas ) {
  13846. if ( face._area1 && face._area2 ) {
  13847. area1 = face._area1;
  13848. area2 = face._area2;
  13849. } else {
  13850. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13851. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13852. face._area1 = area1;
  13853. face._area2 = area2;
  13854. }
  13855. } else {
  13856. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  13857. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13858. }
  13859. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  13860. if ( r < area1 ) {
  13861. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  13862. } else {
  13863. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  13864. }
  13865. }
  13866. },
  13867. // Get uniformly distributed random points in mesh
  13868. // - create array with cumulative sums of face areas
  13869. // - pick random number from 0 to total area
  13870. // - find corresponding place in area array by binary search
  13871. // - get random point in face
  13872. randomPointsInGeometry: function ( geometry, n ) {
  13873. var face, i,
  13874. faces = geometry.faces,
  13875. vertices = geometry.vertices,
  13876. il = faces.length,
  13877. totalArea = 0,
  13878. cumulativeAreas = [],
  13879. vA, vB, vC, vD;
  13880. // precompute face areas
  13881. for ( i = 0; i < il; i ++ ) {
  13882. face = faces[ i ];
  13883. if ( face instanceof THREE.Face3 ) {
  13884. vA = vertices[ face.a ];
  13885. vB = vertices[ face.b ];
  13886. vC = vertices[ face.c ];
  13887. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  13888. } else if ( face instanceof THREE.Face4 ) {
  13889. vA = vertices[ face.a ];
  13890. vB = vertices[ face.b ];
  13891. vC = vertices[ face.c ];
  13892. vD = vertices[ face.d ];
  13893. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13894. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13895. face._area = face._area1 + face._area2;
  13896. }
  13897. totalArea += face._area;
  13898. cumulativeAreas[ i ] = totalArea;
  13899. }
  13900. // binary search cumulative areas array
  13901. function binarySearchIndices( value ) {
  13902. function binarySearch( start, end ) {
  13903. // return closest larger index
  13904. // if exact number is not found
  13905. if ( end < start )
  13906. return start;
  13907. var mid = start + Math.floor( ( end - start ) / 2 );
  13908. if ( cumulativeAreas[ mid ] > value ) {
  13909. return binarySearch( start, mid - 1 );
  13910. } else if ( cumulativeAreas[ mid ] < value ) {
  13911. return binarySearch( mid + 1, end );
  13912. } else {
  13913. return mid;
  13914. }
  13915. }
  13916. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  13917. return result;
  13918. }
  13919. // pick random face weighted by face area
  13920. var r, index,
  13921. result = [];
  13922. var stats = {};
  13923. for ( i = 0; i < n; i ++ ) {
  13924. r = THREE.GeometryUtils.random() * totalArea;
  13925. index = binarySearchIndices( r );
  13926. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  13927. if ( ! stats[ index ] ) {
  13928. stats[ index ] = 1;
  13929. } else {
  13930. stats[ index ] += 1;
  13931. }
  13932. }
  13933. return result;
  13934. },
  13935. // Get triangle area (by Heron's formula)
  13936. // http://en.wikipedia.org/wiki/Heron%27s_formula
  13937. triangleArea: function ( vectorA, vectorB, vectorC ) {
  13938. var s, a, b, c,
  13939. tmp = THREE.GeometryUtils.__v1;
  13940. tmp.sub( vectorA, vectorB );
  13941. a = tmp.length();
  13942. tmp.sub( vectorA, vectorC );
  13943. b = tmp.length();
  13944. tmp.sub( vectorB, vectorC );
  13945. c = tmp.length();
  13946. s = 0.5 * ( a + b + c );
  13947. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  13948. },
  13949. // Center geometry so that 0,0,0 is in center of bounding box
  13950. center: function ( geometry ) {
  13951. geometry.computeBoundingBox();
  13952. var bb = geometry.boundingBox;
  13953. var offset = new THREE.Vector3();
  13954. offset.add( bb.min, bb.max );
  13955. offset.multiplyScalar( -0.5 );
  13956. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  13957. geometry.computeBoundingBox();
  13958. return offset;
  13959. },
  13960. // Normalize UVs to be from <0,1>
  13961. // (for now just the first set of UVs)
  13962. normalizeUVs: function ( geometry ) {
  13963. var uvSet = geometry.faceVertexUvs[ 0 ];
  13964. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  13965. var uvs = uvSet[ i ];
  13966. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  13967. // texture repeat
  13968. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  13969. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  13970. }
  13971. }
  13972. },
  13973. triangulateQuads: function ( geometry ) {
  13974. var i, il, j, jl;
  13975. var faces = [];
  13976. var faceUvs = [];
  13977. var faceVertexUvs = [];
  13978. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  13979. faceUvs[ i ] = [];
  13980. }
  13981. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  13982. faceVertexUvs[ i ] = [];
  13983. }
  13984. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13985. var face = geometry.faces[ i ];
  13986. if ( face instanceof THREE.Face4 ) {
  13987. var a = face.a;
  13988. var b = face.b;
  13989. var c = face.c;
  13990. var d = face.d;
  13991. var triA = new THREE.Face3();
  13992. var triB = new THREE.Face3();
  13993. triA.color.copy( face.color );
  13994. triB.color.copy( face.color );
  13995. triA.materialIndex = face.materialIndex;
  13996. triB.materialIndex = face.materialIndex;
  13997. triA.a = a;
  13998. triA.b = b;
  13999. triA.c = d;
  14000. triB.a = b;
  14001. triB.b = c;
  14002. triB.c = d;
  14003. if ( face.vertexColors.length === 4 ) {
  14004. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  14005. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  14006. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14007. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  14008. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  14009. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14010. }
  14011. faces.push( triA, triB );
  14012. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14013. if ( geometry.faceVertexUvs[ j ].length ) {
  14014. var uvs = geometry.faceVertexUvs[ j ][ i ];
  14015. var uvA = uvs[ 0 ];
  14016. var uvB = uvs[ 1 ];
  14017. var uvC = uvs[ 2 ];
  14018. var uvD = uvs[ 3 ];
  14019. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  14020. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  14021. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14022. }
  14023. }
  14024. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14025. if ( geometry.faceUvs[ j ].length ) {
  14026. var faceUv = geometry.faceUvs[ j ][ i ];
  14027. faceUvs[ j ].push( faceUv, faceUv );
  14028. }
  14029. }
  14030. } else {
  14031. faces.push( face );
  14032. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14033. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  14034. }
  14035. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14036. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14037. }
  14038. }
  14039. }
  14040. geometry.faces = faces;
  14041. geometry.faceUvs = faceUvs;
  14042. geometry.faceVertexUvs = faceVertexUvs;
  14043. geometry.computeCentroids();
  14044. geometry.computeFaceNormals();
  14045. geometry.computeVertexNormals();
  14046. if ( geometry.hasTangents ) geometry.computeTangents();
  14047. },
  14048. // Make all faces use unique vertices
  14049. // so that each face can be separated from others
  14050. explode: function( geometry ) {
  14051. var vertices = [];
  14052. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14053. var n = vertices.length;
  14054. var face = geometry.faces[ i ];
  14055. if ( face instanceof THREE.Face4 ) {
  14056. var a = face.a;
  14057. var b = face.b;
  14058. var c = face.c;
  14059. var d = face.d;
  14060. var va = geometry.vertices[ a ];
  14061. var vb = geometry.vertices[ b ];
  14062. var vc = geometry.vertices[ c ];
  14063. var vd = geometry.vertices[ d ];
  14064. vertices.push( va.clone() );
  14065. vertices.push( vb.clone() );
  14066. vertices.push( vc.clone() );
  14067. vertices.push( vd.clone() );
  14068. face.a = n;
  14069. face.b = n + 1;
  14070. face.c = n + 2;
  14071. face.d = n + 3;
  14072. } else {
  14073. var a = face.a;
  14074. var b = face.b;
  14075. var c = face.c;
  14076. var va = geometry.vertices[ a ];
  14077. var vb = geometry.vertices[ b ];
  14078. var vc = geometry.vertices[ c ];
  14079. vertices.push( va.clone() );
  14080. vertices.push( vb.clone() );
  14081. vertices.push( vc.clone() );
  14082. face.a = n;
  14083. face.b = n + 1;
  14084. face.c = n + 2;
  14085. }
  14086. }
  14087. geometry.vertices = vertices;
  14088. delete geometry.__tmpVertices;
  14089. },
  14090. // Break faces with edges longer than maxEdgeLength
  14091. // - not recursive
  14092. tessellate: function ( geometry, maxEdgeLength ) {
  14093. var i, il, face,
  14094. a, b, c, d,
  14095. va, vb, vc, vd,
  14096. dab, dbc, dac, dcd, dad,
  14097. m, m1, m2,
  14098. vm, vm1, vm2,
  14099. vnm, vnm1, vnm2,
  14100. vcm, vcm1, vcm2,
  14101. triA, triB,
  14102. quadA, quadB,
  14103. edge;
  14104. var faces = [];
  14105. var faceVertexUvs = [];
  14106. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14107. faceVertexUvs[ i ] = [];
  14108. }
  14109. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14110. face = geometry.faces[ i ];
  14111. if ( face instanceof THREE.Face3 ) {
  14112. a = face.a;
  14113. b = face.b;
  14114. c = face.c;
  14115. va = geometry.vertices[ a ];
  14116. vb = geometry.vertices[ b ];
  14117. vc = geometry.vertices[ c ];
  14118. dab = va.distanceTo( vb );
  14119. dbc = vb.distanceTo( vc );
  14120. dac = va.distanceTo( vc );
  14121. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  14122. m = geometry.vertices.length;
  14123. triA = face.clone();
  14124. triB = face.clone();
  14125. if ( dab >= dbc && dab >= dac ) {
  14126. vm = va.clone();
  14127. vm.lerpSelf( vb, 0.5 );
  14128. triA.a = a;
  14129. triA.b = m;
  14130. triA.c = c;
  14131. triB.a = m;
  14132. triB.b = b;
  14133. triB.c = c;
  14134. if ( face.vertexNormals.length === 3 ) {
  14135. vnm = face.vertexNormals[ 0 ].clone();
  14136. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14137. triA.vertexNormals[ 1 ].copy( vnm );
  14138. triB.vertexNormals[ 0 ].copy( vnm );
  14139. }
  14140. if ( face.vertexColors.length === 3 ) {
  14141. vcm = face.vertexColors[ 0 ].clone();
  14142. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14143. triA.vertexColors[ 1 ].copy( vcm );
  14144. triB.vertexColors[ 0 ].copy( vcm );
  14145. }
  14146. edge = 0;
  14147. } else if ( dbc >= dab && dbc >= dac ) {
  14148. vm = vb.clone();
  14149. vm.lerpSelf( vc, 0.5 );
  14150. triA.a = a;
  14151. triA.b = b;
  14152. triA.c = m;
  14153. triB.a = m;
  14154. triB.b = c;
  14155. triB.c = a;
  14156. if ( face.vertexNormals.length === 3 ) {
  14157. vnm = face.vertexNormals[ 1 ].clone();
  14158. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14159. triA.vertexNormals[ 2 ].copy( vnm );
  14160. triB.vertexNormals[ 0 ].copy( vnm );
  14161. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  14162. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  14163. }
  14164. if ( face.vertexColors.length === 3 ) {
  14165. vcm = face.vertexColors[ 1 ].clone();
  14166. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14167. triA.vertexColors[ 2 ].copy( vcm );
  14168. triB.vertexColors[ 0 ].copy( vcm );
  14169. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  14170. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  14171. }
  14172. edge = 1;
  14173. } else {
  14174. vm = va.clone();
  14175. vm.lerpSelf( vc, 0.5 );
  14176. triA.a = a;
  14177. triA.b = b;
  14178. triA.c = m;
  14179. triB.a = m;
  14180. triB.b = b;
  14181. triB.c = c;
  14182. if ( face.vertexNormals.length === 3 ) {
  14183. vnm = face.vertexNormals[ 0 ].clone();
  14184. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14185. triA.vertexNormals[ 2 ].copy( vnm );
  14186. triB.vertexNormals[ 0 ].copy( vnm );
  14187. }
  14188. if ( face.vertexColors.length === 3 ) {
  14189. vcm = face.vertexColors[ 0 ].clone();
  14190. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14191. triA.vertexColors[ 2 ].copy( vcm );
  14192. triB.vertexColors[ 0 ].copy( vcm );
  14193. }
  14194. edge = 2;
  14195. }
  14196. faces.push( triA, triB );
  14197. geometry.vertices.push( vm );
  14198. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  14199. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14200. if ( geometry.faceVertexUvs[ j ].length ) {
  14201. uvs = geometry.faceVertexUvs[ j ][ i ];
  14202. uvA = uvs[ 0 ];
  14203. uvB = uvs[ 1 ];
  14204. uvC = uvs[ 2 ];
  14205. // AB
  14206. if ( edge === 0 ) {
  14207. uvM = uvA.clone();
  14208. uvM.lerpSelf( uvB, 0.5 );
  14209. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  14210. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14211. // BC
  14212. } else if ( edge === 1 ) {
  14213. uvM = uvB.clone();
  14214. uvM.lerpSelf( uvC, 0.5 );
  14215. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14216. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  14217. // AC
  14218. } else {
  14219. uvM = uvA.clone();
  14220. uvM.lerpSelf( uvC, 0.5 );
  14221. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14222. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14223. }
  14224. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14225. }
  14226. }
  14227. } else {
  14228. faces.push( face );
  14229. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14230. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14231. }
  14232. }
  14233. } else {
  14234. a = face.a;
  14235. b = face.b;
  14236. c = face.c;
  14237. d = face.d;
  14238. va = geometry.vertices[ a ];
  14239. vb = geometry.vertices[ b ];
  14240. vc = geometry.vertices[ c ];
  14241. vd = geometry.vertices[ d ];
  14242. dab = va.distanceTo( vb );
  14243. dbc = vb.distanceTo( vc );
  14244. dcd = vc.distanceTo( vd );
  14245. dad = va.distanceTo( vd );
  14246. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  14247. m1 = geometry.vertices.length;
  14248. m2 = geometry.vertices.length + 1;
  14249. quadA = face.clone();
  14250. quadB = face.clone();
  14251. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  14252. vm1 = va.clone();
  14253. vm1.lerpSelf( vb, 0.5 );
  14254. vm2 = vc.clone();
  14255. vm2.lerpSelf( vd, 0.5 );
  14256. quadA.a = a;
  14257. quadA.b = m1;
  14258. quadA.c = m2;
  14259. quadA.d = d;
  14260. quadB.a = m1;
  14261. quadB.b = b;
  14262. quadB.c = c;
  14263. quadB.d = m2;
  14264. if ( face.vertexNormals.length === 4 ) {
  14265. vnm1 = face.vertexNormals[ 0 ].clone();
  14266. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14267. vnm2 = face.vertexNormals[ 2 ].clone();
  14268. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  14269. quadA.vertexNormals[ 1 ].copy( vnm1 );
  14270. quadA.vertexNormals[ 2 ].copy( vnm2 );
  14271. quadB.vertexNormals[ 0 ].copy( vnm1 );
  14272. quadB.vertexNormals[ 3 ].copy( vnm2 );
  14273. }
  14274. if ( face.vertexColors.length === 4 ) {
  14275. vcm1 = face.vertexColors[ 0 ].clone();
  14276. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14277. vcm2 = face.vertexColors[ 2 ].clone();
  14278. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  14279. quadA.vertexColors[ 1 ].copy( vcm1 );
  14280. quadA.vertexColors[ 2 ].copy( vcm2 );
  14281. quadB.vertexColors[ 0 ].copy( vcm1 );
  14282. quadB.vertexColors[ 3 ].copy( vcm2 );
  14283. }
  14284. edge = 0;
  14285. } else {
  14286. vm1 = vb.clone();
  14287. vm1.lerpSelf( vc, 0.5 );
  14288. vm2 = vd.clone();
  14289. vm2.lerpSelf( va, 0.5 );
  14290. quadA.a = a;
  14291. quadA.b = b;
  14292. quadA.c = m1;
  14293. quadA.d = m2;
  14294. quadB.a = m2;
  14295. quadB.b = m1;
  14296. quadB.c = c;
  14297. quadB.d = d;
  14298. if ( face.vertexNormals.length === 4 ) {
  14299. vnm1 = face.vertexNormals[ 1 ].clone();
  14300. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14301. vnm2 = face.vertexNormals[ 3 ].clone();
  14302. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  14303. quadA.vertexNormals[ 2 ].copy( vnm1 );
  14304. quadA.vertexNormals[ 3 ].copy( vnm2 );
  14305. quadB.vertexNormals[ 0 ].copy( vnm2 );
  14306. quadB.vertexNormals[ 1 ].copy( vnm1 );
  14307. }
  14308. if ( face.vertexColors.length === 4 ) {
  14309. vcm1 = face.vertexColors[ 1 ].clone();
  14310. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14311. vcm2 = face.vertexColors[ 3 ].clone();
  14312. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  14313. quadA.vertexColors[ 2 ].copy( vcm1 );
  14314. quadA.vertexColors[ 3 ].copy( vcm2 );
  14315. quadB.vertexColors[ 0 ].copy( vcm2 );
  14316. quadB.vertexColors[ 1 ].copy( vcm1 );
  14317. }
  14318. edge = 1;
  14319. }
  14320. faces.push( quadA, quadB );
  14321. geometry.vertices.push( vm1, vm2 );
  14322. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  14323. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14324. if ( geometry.faceVertexUvs[ j ].length ) {
  14325. uvs = geometry.faceVertexUvs[ j ][ i ];
  14326. uvA = uvs[ 0 ];
  14327. uvB = uvs[ 1 ];
  14328. uvC = uvs[ 2 ];
  14329. uvD = uvs[ 3 ];
  14330. // AB + CD
  14331. if ( edge === 0 ) {
  14332. uvM1 = uvA.clone();
  14333. uvM1.lerpSelf( uvB, 0.5 );
  14334. uvM2 = uvC.clone();
  14335. uvM2.lerpSelf( uvD, 0.5 );
  14336. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  14337. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  14338. // BC + AD
  14339. } else {
  14340. uvM1 = uvB.clone();
  14341. uvM1.lerpSelf( uvC, 0.5 );
  14342. uvM2 = uvD.clone();
  14343. uvM2.lerpSelf( uvA, 0.5 );
  14344. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  14345. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  14346. }
  14347. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  14348. }
  14349. }
  14350. } else {
  14351. faces.push( face );
  14352. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14353. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14354. }
  14355. }
  14356. }
  14357. }
  14358. geometry.faces = faces;
  14359. geometry.faceVertexUvs = faceVertexUvs;
  14360. }
  14361. };
  14362. THREE.GeometryUtils.random = THREE.Math.random16;
  14363. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  14364. /**
  14365. * @author alteredq / http://alteredqualia.com/
  14366. * @author mrdoob / http://mrdoob.com/
  14367. */
  14368. THREE.ImageUtils = {
  14369. crossOrigin: 'anonymous',
  14370. loadTexture: function ( url, mapping, onLoad, onError ) {
  14371. var image = new Image();
  14372. var texture = new THREE.Texture( image, mapping );
  14373. var loader = new THREE.ImageLoader();
  14374. loader.addEventListener( 'load', function ( event ) {
  14375. texture.image = event.content;
  14376. texture.needsUpdate = true;
  14377. if ( onLoad ) onLoad( texture );
  14378. } );
  14379. loader.addEventListener( 'error', function ( event ) {
  14380. if ( onError ) onError( event.message );
  14381. } );
  14382. loader.crossOrigin = this.crossOrigin;
  14383. loader.load( url, image );
  14384. texture.sourceFile = url;
  14385. return texture;
  14386. },
  14387. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  14388. var texture = new THREE.CompressedTexture();
  14389. texture.mapping = mapping;
  14390. var request = new XMLHttpRequest();
  14391. request.onload = function () {
  14392. var buffer = request.response;
  14393. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14394. texture.format = dds.format;
  14395. texture.mipmaps = dds.mipmaps;
  14396. texture.image.width = dds.width;
  14397. texture.image.height = dds.height;
  14398. // gl.generateMipmap fails for compressed textures
  14399. // mipmaps must be embedded in the DDS file
  14400. // or texture filters must not use mipmapping
  14401. texture.generateMipmaps = false;
  14402. texture.needsUpdate = true;
  14403. if ( onLoad ) onLoad( texture );
  14404. }
  14405. request.onerror = onError;
  14406. request.open( 'GET', url, true );
  14407. request.responseType = "arraybuffer";
  14408. request.send( null );
  14409. return texture;
  14410. },
  14411. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  14412. var images = [];
  14413. images.loadCount = 0;
  14414. var texture = new THREE.Texture();
  14415. texture.image = images;
  14416. if ( mapping !== undefined ) texture.mapping = mapping;
  14417. // no flipping needed for cube textures
  14418. texture.flipY = false;
  14419. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14420. var cubeImage = new Image();
  14421. images[ i ] = cubeImage;
  14422. cubeImage.onload = function () {
  14423. images.loadCount += 1;
  14424. if ( images.loadCount === 6 ) {
  14425. texture.needsUpdate = true;
  14426. if ( onLoad ) onLoad();
  14427. }
  14428. };
  14429. cubeImage.onerror = onError;
  14430. cubeImage.crossOrigin = this.crossOrigin;
  14431. cubeImage.src = array[ i ];
  14432. }
  14433. return texture;
  14434. },
  14435. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  14436. var images = [];
  14437. images.loadCount = 0;
  14438. var texture = new THREE.CompressedTexture();
  14439. texture.image = images;
  14440. if ( mapping !== undefined ) texture.mapping = mapping;
  14441. // no flipping for cube textures
  14442. // (also flipping doesn't work for compressed textures )
  14443. texture.flipY = false;
  14444. // can't generate mipmaps for compressed textures
  14445. // mips must be embedded in DDS files
  14446. texture.generateMipmaps = false;
  14447. var generateCubeFaceCallback = function ( rq, img ) {
  14448. return function () {
  14449. var buffer = rq.response;
  14450. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14451. img.format = dds.format;
  14452. img.mipmaps = dds.mipmaps;
  14453. img.width = dds.width;
  14454. img.height = dds.height;
  14455. images.loadCount += 1;
  14456. if ( images.loadCount === 6 ) {
  14457. texture.format = dds.format;
  14458. texture.needsUpdate = true;
  14459. if ( onLoad ) onLoad();
  14460. }
  14461. }
  14462. }
  14463. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14464. var cubeImage = {};
  14465. images[ i ] = cubeImage;
  14466. var request = new XMLHttpRequest();
  14467. request.onload = generateCubeFaceCallback( request, cubeImage );
  14468. request.onerror = onError;
  14469. var url = array[ i ];
  14470. request.open( 'GET', url, true );
  14471. request.responseType = "arraybuffer";
  14472. request.send( null );
  14473. }
  14474. return texture;
  14475. },
  14476. parseDDS: function ( buffer, loadMipmaps ) {
  14477. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  14478. // Adapted from @toji's DDS utils
  14479. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  14480. // All values and structures referenced from:
  14481. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  14482. var DDS_MAGIC = 0x20534444;
  14483. var DDSD_CAPS = 0x1,
  14484. DDSD_HEIGHT = 0x2,
  14485. DDSD_WIDTH = 0x4,
  14486. DDSD_PITCH = 0x8,
  14487. DDSD_PIXELFORMAT = 0x1000,
  14488. DDSD_MIPMAPCOUNT = 0x20000,
  14489. DDSD_LINEARSIZE = 0x80000,
  14490. DDSD_DEPTH = 0x800000;
  14491. var DDSCAPS_COMPLEX = 0x8,
  14492. DDSCAPS_MIPMAP = 0x400000,
  14493. DDSCAPS_TEXTURE = 0x1000;
  14494. var DDSCAPS2_CUBEMAP = 0x200,
  14495. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  14496. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  14497. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  14498. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  14499. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  14500. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  14501. DDSCAPS2_VOLUME = 0x200000;
  14502. var DDPF_ALPHAPIXELS = 0x1,
  14503. DDPF_ALPHA = 0x2,
  14504. DDPF_FOURCC = 0x4,
  14505. DDPF_RGB = 0x40,
  14506. DDPF_YUV = 0x200,
  14507. DDPF_LUMINANCE = 0x20000;
  14508. function fourCCToInt32( value ) {
  14509. return value.charCodeAt(0) +
  14510. (value.charCodeAt(1) << 8) +
  14511. (value.charCodeAt(2) << 16) +
  14512. (value.charCodeAt(3) << 24);
  14513. }
  14514. function int32ToFourCC( value ) {
  14515. return String.fromCharCode(
  14516. value & 0xff,
  14517. (value >> 8) & 0xff,
  14518. (value >> 16) & 0xff,
  14519. (value >> 24) & 0xff
  14520. );
  14521. }
  14522. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  14523. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  14524. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  14525. var headerLengthInt = 31; // The header length in 32 bit ints
  14526. // Offsets into the header array
  14527. var off_magic = 0;
  14528. var off_size = 1;
  14529. var off_flags = 2;
  14530. var off_height = 3;
  14531. var off_width = 4;
  14532. var off_mipmapCount = 7;
  14533. var off_pfFlags = 20;
  14534. var off_pfFourCC = 21;
  14535. // Parse header
  14536. var header = new Int32Array( buffer, 0, headerLengthInt );
  14537. if ( header[ off_magic ] !== DDS_MAGIC ) {
  14538. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  14539. return dds;
  14540. }
  14541. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  14542. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  14543. return dds;
  14544. }
  14545. var blockBytes;
  14546. var fourCC = header[ off_pfFourCC ];
  14547. switch ( fourCC ) {
  14548. case FOURCC_DXT1:
  14549. blockBytes = 8;
  14550. dds.format = THREE.RGB_S3TC_DXT1_Format;
  14551. break;
  14552. case FOURCC_DXT3:
  14553. blockBytes = 16;
  14554. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  14555. break;
  14556. case FOURCC_DXT5:
  14557. blockBytes = 16;
  14558. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  14559. break;
  14560. default:
  14561. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  14562. return dds;
  14563. }
  14564. dds.mipmapCount = 1;
  14565. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  14566. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  14567. }
  14568. dds.width = header[ off_width ];
  14569. dds.height = header[ off_height ];
  14570. var dataOffset = header[ off_size ] + 4;
  14571. // Extract mipmaps buffers
  14572. var width = dds.width;
  14573. var height = dds.height;
  14574. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  14575. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  14576. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  14577. var mipmap = { "data": byteArray, "width": width, "height": height };
  14578. dds.mipmaps.push( mipmap );
  14579. dataOffset += dataLength;
  14580. width = Math.max( width * 0.5, 1 );
  14581. height = Math.max( height * 0.5, 1 );
  14582. }
  14583. return dds;
  14584. },
  14585. getNormalMap: function ( image, depth ) {
  14586. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  14587. var cross = function ( a, b ) {
  14588. 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 ] ];
  14589. }
  14590. var subtract = function ( a, b ) {
  14591. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  14592. }
  14593. var normalize = function ( a ) {
  14594. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  14595. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  14596. }
  14597. depth = depth | 1;
  14598. var width = image.width;
  14599. var height = image.height;
  14600. var canvas = document.createElement( 'canvas' );
  14601. canvas.width = width;
  14602. canvas.height = height;
  14603. var context = canvas.getContext( '2d' );
  14604. context.drawImage( image, 0, 0 );
  14605. var data = context.getImageData( 0, 0, width, height ).data;
  14606. var imageData = context.createImageData( width, height );
  14607. var output = imageData.data;
  14608. for ( var x = 0; x < width; x ++ ) {
  14609. for ( var y = 0; y < height; y ++ ) {
  14610. var ly = y - 1 < 0 ? 0 : y - 1;
  14611. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  14612. var lx = x - 1 < 0 ? 0 : x - 1;
  14613. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  14614. var points = [];
  14615. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  14616. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  14617. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  14618. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  14619. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  14620. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  14621. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  14622. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  14623. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  14624. var normals = [];
  14625. var num_points = points.length;
  14626. for ( var i = 0; i < num_points; i ++ ) {
  14627. var v1 = points[ i ];
  14628. var v2 = points[ ( i + 1 ) % num_points ];
  14629. v1 = subtract( v1, origin );
  14630. v2 = subtract( v2, origin );
  14631. normals.push( normalize( cross( v1, v2 ) ) );
  14632. }
  14633. var normal = [ 0, 0, 0 ];
  14634. for ( var i = 0; i < normals.length; i ++ ) {
  14635. normal[ 0 ] += normals[ i ][ 0 ];
  14636. normal[ 1 ] += normals[ i ][ 1 ];
  14637. normal[ 2 ] += normals[ i ][ 2 ];
  14638. }
  14639. normal[ 0 ] /= normals.length;
  14640. normal[ 1 ] /= normals.length;
  14641. normal[ 2 ] /= normals.length;
  14642. var idx = ( y * width + x ) * 4;
  14643. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14644. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14645. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  14646. output[ idx + 3 ] = 255;
  14647. }
  14648. }
  14649. context.putImageData( imageData, 0, 0 );
  14650. return canvas;
  14651. },
  14652. generateDataTexture: function ( width, height, color ) {
  14653. var size = width * height;
  14654. var data = new Uint8Array( 3 * size );
  14655. var r = Math.floor( color.r * 255 );
  14656. var g = Math.floor( color.g * 255 );
  14657. var b = Math.floor( color.b * 255 );
  14658. for ( var i = 0; i < size; i ++ ) {
  14659. data[ i * 3 ] = r;
  14660. data[ i * 3 + 1 ] = g;
  14661. data[ i * 3 + 2 ] = b;
  14662. }
  14663. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  14664. texture.needsUpdate = true;
  14665. return texture;
  14666. }
  14667. };
  14668. /**
  14669. * @author alteredq / http://alteredqualia.com/
  14670. */
  14671. THREE.SceneUtils = {
  14672. createMultiMaterialObject: function ( geometry, materials ) {
  14673. var group = new THREE.Object3D();
  14674. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  14675. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  14676. }
  14677. return group;
  14678. },
  14679. detach : function ( child, parent, scene ) {
  14680. child.applyMatrix( parent.matrixWorld );
  14681. parent.remove( child );
  14682. scene.add( child );
  14683. },
  14684. attach: function ( child, scene, parent ) {
  14685. var matrixWorldInverse = new THREE.Matrix4();
  14686. matrixWorldInverse.getInverse( parent.matrixWorld );
  14687. child.applyMatrix( matrixWorldInverse );
  14688. scene.remove( child );
  14689. parent.add( child );
  14690. }
  14691. };
  14692. /**
  14693. * @author alteredq / http://alteredqualia.com/
  14694. * @author mrdoob / http://mrdoob.com/
  14695. *
  14696. * ShaderUtils currently contains:
  14697. *
  14698. * fresnel
  14699. * normal
  14700. * cube
  14701. *
  14702. */
  14703. THREE.ShaderUtils = {
  14704. lib: {
  14705. /* -------------------------------------------------------------------------
  14706. // Fresnel shader
  14707. // - based on Nvidia Cg tutorial
  14708. ------------------------------------------------------------------------- */
  14709. 'fresnel': {
  14710. uniforms: {
  14711. "mRefractionRatio": { type: "f", value: 1.02 },
  14712. "mFresnelBias": { type: "f", value: 0.1 },
  14713. "mFresnelPower": { type: "f", value: 2.0 },
  14714. "mFresnelScale": { type: "f", value: 1.0 },
  14715. "tCube": { type: "t", value: null }
  14716. },
  14717. fragmentShader: [
  14718. "uniform samplerCube tCube;",
  14719. "varying vec3 vReflect;",
  14720. "varying vec3 vRefract[3];",
  14721. "varying float vReflectionFactor;",
  14722. "void main() {",
  14723. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  14724. "vec4 refractedColor = vec4( 1.0 );",
  14725. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  14726. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  14727. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  14728. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  14729. "}"
  14730. ].join("\n"),
  14731. vertexShader: [
  14732. "uniform float mRefractionRatio;",
  14733. "uniform float mFresnelBias;",
  14734. "uniform float mFresnelScale;",
  14735. "uniform float mFresnelPower;",
  14736. "varying vec3 vReflect;",
  14737. "varying vec3 vRefract[3];",
  14738. "varying float vReflectionFactor;",
  14739. "void main() {",
  14740. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14741. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  14742. "vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  14743. "vec3 I = worldPosition.xyz - cameraPosition;",
  14744. "vReflect = reflect( I, worldNormal );",
  14745. "vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );",
  14746. "vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );",
  14747. "vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );",
  14748. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );",
  14749. "gl_Position = projectionMatrix * mvPosition;",
  14750. "}"
  14751. ].join("\n")
  14752. },
  14753. /* -------------------------------------------------------------------------
  14754. // Normal map shader
  14755. // - Blinn-Phong
  14756. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  14757. // - point and directional lights (use with "lights: true" material option)
  14758. ------------------------------------------------------------------------- */
  14759. 'normal' : {
  14760. uniforms: THREE.UniformsUtils.merge( [
  14761. THREE.UniformsLib[ "fog" ],
  14762. THREE.UniformsLib[ "lights" ],
  14763. THREE.UniformsLib[ "shadowmap" ],
  14764. {
  14765. "enableAO" : { type: "i", value: 0 },
  14766. "enableDiffuse" : { type: "i", value: 0 },
  14767. "enableSpecular" : { type: "i", value: 0 },
  14768. "enableReflection": { type: "i", value: 0 },
  14769. "enableDisplacement": { type: "i", value: 0 },
  14770. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  14771. "tDiffuse" : { type: "t", value: null },
  14772. "tCube" : { type: "t", value: null },
  14773. "tNormal" : { type: "t", value: null },
  14774. "tSpecular" : { type: "t", value: null },
  14775. "tAO" : { type: "t", value: null },
  14776. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14777. "uDisplacementBias": { type: "f", value: 0.0 },
  14778. "uDisplacementScale": { type: "f", value: 1.0 },
  14779. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14780. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  14781. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14782. "uShininess": { type: "f", value: 30 },
  14783. "uOpacity": { type: "f", value: 1 },
  14784. "useRefract": { type: "i", value: 0 },
  14785. "uRefractionRatio": { type: "f", value: 0.98 },
  14786. "uReflectivity": { type: "f", value: 0.5 },
  14787. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  14788. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14789. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  14790. }
  14791. ] ),
  14792. fragmentShader: [
  14793. "uniform vec3 uAmbientColor;",
  14794. "uniform vec3 uDiffuseColor;",
  14795. "uniform vec3 uSpecularColor;",
  14796. "uniform float uShininess;",
  14797. "uniform float uOpacity;",
  14798. "uniform bool enableDiffuse;",
  14799. "uniform bool enableSpecular;",
  14800. "uniform bool enableAO;",
  14801. "uniform bool enableReflection;",
  14802. "uniform sampler2D tDiffuse;",
  14803. "uniform sampler2D tNormal;",
  14804. "uniform sampler2D tSpecular;",
  14805. "uniform sampler2D tAO;",
  14806. "uniform samplerCube tCube;",
  14807. "uniform vec2 uNormalScale;",
  14808. "uniform bool useRefract;",
  14809. "uniform float uRefractionRatio;",
  14810. "uniform float uReflectivity;",
  14811. "varying vec3 vTangent;",
  14812. "varying vec3 vBinormal;",
  14813. "varying vec3 vNormal;",
  14814. "varying vec2 vUv;",
  14815. "uniform vec3 ambientLightColor;",
  14816. "#if MAX_DIR_LIGHTS > 0",
  14817. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  14818. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  14819. "#endif",
  14820. "#if MAX_HEMI_LIGHTS > 0",
  14821. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  14822. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  14823. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  14824. "#endif",
  14825. "#if MAX_POINT_LIGHTS > 0",
  14826. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  14827. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  14828. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  14829. "#endif",
  14830. "#if MAX_SPOT_LIGHTS > 0",
  14831. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  14832. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  14833. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  14834. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  14835. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  14836. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  14837. "#endif",
  14838. "#ifdef WRAP_AROUND",
  14839. "uniform vec3 wrapRGB;",
  14840. "#endif",
  14841. "varying vec3 vWorldPosition;",
  14842. "varying vec3 vViewPosition;",
  14843. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14844. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14845. "void main() {",
  14846. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  14847. "vec3 specularTex = vec3( 1.0 );",
  14848. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  14849. "normalTex.xy *= uNormalScale;",
  14850. "normalTex = normalize( normalTex );",
  14851. "if( enableDiffuse ) {",
  14852. "#ifdef GAMMA_INPUT",
  14853. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  14854. "texelColor.xyz *= texelColor.xyz;",
  14855. "gl_FragColor = gl_FragColor * texelColor;",
  14856. "#else",
  14857. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  14858. "#endif",
  14859. "}",
  14860. "if( enableAO ) {",
  14861. "#ifdef GAMMA_INPUT",
  14862. "vec4 aoColor = texture2D( tAO, vUv );",
  14863. "aoColor.xyz *= aoColor.xyz;",
  14864. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  14865. "#else",
  14866. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  14867. "#endif",
  14868. "}",
  14869. "if( enableSpecular )",
  14870. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  14871. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  14872. "vec3 finalNormal = tsb * normalTex;",
  14873. "#ifdef FLIP_SIDED",
  14874. "finalNormal = -finalNormal;",
  14875. "#endif",
  14876. "vec3 normal = normalize( finalNormal );",
  14877. "vec3 viewPosition = normalize( vViewPosition );",
  14878. // point lights
  14879. "#if MAX_POINT_LIGHTS > 0",
  14880. "vec3 pointDiffuse = vec3( 0.0 );",
  14881. "vec3 pointSpecular = vec3( 0.0 );",
  14882. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  14883. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  14884. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  14885. "float pointDistance = 1.0;",
  14886. "if ( pointLightDistance[ i ] > 0.0 )",
  14887. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  14888. "pointVector = normalize( pointVector );",
  14889. // diffuse
  14890. "#ifdef WRAP_AROUND",
  14891. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  14892. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  14893. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  14894. "#else",
  14895. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  14896. "#endif",
  14897. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  14898. // specular
  14899. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  14900. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  14901. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  14902. "#ifdef PHYSICALLY_BASED_SHADING",
  14903. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14904. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14905. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  14906. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  14907. "#else",
  14908. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  14909. "#endif",
  14910. "}",
  14911. "#endif",
  14912. // spot lights
  14913. "#if MAX_SPOT_LIGHTS > 0",
  14914. "vec3 spotDiffuse = vec3( 0.0 );",
  14915. "vec3 spotSpecular = vec3( 0.0 );",
  14916. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  14917. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  14918. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  14919. "float spotDistance = 1.0;",
  14920. "if ( spotLightDistance[ i ] > 0.0 )",
  14921. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  14922. "spotVector = normalize( spotVector );",
  14923. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  14924. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  14925. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  14926. // diffuse
  14927. "#ifdef WRAP_AROUND",
  14928. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  14929. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  14930. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  14931. "#else",
  14932. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  14933. "#endif",
  14934. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  14935. // specular
  14936. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  14937. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  14938. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  14939. "#ifdef PHYSICALLY_BASED_SHADING",
  14940. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14941. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14942. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  14943. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  14944. "#else",
  14945. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  14946. "#endif",
  14947. "}",
  14948. "}",
  14949. "#endif",
  14950. // directional lights
  14951. "#if MAX_DIR_LIGHTS > 0",
  14952. "vec3 dirDiffuse = vec3( 0.0 );",
  14953. "vec3 dirSpecular = vec3( 0.0 );",
  14954. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  14955. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  14956. "vec3 dirVector = normalize( lDirection.xyz );",
  14957. // diffuse
  14958. "#ifdef WRAP_AROUND",
  14959. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  14960. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  14961. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  14962. "#else",
  14963. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  14964. "#endif",
  14965. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  14966. // specular
  14967. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  14968. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  14969. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  14970. "#ifdef PHYSICALLY_BASED_SHADING",
  14971. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14972. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14973. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  14974. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  14975. "#else",
  14976. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  14977. "#endif",
  14978. "}",
  14979. "#endif",
  14980. // hemisphere lights
  14981. "#if MAX_HEMI_LIGHTS > 0",
  14982. "vec3 hemiDiffuse = vec3( 0.0 );",
  14983. "vec3 hemiSpecular = vec3( 0.0 );" ,
  14984. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  14985. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  14986. "vec3 lVector = normalize( lDirection.xyz );",
  14987. // diffuse
  14988. "float dotProduct = dot( normal, lVector );",
  14989. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  14990. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  14991. "hemiDiffuse += uDiffuseColor * hemiColor;",
  14992. // specular (sky light)
  14993. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  14994. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  14995. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  14996. // specular (ground light)
  14997. "vec3 lVectorGround = -lVector;",
  14998. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  14999. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  15000. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  15001. "#ifdef PHYSICALLY_BASED_SHADING",
  15002. "float dotProductGround = dot( normal, lVectorGround );",
  15003. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15004. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15005. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  15006. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  15007. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  15008. "#else",
  15009. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  15010. "#endif",
  15011. "}",
  15012. "#endif",
  15013. // all lights contribution summation
  15014. "vec3 totalDiffuse = vec3( 0.0 );",
  15015. "vec3 totalSpecular = vec3( 0.0 );",
  15016. "#if MAX_DIR_LIGHTS > 0",
  15017. "totalDiffuse += dirDiffuse;",
  15018. "totalSpecular += dirSpecular;",
  15019. "#endif",
  15020. "#if MAX_HEMI_LIGHTS > 0",
  15021. "totalDiffuse += hemiDiffuse;",
  15022. "totalSpecular += hemiSpecular;",
  15023. "#endif",
  15024. "#if MAX_POINT_LIGHTS > 0",
  15025. "totalDiffuse += pointDiffuse;",
  15026. "totalSpecular += pointSpecular;",
  15027. "#endif",
  15028. "#if MAX_SPOT_LIGHTS > 0",
  15029. "totalDiffuse += spotDiffuse;",
  15030. "totalSpecular += spotSpecular;",
  15031. "#endif",
  15032. "#ifdef METAL",
  15033. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  15034. "#else",
  15035. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  15036. "#endif",
  15037. "if ( enableReflection ) {",
  15038. "vec3 vReflect;",
  15039. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  15040. "if ( useRefract ) {",
  15041. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  15042. "} else {",
  15043. "vReflect = reflect( cameraToVertex, normal );",
  15044. "}",
  15045. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15046. "#ifdef GAMMA_INPUT",
  15047. "cubeColor.xyz *= cubeColor.xyz;",
  15048. "#endif",
  15049. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  15050. "}",
  15051. THREE.ShaderChunk[ "shadowmap_fragment" ],
  15052. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  15053. THREE.ShaderChunk[ "fog_fragment" ],
  15054. "}"
  15055. ].join("\n"),
  15056. vertexShader: [
  15057. "attribute vec4 tangent;",
  15058. "uniform vec2 uOffset;",
  15059. "uniform vec2 uRepeat;",
  15060. "uniform bool enableDisplacement;",
  15061. "#ifdef VERTEX_TEXTURES",
  15062. "uniform sampler2D tDisplacement;",
  15063. "uniform float uDisplacementScale;",
  15064. "uniform float uDisplacementBias;",
  15065. "#endif",
  15066. "varying vec3 vTangent;",
  15067. "varying vec3 vBinormal;",
  15068. "varying vec3 vNormal;",
  15069. "varying vec2 vUv;",
  15070. "varying vec3 vWorldPosition;",
  15071. "varying vec3 vViewPosition;",
  15072. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  15073. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  15074. "void main() {",
  15075. THREE.ShaderChunk[ "skinbase_vertex" ],
  15076. THREE.ShaderChunk[ "skinnormal_vertex" ],
  15077. // normal, tangent and binormal vectors
  15078. "#ifdef USE_SKINNING",
  15079. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  15080. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  15081. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  15082. "#else",
  15083. "vNormal = normalize( normalMatrix * normal );",
  15084. "vTangent = normalize( normalMatrix * tangent.xyz );",
  15085. "#endif",
  15086. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  15087. "vUv = uv * uRepeat + uOffset;",
  15088. // displacement mapping
  15089. "vec3 displacedPosition;",
  15090. "#ifdef VERTEX_TEXTURES",
  15091. "if ( enableDisplacement ) {",
  15092. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  15093. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  15094. "displacedPosition = position + normalize( normal ) * df;",
  15095. "} else {",
  15096. "#ifdef USE_SKINNING",
  15097. "vec4 skinVertex = vec4( position, 1.0 );",
  15098. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15099. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15100. "displacedPosition = skinned.xyz;",
  15101. "#else",
  15102. "displacedPosition = position;",
  15103. "#endif",
  15104. "}",
  15105. "#else",
  15106. "#ifdef USE_SKINNING",
  15107. "vec4 skinVertex = vec4( position, 1.0 );",
  15108. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15109. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15110. "displacedPosition = skinned.xyz;",
  15111. "#else",
  15112. "displacedPosition = position;",
  15113. "#endif",
  15114. "#endif",
  15115. //
  15116. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  15117. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  15118. "gl_Position = projectionMatrix * mvPosition;",
  15119. //
  15120. "vWorldPosition = worldPosition.xyz;",
  15121. "vViewPosition = -mvPosition.xyz;",
  15122. // shadows
  15123. "#ifdef USE_SHADOWMAP",
  15124. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  15125. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  15126. "}",
  15127. "#endif",
  15128. "}"
  15129. ].join("\n")
  15130. },
  15131. /* -------------------------------------------------------------------------
  15132. // Cube map shader
  15133. ------------------------------------------------------------------------- */
  15134. 'cube': {
  15135. uniforms: { "tCube": { type: "t", value: null },
  15136. "tFlip": { type: "f", value: -1 } },
  15137. vertexShader: [
  15138. "varying vec3 vWorldPosition;",
  15139. "void main() {",
  15140. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15141. "vWorldPosition = worldPosition.xyz;",
  15142. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  15143. "}"
  15144. ].join("\n"),
  15145. fragmentShader: [
  15146. "uniform samplerCube tCube;",
  15147. "uniform float tFlip;",
  15148. "varying vec3 vWorldPosition;",
  15149. "void main() {",
  15150. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  15151. "}"
  15152. ].join("\n")
  15153. }
  15154. }
  15155. };
  15156. /**
  15157. * @author zz85 / http://www.lab4games.net/zz85/blog
  15158. * @author alteredq / http://alteredqualia.com/
  15159. *
  15160. * For Text operations in three.js (See TextGeometry)
  15161. *
  15162. * It uses techniques used in:
  15163. *
  15164. * typeface.js and canvastext
  15165. * For converting fonts and rendering with javascript
  15166. * http://typeface.neocracy.org
  15167. *
  15168. * Triangulation ported from AS3
  15169. * Simple Polygon Triangulation
  15170. * http://actionsnippet.com/?p=1462
  15171. *
  15172. * A Method to triangulate shapes with holes
  15173. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15174. *
  15175. */
  15176. THREE.FontUtils = {
  15177. faces : {},
  15178. // Just for now. face[weight][style]
  15179. face : "helvetiker",
  15180. weight: "normal",
  15181. style : "normal",
  15182. size : 150,
  15183. divisions : 10,
  15184. getFace : function() {
  15185. return this.faces[ this.face ][ this.weight ][ this.style ];
  15186. },
  15187. loadFace : function( data ) {
  15188. var family = data.familyName.toLowerCase();
  15189. var ThreeFont = this;
  15190. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15191. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15192. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15193. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15194. return data;
  15195. },
  15196. drawText : function( text ) {
  15197. var characterPts = [], allPts = [];
  15198. // RenderText
  15199. var i, p,
  15200. face = this.getFace(),
  15201. scale = this.size / face.resolution,
  15202. offset = 0,
  15203. chars = String( text ).split( '' ),
  15204. length = chars.length;
  15205. var fontPaths = [];
  15206. for ( i = 0; i < length; i ++ ) {
  15207. var path = new THREE.Path();
  15208. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15209. offset += ret.offset;
  15210. fontPaths.push( ret.path );
  15211. }
  15212. // get the width
  15213. var width = offset / 2;
  15214. //
  15215. // for ( p = 0; p < allPts.length; p++ ) {
  15216. //
  15217. // allPts[ p ].x -= width;
  15218. //
  15219. // }
  15220. //var extract = this.extractPoints( allPts, characterPts );
  15221. //extract.contour = allPts;
  15222. //extract.paths = fontPaths;
  15223. //extract.offset = width;
  15224. return { paths : fontPaths, offset : width };
  15225. },
  15226. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15227. var pts = [];
  15228. var i, i2, divisions,
  15229. outline, action, length,
  15230. scaleX, scaleY,
  15231. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15232. laste,
  15233. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15234. if ( !glyph ) return;
  15235. if ( glyph.o ) {
  15236. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15237. length = outline.length;
  15238. scaleX = scale;
  15239. scaleY = scale;
  15240. for ( i = 0; i < length; ) {
  15241. action = outline[ i ++ ];
  15242. //console.log( action );
  15243. switch( action ) {
  15244. case 'm':
  15245. // Move To
  15246. x = outline[ i++ ] * scaleX + offset;
  15247. y = outline[ i++ ] * scaleY;
  15248. path.moveTo( x, y );
  15249. break;
  15250. case 'l':
  15251. // Line To
  15252. x = outline[ i++ ] * scaleX + offset;
  15253. y = outline[ i++ ] * scaleY;
  15254. path.lineTo(x,y);
  15255. break;
  15256. case 'q':
  15257. // QuadraticCurveTo
  15258. cpx = outline[ i++ ] * scaleX + offset;
  15259. cpy = outline[ i++ ] * scaleY;
  15260. cpx1 = outline[ i++ ] * scaleX + offset;
  15261. cpy1 = outline[ i++ ] * scaleY;
  15262. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15263. laste = pts[ pts.length - 1 ];
  15264. if ( laste ) {
  15265. cpx0 = laste.x;
  15266. cpy0 = laste.y;
  15267. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15268. var t = i2 / divisions;
  15269. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15270. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15271. }
  15272. }
  15273. break;
  15274. case 'b':
  15275. // Cubic Bezier Curve
  15276. cpx = outline[ i++ ] * scaleX + offset;
  15277. cpy = outline[ i++ ] * scaleY;
  15278. cpx1 = outline[ i++ ] * scaleX + offset;
  15279. cpy1 = outline[ i++ ] * -scaleY;
  15280. cpx2 = outline[ i++ ] * scaleX + offset;
  15281. cpy2 = outline[ i++ ] * -scaleY;
  15282. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15283. laste = pts[ pts.length - 1 ];
  15284. if ( laste ) {
  15285. cpx0 = laste.x;
  15286. cpy0 = laste.y;
  15287. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15288. var t = i2 / divisions;
  15289. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15290. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15291. }
  15292. }
  15293. break;
  15294. }
  15295. }
  15296. }
  15297. return { offset: glyph.ha*scale, path:path};
  15298. }
  15299. };
  15300. THREE.FontUtils.generateShapes = function( text, parameters ) {
  15301. // Parameters
  15302. parameters = parameters || {};
  15303. var size = parameters.size !== undefined ? parameters.size : 100;
  15304. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  15305. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  15306. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  15307. var style = parameters.style !== undefined ? parameters.style : "normal";
  15308. THREE.FontUtils.size = size;
  15309. THREE.FontUtils.divisions = curveSegments;
  15310. THREE.FontUtils.face = font;
  15311. THREE.FontUtils.weight = weight;
  15312. THREE.FontUtils.style = style;
  15313. // Get a Font data json object
  15314. var data = THREE.FontUtils.drawText( text );
  15315. var paths = data.paths;
  15316. var shapes = [];
  15317. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  15318. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  15319. }
  15320. return shapes;
  15321. };
  15322. /**
  15323. * This code is a quick port of code written in C++ which was submitted to
  15324. * flipcode.com by John W. Ratcliff // July 22, 2000
  15325. * See original code and more information here:
  15326. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15327. *
  15328. * ported to actionscript by Zevan Rosser
  15329. * www.actionsnippet.com
  15330. *
  15331. * ported to javascript by Joshua Koo
  15332. * http://www.lab4games.net/zz85/blog
  15333. *
  15334. */
  15335. ( function( namespace ) {
  15336. var EPSILON = 0.0000000001;
  15337. // takes in an contour array and returns
  15338. var process = function( contour, indices ) {
  15339. var n = contour.length;
  15340. if ( n < 3 ) return null;
  15341. var result = [],
  15342. verts = [],
  15343. vertIndices = [];
  15344. /* we want a counter-clockwise polygon in verts */
  15345. var u, v, w;
  15346. if ( area( contour ) > 0.0 ) {
  15347. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  15348. } else {
  15349. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  15350. }
  15351. var nv = n;
  15352. /* remove nv - 2 vertices, creating 1 triangle every time */
  15353. var count = 2 * nv; /* error detection */
  15354. for( v = nv - 1; nv > 2; ) {
  15355. /* if we loop, it is probably a non-simple polygon */
  15356. if ( ( count-- ) <= 0 ) {
  15357. //** Triangulate: ERROR - probable bad polygon!
  15358. //throw ( "Warning, unable to triangulate polygon!" );
  15359. //return null;
  15360. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15361. console.log( "Warning, unable to triangulate polygon!" );
  15362. if ( indices ) return vertIndices;
  15363. return result;
  15364. }
  15365. /* three consecutive vertices in current polygon, <u,v,w> */
  15366. u = v; if ( nv <= u ) u = 0; /* previous */
  15367. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15368. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15369. if ( snip( contour, u, v, w, nv, verts ) ) {
  15370. var a, b, c, s, t;
  15371. /* true names of the vertices */
  15372. a = verts[ u ];
  15373. b = verts[ v ];
  15374. c = verts[ w ];
  15375. /* output Triangle */
  15376. /*
  15377. result.push( contour[ a ] );
  15378. result.push( contour[ b ] );
  15379. result.push( contour[ c ] );
  15380. */
  15381. result.push( [ contour[ a ],
  15382. contour[ b ],
  15383. contour[ c ] ] );
  15384. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15385. /* remove v from the remaining polygon */
  15386. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  15387. verts[ s ] = verts[ t ];
  15388. }
  15389. nv--;
  15390. /* reset error detection counter */
  15391. count = 2 * nv;
  15392. }
  15393. }
  15394. if ( indices ) return vertIndices;
  15395. return result;
  15396. };
  15397. // calculate area of the contour polygon
  15398. var area = function ( contour ) {
  15399. var n = contour.length;
  15400. var a = 0.0;
  15401. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  15402. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15403. }
  15404. return a * 0.5;
  15405. };
  15406. // see if p is inside triangle abc
  15407. var insideTriangle = function( ax, ay,
  15408. bx, by,
  15409. cx, cy,
  15410. px, py ) {
  15411. var aX, aY, bX, bY;
  15412. var cX, cY, apx, apy;
  15413. var bpx, bpy, cpx, cpy;
  15414. var cCROSSap, bCROSScp, aCROSSbp;
  15415. aX = cx - bx; aY = cy - by;
  15416. bX = ax - cx; bY = ay - cy;
  15417. cX = bx - ax; cY = by - ay;
  15418. apx= px -ax; apy= py - ay;
  15419. bpx= px - bx; bpy= py - by;
  15420. cpx= px - cx; cpy= py - cy;
  15421. aCROSSbp = aX*bpy - aY*bpx;
  15422. cCROSSap = cX*apy - cY*apx;
  15423. bCROSScp = bX*cpy - bY*cpx;
  15424. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  15425. };
  15426. var snip = function ( contour, u, v, w, n, verts ) {
  15427. var p;
  15428. var ax, ay, bx, by;
  15429. var cx, cy, px, py;
  15430. ax = contour[ verts[ u ] ].x;
  15431. ay = contour[ verts[ u ] ].y;
  15432. bx = contour[ verts[ v ] ].x;
  15433. by = contour[ verts[ v ] ].y;
  15434. cx = contour[ verts[ w ] ].x;
  15435. cy = contour[ verts[ w ] ].y;
  15436. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  15437. for ( p = 0; p < n; p++ ) {
  15438. if( (p == u) || (p == v) || (p == w) ) continue;
  15439. px = contour[ verts[ p ] ].x
  15440. py = contour[ verts[ p ] ].y
  15441. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  15442. }
  15443. return true;
  15444. };
  15445. namespace.Triangulate = process;
  15446. namespace.Triangulate.area = area;
  15447. return namespace;
  15448. })(THREE.FontUtils);
  15449. // To use the typeface.js face files, hook up the API
  15450. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  15451. * @author zz85 / http://www.lab4games.net/zz85/blog
  15452. * Extensible curve object
  15453. *
  15454. * Some common of Curve methods
  15455. * .getPoint(t), getTangent(t)
  15456. * .getPointAt(u), getTagentAt(u)
  15457. * .getPoints(), .getSpacedPoints()
  15458. * .getLength()
  15459. * .updateArcLengths()
  15460. *
  15461. * This file contains following classes:
  15462. *
  15463. * -- 2d classes --
  15464. * THREE.Curve
  15465. * THREE.LineCurve
  15466. * THREE.QuadraticBezierCurve
  15467. * THREE.CubicBezierCurve
  15468. * THREE.SplineCurve
  15469. * THREE.ArcCurve
  15470. * THREE.EllipseCurve
  15471. *
  15472. * -- 3d classes --
  15473. * THREE.LineCurve3
  15474. * THREE.QuadraticBezierCurve3
  15475. * THREE.CubicBezierCurve3
  15476. * THREE.SplineCurve3
  15477. * THREE.ClosedSplineCurve3
  15478. *
  15479. * A series of curves can be represented as a THREE.CurvePath
  15480. *
  15481. **/
  15482. /**************************************************************
  15483. * Abstract Curve base class
  15484. **************************************************************/
  15485. THREE.Curve = function () {
  15486. };
  15487. // Virtual base class method to overwrite and implement in subclasses
  15488. // - t [0 .. 1]
  15489. THREE.Curve.prototype.getPoint = function ( t ) {
  15490. console.log( "Warning, getPoint() not implemented!" );
  15491. return null;
  15492. };
  15493. // Get point at relative position in curve according to arc length
  15494. // - u [0 .. 1]
  15495. THREE.Curve.prototype.getPointAt = function ( u ) {
  15496. var t = this.getUtoTmapping( u );
  15497. return this.getPoint( t );
  15498. };
  15499. // Get sequence of points using getPoint( t )
  15500. THREE.Curve.prototype.getPoints = function ( divisions ) {
  15501. if ( !divisions ) divisions = 5;
  15502. var d, pts = [];
  15503. for ( d = 0; d <= divisions; d ++ ) {
  15504. pts.push( this.getPoint( d / divisions ) );
  15505. }
  15506. return pts;
  15507. };
  15508. // Get sequence of points using getPointAt( u )
  15509. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  15510. if ( !divisions ) divisions = 5;
  15511. var d, pts = [];
  15512. for ( d = 0; d <= divisions; d ++ ) {
  15513. pts.push( this.getPointAt( d / divisions ) );
  15514. }
  15515. return pts;
  15516. };
  15517. // Get total curve arc length
  15518. THREE.Curve.prototype.getLength = function () {
  15519. var lengths = this.getLengths();
  15520. return lengths[ lengths.length - 1 ];
  15521. };
  15522. // Get list of cumulative segment lengths
  15523. THREE.Curve.prototype.getLengths = function ( divisions ) {
  15524. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  15525. if ( this.cacheArcLengths
  15526. && ( this.cacheArcLengths.length == divisions + 1 )
  15527. && !this.needsUpdate) {
  15528. //console.log( "cached", this.cacheArcLengths );
  15529. return this.cacheArcLengths;
  15530. }
  15531. this.needsUpdate = false;
  15532. var cache = [];
  15533. var current, last = this.getPoint( 0 );
  15534. var p, sum = 0;
  15535. cache.push( 0 );
  15536. for ( p = 1; p <= divisions; p ++ ) {
  15537. current = this.getPoint ( p / divisions );
  15538. sum += current.distanceTo( last );
  15539. cache.push( sum );
  15540. last = current;
  15541. }
  15542. this.cacheArcLengths = cache;
  15543. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  15544. };
  15545. THREE.Curve.prototype.updateArcLengths = function() {
  15546. this.needsUpdate = true;
  15547. this.getLengths();
  15548. };
  15549. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  15550. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  15551. var arcLengths = this.getLengths();
  15552. var i = 0, il = arcLengths.length;
  15553. var targetArcLength; // The targeted u distance value to get
  15554. if ( distance ) {
  15555. targetArcLength = distance;
  15556. } else {
  15557. targetArcLength = u * arcLengths[ il - 1 ];
  15558. }
  15559. //var time = Date.now();
  15560. // binary search for the index with largest value smaller than target u distance
  15561. var low = 0, high = il - 1, comparison;
  15562. while ( low <= high ) {
  15563. 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
  15564. comparison = arcLengths[ i ] - targetArcLength;
  15565. if ( comparison < 0 ) {
  15566. low = i + 1;
  15567. continue;
  15568. } else if ( comparison > 0 ) {
  15569. high = i - 1;
  15570. continue;
  15571. } else {
  15572. high = i;
  15573. break;
  15574. // DONE
  15575. }
  15576. }
  15577. i = high;
  15578. //console.log('b' , i, low, high, Date.now()- time);
  15579. if ( arcLengths[ i ] == targetArcLength ) {
  15580. var t = i / ( il - 1 );
  15581. return t;
  15582. }
  15583. // we could get finer grain at lengths, or use simple interpolatation between two points
  15584. var lengthBefore = arcLengths[ i ];
  15585. var lengthAfter = arcLengths[ i + 1 ];
  15586. var segmentLength = lengthAfter - lengthBefore;
  15587. // determine where we are between the 'before' and 'after' points
  15588. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  15589. // add that fractional amount to t
  15590. var t = ( i + segmentFraction ) / ( il -1 );
  15591. return t;
  15592. };
  15593. // In 2D space, there are actually 2 normal vectors,
  15594. // and in 3D space, infinte
  15595. // TODO this should be depreciated.
  15596. THREE.Curve.prototype.getNormalVector = function( t ) {
  15597. var vec = this.getTangent( t );
  15598. return new THREE.Vector2( -vec.y , vec.x );
  15599. };
  15600. // Returns a unit vector tangent at t
  15601. // In case any sub curve does not implement its tangent / normal finding,
  15602. // we get 2 points with a small delta and find a gradient of the 2 points
  15603. // which seems to make a reasonable approximation
  15604. THREE.Curve.prototype.getTangent = function( t ) {
  15605. var delta = 0.0001;
  15606. var t1 = t - delta;
  15607. var t2 = t + delta;
  15608. // Capping in case of danger
  15609. if ( t1 < 0 ) t1 = 0;
  15610. if ( t2 > 1 ) t2 = 1;
  15611. var pt1 = this.getPoint( t1 );
  15612. var pt2 = this.getPoint( t2 );
  15613. var vec = pt2.clone().subSelf(pt1);
  15614. return vec.normalize();
  15615. };
  15616. THREE.Curve.prototype.getTangentAt = function ( u ) {
  15617. var t = this.getUtoTmapping( u );
  15618. return this.getTangent( t );
  15619. };
  15620. /**************************************************************
  15621. * Line
  15622. **************************************************************/
  15623. THREE.LineCurve = function ( v1, v2 ) {
  15624. this.v1 = v1;
  15625. this.v2 = v2;
  15626. };
  15627. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  15628. THREE.LineCurve.prototype.getPoint = function ( t ) {
  15629. var point = this.v2.clone().subSelf(this.v1);
  15630. point.multiplyScalar( t ).addSelf( this.v1 );
  15631. return point;
  15632. };
  15633. // Line curve is linear, so we can overwrite default getPointAt
  15634. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  15635. return this.getPoint( u );
  15636. };
  15637. THREE.LineCurve.prototype.getTangent = function( t ) {
  15638. var tangent = this.v2.clone().subSelf(this.v1);
  15639. return tangent.normalize();
  15640. };
  15641. /**************************************************************
  15642. * Quadratic Bezier curve
  15643. **************************************************************/
  15644. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  15645. this.v0 = v0;
  15646. this.v1 = v1;
  15647. this.v2 = v2;
  15648. };
  15649. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15650. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  15651. var tx, ty;
  15652. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15653. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15654. return new THREE.Vector2( tx, ty );
  15655. };
  15656. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  15657. var tx, ty;
  15658. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  15659. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  15660. // returns unit vector
  15661. var tangent = new THREE.Vector2( tx, ty );
  15662. tangent.normalize();
  15663. return tangent;
  15664. };
  15665. /**************************************************************
  15666. * Cubic Bezier curve
  15667. **************************************************************/
  15668. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  15669. this.v0 = v0;
  15670. this.v1 = v1;
  15671. this.v2 = v2;
  15672. this.v3 = v3;
  15673. };
  15674. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15675. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  15676. var tx, ty;
  15677. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15678. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15679. return new THREE.Vector2( tx, ty );
  15680. };
  15681. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  15682. var tx, ty;
  15683. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15684. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15685. var tangent = new THREE.Vector2( tx, ty );
  15686. tangent.normalize();
  15687. return tangent;
  15688. };
  15689. /**************************************************************
  15690. * Spline curve
  15691. **************************************************************/
  15692. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  15693. this.points = (points == undefined) ? [] : points;
  15694. };
  15695. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  15696. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  15697. var v = new THREE.Vector2();
  15698. var c = [];
  15699. var points = this.points, point, intPoint, weight;
  15700. point = ( points.length - 1 ) * t;
  15701. intPoint = Math.floor( point );
  15702. weight = point - intPoint;
  15703. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15704. c[ 1 ] = intPoint;
  15705. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  15706. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  15707. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15708. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15709. return v;
  15710. };
  15711. /**************************************************************
  15712. * Ellipse curve
  15713. **************************************************************/
  15714. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  15715. aStartAngle, aEndAngle,
  15716. aClockwise ) {
  15717. this.aX = aX;
  15718. this.aY = aY;
  15719. this.xRadius = xRadius;
  15720. this.yRadius = yRadius;
  15721. this.aStartAngle = aStartAngle;
  15722. this.aEndAngle = aEndAngle;
  15723. this.aClockwise = aClockwise;
  15724. };
  15725. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  15726. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  15727. var deltaAngle = this.aEndAngle - this.aStartAngle;
  15728. if ( !this.aClockwise ) {
  15729. t = 1 - t;
  15730. }
  15731. var angle = this.aStartAngle + t * deltaAngle;
  15732. var tx = this.aX + this.xRadius * Math.cos( angle );
  15733. var ty = this.aY + this.yRadius * Math.sin( angle );
  15734. return new THREE.Vector2( tx, ty );
  15735. };
  15736. /**************************************************************
  15737. * Arc curve
  15738. **************************************************************/
  15739. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  15740. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  15741. };
  15742. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  15743. /**************************************************************
  15744. * Utils
  15745. **************************************************************/
  15746. THREE.Curve.Utils = {
  15747. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  15748. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  15749. },
  15750. // Puay Bing, thanks for helping with this derivative!
  15751. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  15752. return -3 * p0 * (1 - t) * (1 - t) +
  15753. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  15754. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  15755. 3 * t * t * p3;
  15756. },
  15757. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  15758. // To check if my formulas are correct
  15759. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  15760. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  15761. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  15762. var h11 = 3 * t * t - 2 * t; // t3 − t2
  15763. return h00 + h10 + h01 + h11;
  15764. },
  15765. // Catmull-Rom
  15766. interpolate: function( p0, p1, p2, p3, t ) {
  15767. var v0 = ( p2 - p0 ) * 0.5;
  15768. var v1 = ( p3 - p1 ) * 0.5;
  15769. var t2 = t * t;
  15770. var t3 = t * t2;
  15771. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  15772. }
  15773. };
  15774. // TODO: Transformation for Curves?
  15775. /**************************************************************
  15776. * 3D Curves
  15777. **************************************************************/
  15778. // A Factory method for creating new curve subclasses
  15779. THREE.Curve.create = function ( constructor, getPointFunc ) {
  15780. constructor.prototype = Object.create( THREE.Curve.prototype );
  15781. constructor.prototype.getPoint = getPointFunc;
  15782. return constructor;
  15783. };
  15784. /**************************************************************
  15785. * Line3D
  15786. **************************************************************/
  15787. THREE.LineCurve3 = THREE.Curve.create(
  15788. function ( v1, v2 ) {
  15789. this.v1 = v1;
  15790. this.v2 = v2;
  15791. },
  15792. function ( t ) {
  15793. var r = new THREE.Vector3();
  15794. r.sub( this.v2, this.v1 ); // diff
  15795. r.multiplyScalar( t );
  15796. r.addSelf( this.v1 );
  15797. return r;
  15798. }
  15799. );
  15800. /**************************************************************
  15801. * Quadratic Bezier 3D curve
  15802. **************************************************************/
  15803. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  15804. function ( v0, v1, v2 ) {
  15805. this.v0 = v0;
  15806. this.v1 = v1;
  15807. this.v2 = v2;
  15808. },
  15809. function ( t ) {
  15810. var tx, ty, tz;
  15811. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15812. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15813. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  15814. return new THREE.Vector3( tx, ty, tz );
  15815. }
  15816. );
  15817. /**************************************************************
  15818. * Cubic Bezier 3D curve
  15819. **************************************************************/
  15820. THREE.CubicBezierCurve3 = THREE.Curve.create(
  15821. function ( v0, v1, v2, v3 ) {
  15822. this.v0 = v0;
  15823. this.v1 = v1;
  15824. this.v2 = v2;
  15825. this.v3 = v3;
  15826. },
  15827. function ( t ) {
  15828. var tx, ty, tz;
  15829. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15830. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15831. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  15832. return new THREE.Vector3( tx, ty, tz );
  15833. }
  15834. );
  15835. /**************************************************************
  15836. * Spline 3D curve
  15837. **************************************************************/
  15838. THREE.SplineCurve3 = THREE.Curve.create(
  15839. function ( points /* array of Vector3 */) {
  15840. this.points = (points == undefined) ? [] : points;
  15841. },
  15842. function ( t ) {
  15843. var v = new THREE.Vector3();
  15844. var c = [];
  15845. var points = this.points, point, intPoint, weight;
  15846. point = ( points.length - 1 ) * t;
  15847. intPoint = Math.floor( point );
  15848. weight = point - intPoint;
  15849. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15850. c[ 1 ] = intPoint;
  15851. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15852. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15853. var pt0 = points[ c[0] ],
  15854. pt1 = points[ c[1] ],
  15855. pt2 = points[ c[2] ],
  15856. pt3 = points[ c[3] ];
  15857. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  15858. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  15859. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  15860. return v;
  15861. }
  15862. );
  15863. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  15864. // var v = new THREE.Vector3();
  15865. // var c = [];
  15866. // var points = this.points, point, intPoint, weight;
  15867. // point = ( points.length - 1 ) * t;
  15868. // intPoint = Math.floor( point );
  15869. // weight = point - intPoint;
  15870. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15871. // c[ 1 ] = intPoint;
  15872. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15873. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15874. // var pt0 = points[ c[0] ],
  15875. // pt1 = points[ c[1] ],
  15876. // pt2 = points[ c[2] ],
  15877. // pt3 = points[ c[3] ];
  15878. // // t = weight;
  15879. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  15880. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  15881. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  15882. // return v;
  15883. // }
  15884. /**************************************************************
  15885. * Closed Spline 3D curve
  15886. **************************************************************/
  15887. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  15888. function ( points /* array of Vector3 */) {
  15889. this.points = (points == undefined) ? [] : points;
  15890. },
  15891. function ( t ) {
  15892. var v = new THREE.Vector3();
  15893. var c = [];
  15894. var points = this.points, point, intPoint, weight;
  15895. point = ( points.length - 0 ) * t;
  15896. // This needs to be from 0-length +1
  15897. intPoint = Math.floor( point );
  15898. weight = point - intPoint;
  15899. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  15900. c[ 0 ] = ( intPoint - 1 ) % points.length;
  15901. c[ 1 ] = ( intPoint ) % points.length;
  15902. c[ 2 ] = ( intPoint + 1 ) % points.length;
  15903. c[ 3 ] = ( intPoint + 2 ) % points.length;
  15904. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15905. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15906. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  15907. return v;
  15908. }
  15909. );
  15910. /**
  15911. * @author zz85 / http://www.lab4games.net/zz85/blog
  15912. *
  15913. **/
  15914. /**************************************************************
  15915. * Curved Path - a curve path is simply a array of connected
  15916. * curves, but retains the api of a curve
  15917. **************************************************************/
  15918. THREE.CurvePath = function () {
  15919. this.curves = [];
  15920. this.bends = [];
  15921. this.autoClose = false; // Automatically closes the path
  15922. };
  15923. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  15924. THREE.CurvePath.prototype.add = function ( curve ) {
  15925. this.curves.push( curve );
  15926. };
  15927. THREE.CurvePath.prototype.checkConnection = function() {
  15928. // TODO
  15929. // If the ending of curve is not connected to the starting
  15930. // or the next curve, then, this is not a real path
  15931. };
  15932. THREE.CurvePath.prototype.closePath = function() {
  15933. // TODO Test
  15934. // and verify for vector3 (needs to implement equals)
  15935. // Add a line curve if start and end of lines are not connected
  15936. var startPoint = this.curves[0].getPoint(0);
  15937. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  15938. if (!startPoint.equals(endPoint)) {
  15939. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  15940. }
  15941. };
  15942. // To get accurate point with reference to
  15943. // entire path distance at time t,
  15944. // following has to be done:
  15945. // 1. Length of each sub path have to be known
  15946. // 2. Locate and identify type of curve
  15947. // 3. Get t for the curve
  15948. // 4. Return curve.getPointAt(t')
  15949. THREE.CurvePath.prototype.getPoint = function( t ) {
  15950. var d = t * this.getLength();
  15951. var curveLengths = this.getCurveLengths();
  15952. var i = 0, diff, curve;
  15953. // To think about boundaries points.
  15954. while ( i < curveLengths.length ) {
  15955. if ( curveLengths[ i ] >= d ) {
  15956. diff = curveLengths[ i ] - d;
  15957. curve = this.curves[ i ];
  15958. var u = 1 - diff / curve.getLength();
  15959. return curve.getPointAt( u );
  15960. break;
  15961. }
  15962. i ++;
  15963. }
  15964. return null;
  15965. // loop where sum != 0, sum > d , sum+1 <d
  15966. };
  15967. /*
  15968. THREE.CurvePath.prototype.getTangent = function( t ) {
  15969. };*/
  15970. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  15971. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  15972. // getPoint() depends on getLength
  15973. THREE.CurvePath.prototype.getLength = function() {
  15974. var lens = this.getCurveLengths();
  15975. return lens[ lens.length - 1 ];
  15976. };
  15977. // Compute lengths and cache them
  15978. // We cannot overwrite getLengths() because UtoT mapping uses it.
  15979. THREE.CurvePath.prototype.getCurveLengths = function() {
  15980. // We use cache values if curves and cache array are same length
  15981. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  15982. return this.cacheLengths;
  15983. };
  15984. // Get length of subsurve
  15985. // Push sums into cached array
  15986. var lengths = [], sums = 0;
  15987. var i, il = this.curves.length;
  15988. for ( i = 0; i < il; i ++ ) {
  15989. sums += this.curves[ i ].getLength();
  15990. lengths.push( sums );
  15991. }
  15992. this.cacheLengths = lengths;
  15993. return lengths;
  15994. };
  15995. // Returns min and max coordinates, as well as centroid
  15996. THREE.CurvePath.prototype.getBoundingBox = function () {
  15997. var points = this.getPoints();
  15998. var maxX, maxY, maxZ;
  15999. var minX, minY, minZ;
  16000. maxX = maxY = Number.NEGATIVE_INFINITY;
  16001. minX = minY = Number.POSITIVE_INFINITY;
  16002. var p, i, il, sum;
  16003. var v3 = points[0] instanceof THREE.Vector3;
  16004. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16005. for ( i = 0, il = points.length; i < il; i ++ ) {
  16006. p = points[ i ];
  16007. if ( p.x > maxX ) maxX = p.x;
  16008. else if ( p.x < minX ) minX = p.x;
  16009. if ( p.y > maxY ) maxY = p.y;
  16010. else if ( p.y < minY ) minY = p.y;
  16011. if (v3) {
  16012. if ( p.z > maxZ ) maxZ = p.z;
  16013. else if ( p.z < minZ ) minZ = p.z;
  16014. }
  16015. sum.addSelf( p );
  16016. }
  16017. var ret = {
  16018. minX: minX,
  16019. minY: minY,
  16020. maxX: maxX,
  16021. maxY: maxY,
  16022. centroid: sum.divideScalar( il )
  16023. };
  16024. if (v3) {
  16025. ret.maxZ = maxZ;
  16026. ret.minZ = minZ;
  16027. }
  16028. return ret;
  16029. };
  16030. /**************************************************************
  16031. * Create Geometries Helpers
  16032. **************************************************************/
  16033. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16034. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16035. var pts = this.getPoints( divisions, true );
  16036. return this.createGeometry( pts );
  16037. };
  16038. // Generate geometry from equidistance sampling along the path
  16039. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16040. var pts = this.getSpacedPoints( divisions, true );
  16041. return this.createGeometry( pts );
  16042. };
  16043. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16044. var geometry = new THREE.Geometry();
  16045. for ( var i = 0; i < points.length; i ++ ) {
  16046. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16047. }
  16048. return geometry;
  16049. };
  16050. /**************************************************************
  16051. * Bend / Wrap Helper Methods
  16052. **************************************************************/
  16053. // Wrap path / Bend modifiers?
  16054. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16055. this.bends.push( bendpath );
  16056. };
  16057. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16058. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16059. var i, il;
  16060. if ( !bends ) {
  16061. bends = this.bends;
  16062. }
  16063. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16064. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16065. }
  16066. return oldPts;
  16067. };
  16068. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16069. var oldPts = this.getSpacedPoints( segments );
  16070. var i, il;
  16071. if ( !bends ) {
  16072. bends = this.bends;
  16073. }
  16074. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16075. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16076. }
  16077. return oldPts;
  16078. };
  16079. // This returns getPoints() bend/wrapped around the contour of a path.
  16080. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16081. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16082. var bounds = this.getBoundingBox();
  16083. var i, il, p, oldX, oldY, xNorm;
  16084. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16085. p = oldPts[ i ];
  16086. oldX = p.x;
  16087. oldY = p.y;
  16088. xNorm = oldX / bounds.maxX;
  16089. // If using actual distance, for length > path, requires line extrusions
  16090. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16091. xNorm = path.getUtoTmapping( xNorm, oldX );
  16092. // check for out of bounds?
  16093. var pathPt = path.getPoint( xNorm );
  16094. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16095. p.x = pathPt.x + normal.x;
  16096. p.y = pathPt.y + normal.y;
  16097. }
  16098. return oldPts;
  16099. };
  16100. /**
  16101. * @author alteredq / http://alteredqualia.com/
  16102. */
  16103. THREE.Gyroscope = function () {
  16104. THREE.Object3D.call( this );
  16105. };
  16106. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16107. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16108. this.matrixAutoUpdate && this.updateMatrix();
  16109. // update matrixWorld
  16110. if ( this.matrixWorldNeedsUpdate || force ) {
  16111. if ( this.parent ) {
  16112. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  16113. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16114. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16115. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16116. } else {
  16117. this.matrixWorld.copy( this.matrix );
  16118. }
  16119. this.matrixWorldNeedsUpdate = false;
  16120. force = true;
  16121. }
  16122. // update children
  16123. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16124. this.children[ i ].updateMatrixWorld( force );
  16125. }
  16126. };
  16127. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16128. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16129. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16130. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16131. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16132. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16133. /**
  16134. * @author zz85 / http://www.lab4games.net/zz85/blog
  16135. * Creates free form 2d path using series of points, lines or curves.
  16136. *
  16137. **/
  16138. THREE.Path = function ( points ) {
  16139. THREE.CurvePath.call(this);
  16140. this.actions = [];
  16141. if ( points ) {
  16142. this.fromPoints( points );
  16143. }
  16144. };
  16145. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16146. THREE.PathActions = {
  16147. MOVE_TO: 'moveTo',
  16148. LINE_TO: 'lineTo',
  16149. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16150. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16151. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16152. ARC: 'arc', // Circle
  16153. ELLIPSE: 'ellipse'
  16154. };
  16155. // TODO Clean up PATH API
  16156. // Create path using straight lines to connect all points
  16157. // - vectors: array of Vector2
  16158. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16159. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16160. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16161. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16162. };
  16163. };
  16164. // startPath() endPath()?
  16165. THREE.Path.prototype.moveTo = function ( x, y ) {
  16166. var args = Array.prototype.slice.call( arguments );
  16167. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16168. };
  16169. THREE.Path.prototype.lineTo = function ( x, y ) {
  16170. var args = Array.prototype.slice.call( arguments );
  16171. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16172. var x0 = lastargs[ lastargs.length - 2 ];
  16173. var y0 = lastargs[ lastargs.length - 1 ];
  16174. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16175. this.curves.push( curve );
  16176. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16177. };
  16178. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16179. var args = Array.prototype.slice.call( arguments );
  16180. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16181. var x0 = lastargs[ lastargs.length - 2 ];
  16182. var y0 = lastargs[ lastargs.length - 1 ];
  16183. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16184. new THREE.Vector2( aCPx, aCPy ),
  16185. new THREE.Vector2( aX, aY ) );
  16186. this.curves.push( curve );
  16187. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16188. };
  16189. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16190. aCP2x, aCP2y,
  16191. aX, aY ) {
  16192. var args = Array.prototype.slice.call( arguments );
  16193. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16194. var x0 = lastargs[ lastargs.length - 2 ];
  16195. var y0 = lastargs[ lastargs.length - 1 ];
  16196. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16197. new THREE.Vector2( aCP1x, aCP1y ),
  16198. new THREE.Vector2( aCP2x, aCP2y ),
  16199. new THREE.Vector2( aX, aY ) );
  16200. this.curves.push( curve );
  16201. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16202. };
  16203. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16204. var args = Array.prototype.slice.call( arguments );
  16205. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16206. var x0 = lastargs[ lastargs.length - 2 ];
  16207. var y0 = lastargs[ lastargs.length - 1 ];
  16208. //---
  16209. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16210. Array.prototype.push.apply( npts, pts );
  16211. var curve = new THREE.SplineCurve( npts );
  16212. this.curves.push( curve );
  16213. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16214. };
  16215. // FUTURE: Change the API or follow canvas API?
  16216. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16217. aStartAngle, aEndAngle, aClockwise ) {
  16218. var lastargs = this.actions[ this.actions.length - 1].args;
  16219. var x0 = lastargs[ lastargs.length - 2 ];
  16220. var y0 = lastargs[ lastargs.length - 1 ];
  16221. this.absarc(aX + x0, aY + y0, aRadius,
  16222. aStartAngle, aEndAngle, aClockwise );
  16223. };
  16224. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16225. aStartAngle, aEndAngle, aClockwise ) {
  16226. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16227. };
  16228. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16229. aStartAngle, aEndAngle, aClockwise ) {
  16230. var lastargs = this.actions[ this.actions.length - 1].args;
  16231. var x0 = lastargs[ lastargs.length - 2 ];
  16232. var y0 = lastargs[ lastargs.length - 1 ];
  16233. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16234. aStartAngle, aEndAngle, aClockwise );
  16235. };
  16236. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16237. aStartAngle, aEndAngle, aClockwise ) {
  16238. var args = Array.prototype.slice.call( arguments );
  16239. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16240. aStartAngle, aEndAngle, aClockwise );
  16241. this.curves.push( curve );
  16242. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  16243. args.push(lastPoint.x);
  16244. args.push(lastPoint.y);
  16245. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16246. };
  16247. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16248. if ( ! divisions ) divisions = 40;
  16249. var points = [];
  16250. for ( var i = 0; i < divisions; i ++ ) {
  16251. points.push( this.getPoint( i / divisions ) );
  16252. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16253. }
  16254. // if ( closedPath ) {
  16255. //
  16256. // points.push( points[ 0 ] );
  16257. //
  16258. // }
  16259. return points;
  16260. };
  16261. /* Return an array of vectors based on contour of the path */
  16262. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16263. if (this.useSpacedPoints) {
  16264. console.log('tata');
  16265. return this.getSpacedPoints( divisions, closedPath );
  16266. }
  16267. divisions = divisions || 12;
  16268. var points = [];
  16269. var i, il, item, action, args;
  16270. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16271. laste, j,
  16272. t, tx, ty;
  16273. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16274. item = this.actions[ i ];
  16275. action = item.action;
  16276. args = item.args;
  16277. switch( action ) {
  16278. case THREE.PathActions.MOVE_TO:
  16279. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16280. break;
  16281. case THREE.PathActions.LINE_TO:
  16282. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16283. break;
  16284. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16285. cpx = args[ 2 ];
  16286. cpy = args[ 3 ];
  16287. cpx1 = args[ 0 ];
  16288. cpy1 = args[ 1 ];
  16289. if ( points.length > 0 ) {
  16290. laste = points[ points.length - 1 ];
  16291. cpx0 = laste.x;
  16292. cpy0 = laste.y;
  16293. } else {
  16294. laste = this.actions[ i - 1 ].args;
  16295. cpx0 = laste[ laste.length - 2 ];
  16296. cpy0 = laste[ laste.length - 1 ];
  16297. }
  16298. for ( j = 1; j <= divisions; j ++ ) {
  16299. t = j / divisions;
  16300. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16301. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16302. points.push( new THREE.Vector2( tx, ty ) );
  16303. }
  16304. break;
  16305. case THREE.PathActions.BEZIER_CURVE_TO:
  16306. cpx = args[ 4 ];
  16307. cpy = args[ 5 ];
  16308. cpx1 = args[ 0 ];
  16309. cpy1 = args[ 1 ];
  16310. cpx2 = args[ 2 ];
  16311. cpy2 = args[ 3 ];
  16312. if ( points.length > 0 ) {
  16313. laste = points[ points.length - 1 ];
  16314. cpx0 = laste.x;
  16315. cpy0 = laste.y;
  16316. } else {
  16317. laste = this.actions[ i - 1 ].args;
  16318. cpx0 = laste[ laste.length - 2 ];
  16319. cpy0 = laste[ laste.length - 1 ];
  16320. }
  16321. for ( j = 1; j <= divisions; j ++ ) {
  16322. t = j / divisions;
  16323. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16324. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16325. points.push( new THREE.Vector2( tx, ty ) );
  16326. }
  16327. break;
  16328. case THREE.PathActions.CSPLINE_THRU:
  16329. laste = this.actions[ i - 1 ].args;
  16330. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16331. var spts = [ last ];
  16332. var n = divisions * args[ 0 ].length;
  16333. spts = spts.concat( args[ 0 ] );
  16334. var spline = new THREE.SplineCurve( spts );
  16335. for ( j = 1; j <= n; j ++ ) {
  16336. points.push( spline.getPointAt( j / n ) ) ;
  16337. }
  16338. break;
  16339. case THREE.PathActions.ARC:
  16340. var aX = args[ 0 ], aY = args[ 1 ],
  16341. aRadius = args[ 2 ],
  16342. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16343. aClockwise = !!args[ 5 ];
  16344. var deltaAngle = aEndAngle - aStartAngle;
  16345. var angle;
  16346. var tdivisions = divisions * 2;
  16347. for ( j = 1; j <= tdivisions; j ++ ) {
  16348. t = j / tdivisions;
  16349. if ( ! aClockwise ) {
  16350. t = 1 - t;
  16351. }
  16352. angle = aStartAngle + t * deltaAngle;
  16353. tx = aX + aRadius * Math.cos( angle );
  16354. ty = aY + aRadius * Math.sin( angle );
  16355. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16356. points.push( new THREE.Vector2( tx, ty ) );
  16357. }
  16358. //console.log(points);
  16359. break;
  16360. case THREE.PathActions.ELLIPSE:
  16361. var aX = args[ 0 ], aY = args[ 1 ],
  16362. xRadius = args[ 2 ],
  16363. yRadius = args[ 3 ],
  16364. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16365. aClockwise = !!args[ 6 ];
  16366. var deltaAngle = aEndAngle - aStartAngle;
  16367. var angle;
  16368. var tdivisions = divisions * 2;
  16369. for ( j = 1; j <= tdivisions; j ++ ) {
  16370. t = j / tdivisions;
  16371. if ( ! aClockwise ) {
  16372. t = 1 - t;
  16373. }
  16374. angle = aStartAngle + t * deltaAngle;
  16375. tx = aX + xRadius * Math.cos( angle );
  16376. ty = aY + yRadius * Math.sin( angle );
  16377. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16378. points.push( new THREE.Vector2( tx, ty ) );
  16379. }
  16380. //console.log(points);
  16381. break;
  16382. } // end switch
  16383. }
  16384. // Normalize to remove the closing point by default.
  16385. var lastPoint = points[ points.length - 1];
  16386. var EPSILON = 0.0000000001;
  16387. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  16388. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  16389. points.splice( points.length - 1, 1);
  16390. if ( closedPath ) {
  16391. points.push( points[ 0 ] );
  16392. }
  16393. return points;
  16394. };
  16395. // Breaks path into shapes
  16396. THREE.Path.prototype.toShapes = function() {
  16397. var i, il, item, action, args;
  16398. var subPaths = [], lastPath = new THREE.Path();
  16399. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16400. item = this.actions[ i ];
  16401. args = item.args;
  16402. action = item.action;
  16403. if ( action == THREE.PathActions.MOVE_TO ) {
  16404. if ( lastPath.actions.length != 0 ) {
  16405. subPaths.push( lastPath );
  16406. lastPath = new THREE.Path();
  16407. }
  16408. }
  16409. lastPath[ action ].apply( lastPath, args );
  16410. }
  16411. if ( lastPath.actions.length != 0 ) {
  16412. subPaths.push( lastPath );
  16413. }
  16414. // console.log(subPaths);
  16415. if ( subPaths.length == 0 ) return [];
  16416. var tmpPath, tmpShape, shapes = [];
  16417. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  16418. // console.log("Holes first", holesFirst);
  16419. if ( subPaths.length == 1) {
  16420. tmpPath = subPaths[0];
  16421. tmpShape = new THREE.Shape();
  16422. tmpShape.actions = tmpPath.actions;
  16423. tmpShape.curves = tmpPath.curves;
  16424. shapes.push( tmpShape );
  16425. return shapes;
  16426. };
  16427. if ( holesFirst ) {
  16428. tmpShape = new THREE.Shape();
  16429. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16430. tmpPath = subPaths[ i ];
  16431. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16432. tmpShape.actions = tmpPath.actions;
  16433. tmpShape.curves = tmpPath.curves;
  16434. shapes.push( tmpShape );
  16435. tmpShape = new THREE.Shape();
  16436. //console.log('cw', i);
  16437. } else {
  16438. tmpShape.holes.push( tmpPath );
  16439. //console.log('ccw', i);
  16440. }
  16441. }
  16442. } else {
  16443. // Shapes first
  16444. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16445. tmpPath = subPaths[ i ];
  16446. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16447. if ( tmpShape ) shapes.push( tmpShape );
  16448. tmpShape = new THREE.Shape();
  16449. tmpShape.actions = tmpPath.actions;
  16450. tmpShape.curves = tmpPath.curves;
  16451. } else {
  16452. tmpShape.holes.push( tmpPath );
  16453. }
  16454. }
  16455. shapes.push( tmpShape );
  16456. }
  16457. //console.log("shape", shapes);
  16458. return shapes;
  16459. };
  16460. /**
  16461. * @author zz85 / http://www.lab4games.net/zz85/blog
  16462. * Defines a 2d shape plane using paths.
  16463. **/
  16464. // STEP 1 Create a path.
  16465. // STEP 2 Turn path into shape.
  16466. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  16467. // STEP 3a - Extract points from each shape, turn to vertices
  16468. // STEP 3b - Triangulate each shape, add faces.
  16469. THREE.Shape = function ( ) {
  16470. THREE.Path.apply( this, arguments );
  16471. this.holes = [];
  16472. };
  16473. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  16474. // Convenience method to return ExtrudeGeometry
  16475. THREE.Shape.prototype.extrude = function ( options ) {
  16476. var extruded = new THREE.ExtrudeGeometry( this, options );
  16477. return extruded;
  16478. };
  16479. // Convenience method to return ShapeGeometry
  16480. THREE.Shape.prototype.makeGeometry = function ( options ) {
  16481. var geometry = new THREE.ShapeGeometry( this, options );
  16482. return geometry;
  16483. };
  16484. // Get points of holes
  16485. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  16486. var i, il = this.holes.length, holesPts = [];
  16487. for ( i = 0; i < il; i ++ ) {
  16488. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  16489. }
  16490. return holesPts;
  16491. };
  16492. // Get points of holes (spaced by regular distance)
  16493. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  16494. var i, il = this.holes.length, holesPts = [];
  16495. for ( i = 0; i < il; i ++ ) {
  16496. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  16497. }
  16498. return holesPts;
  16499. };
  16500. // Get points of shape and holes (keypoints based on segments parameter)
  16501. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  16502. return {
  16503. shape: this.getTransformedPoints( divisions ),
  16504. holes: this.getPointsHoles( divisions )
  16505. };
  16506. };
  16507. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  16508. if (this.useSpacedPoints) {
  16509. return this.extractAllSpacedPoints(divisions);
  16510. }
  16511. return this.extractAllPoints(divisions);
  16512. };
  16513. //
  16514. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  16515. //
  16516. // return {
  16517. //
  16518. // shape: this.transform( bend, divisions ),
  16519. // holes: this.getPointsHoles( divisions, bend )
  16520. //
  16521. // };
  16522. //
  16523. // };
  16524. // Get points of shape and holes (spaced by regular distance)
  16525. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  16526. return {
  16527. shape: this.getTransformedSpacedPoints( divisions ),
  16528. holes: this.getSpacedPointsHoles( divisions )
  16529. };
  16530. };
  16531. /**************************************************************
  16532. * Utils
  16533. **************************************************************/
  16534. THREE.Shape.Utils = {
  16535. /*
  16536. contour - array of vector2 for contour
  16537. holes - array of array of vector2
  16538. */
  16539. removeHoles: function ( contour, holes ) {
  16540. var shape = contour.concat(); // work on this shape
  16541. var allpoints = shape.concat();
  16542. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  16543. var prevShapeVert, nextShapeVert,
  16544. prevHoleVert, nextHoleVert,
  16545. holeIndex, shapeIndex,
  16546. shapeId, shapeGroup,
  16547. h, h2,
  16548. hole, shortest, d,
  16549. p, pts1, pts2,
  16550. tmpShape1, tmpShape2,
  16551. tmpHole1, tmpHole2,
  16552. verts = [];
  16553. for ( h = 0; h < holes.length; h ++ ) {
  16554. hole = holes[ h ];
  16555. /*
  16556. shapeholes[ h ].concat(); // preserves original
  16557. holes.push( hole );
  16558. */
  16559. Array.prototype.push.apply( allpoints, hole );
  16560. shortest = Number.POSITIVE_INFINITY;
  16561. // Find the shortest pair of pts between shape and hole
  16562. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  16563. // Using distanceToSquared() intead of distanceTo() should speed a little
  16564. // since running square roots operations are reduced.
  16565. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  16566. pts1 = hole[ h2 ];
  16567. var dist = [];
  16568. for ( p = 0; p < shape.length; p++ ) {
  16569. pts2 = shape[ p ];
  16570. d = pts1.distanceToSquared( pts2 );
  16571. dist.push( d );
  16572. if ( d < shortest ) {
  16573. shortest = d;
  16574. holeIndex = h2;
  16575. shapeIndex = p;
  16576. }
  16577. }
  16578. }
  16579. //console.log("shortest", shortest, dist);
  16580. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16581. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16582. var areaapts = [
  16583. hole[ holeIndex ],
  16584. shape[ shapeIndex ],
  16585. shape[ prevShapeVert ]
  16586. ];
  16587. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  16588. var areabpts = [
  16589. hole[ holeIndex ],
  16590. hole[ prevHoleVert ],
  16591. shape[ shapeIndex ]
  16592. ];
  16593. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  16594. var shapeOffset = 1;
  16595. var holeOffset = -1;
  16596. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  16597. shapeIndex += shapeOffset;
  16598. holeIndex += holeOffset;
  16599. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16600. shapeIndex %= shape.length;
  16601. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16602. holeIndex %= hole.length;
  16603. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16604. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16605. areaapts = [
  16606. hole[ holeIndex ],
  16607. shape[ shapeIndex ],
  16608. shape[ prevShapeVert ]
  16609. ];
  16610. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  16611. areabpts = [
  16612. hole[ holeIndex ],
  16613. hole[ prevHoleVert ],
  16614. shape[ shapeIndex ]
  16615. ];
  16616. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  16617. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  16618. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  16619. // In case areas are not correct.
  16620. //console.log("USE THIS");
  16621. shapeIndex = oldShapeIndex;
  16622. holeIndex = oldHoleIndex ;
  16623. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16624. shapeIndex %= shape.length;
  16625. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16626. holeIndex %= hole.length;
  16627. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16628. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16629. } else {
  16630. //console.log("USE THAT ")
  16631. }
  16632. tmpShape1 = shape.slice( 0, shapeIndex );
  16633. tmpShape2 = shape.slice( shapeIndex );
  16634. tmpHole1 = hole.slice( holeIndex );
  16635. tmpHole2 = hole.slice( 0, holeIndex );
  16636. // Should check orders here again?
  16637. var trianglea = [
  16638. hole[ holeIndex ],
  16639. shape[ shapeIndex ],
  16640. shape[ prevShapeVert ]
  16641. ];
  16642. var triangleb = [
  16643. hole[ holeIndex ] ,
  16644. hole[ prevHoleVert ],
  16645. shape[ shapeIndex ]
  16646. ];
  16647. verts.push( trianglea );
  16648. verts.push( triangleb );
  16649. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  16650. }
  16651. return {
  16652. shape:shape, /* shape with no holes */
  16653. isolatedPts: verts, /* isolated faces */
  16654. allpoints: allpoints
  16655. }
  16656. },
  16657. triangulateShape: function ( contour, holes ) {
  16658. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  16659. var shape = shapeWithoutHoles.shape,
  16660. allpoints = shapeWithoutHoles.allpoints,
  16661. isolatedPts = shapeWithoutHoles.isolatedPts;
  16662. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  16663. // 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.
  16664. //console.log( "triangles",triangles, triangles.length );
  16665. //console.log( "allpoints",allpoints, allpoints.length );
  16666. var i, il, f, face,
  16667. key, index,
  16668. allPointsMap = {},
  16669. isolatedPointsMap = {};
  16670. // prepare all points map
  16671. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  16672. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  16673. if ( allPointsMap[ key ] !== undefined ) {
  16674. console.log( "Duplicate point", key );
  16675. }
  16676. allPointsMap[ key ] = i;
  16677. }
  16678. // check all face vertices against all points map
  16679. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  16680. face = triangles[ i ];
  16681. for ( f = 0; f < 3; f ++ ) {
  16682. key = face[ f ].x + ":" + face[ f ].y;
  16683. index = allPointsMap[ key ];
  16684. if ( index !== undefined ) {
  16685. face[ f ] = index;
  16686. }
  16687. }
  16688. }
  16689. // check isolated points vertices against all points map
  16690. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  16691. face = isolatedPts[ i ];
  16692. for ( f = 0; f < 3; f ++ ) {
  16693. key = face[ f ].x + ":" + face[ f ].y;
  16694. index = allPointsMap[ key ];
  16695. if ( index !== undefined ) {
  16696. face[ f ] = index;
  16697. }
  16698. }
  16699. }
  16700. return triangles.concat( isolatedPts );
  16701. }, // end triangulate shapes
  16702. /*
  16703. triangulate2 : function( pts, holes ) {
  16704. // For use with Poly2Tri.js
  16705. var allpts = pts.concat();
  16706. var shape = [];
  16707. for (var p in pts) {
  16708. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  16709. }
  16710. var swctx = new js.poly2tri.SweepContext(shape);
  16711. for (var h in holes) {
  16712. var aHole = holes[h];
  16713. var newHole = []
  16714. for (i in aHole) {
  16715. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  16716. allpts.push(aHole[i]);
  16717. }
  16718. swctx.AddHole(newHole);
  16719. }
  16720. var find;
  16721. var findIndexForPt = function (pt) {
  16722. find = new THREE.Vector2(pt.x, pt.y);
  16723. var p;
  16724. for (p=0, pl = allpts.length; p<pl; p++) {
  16725. if (allpts[p].equals(find)) return p;
  16726. }
  16727. return -1;
  16728. };
  16729. // triangulate
  16730. js.poly2tri.sweep.Triangulate(swctx);
  16731. var triangles = swctx.GetTriangles();
  16732. var tr ;
  16733. var facesPts = [];
  16734. for (var t in triangles) {
  16735. tr = triangles[t];
  16736. facesPts.push([
  16737. findIndexForPt(tr.GetPoint(0)),
  16738. findIndexForPt(tr.GetPoint(1)),
  16739. findIndexForPt(tr.GetPoint(2))
  16740. ]);
  16741. }
  16742. // console.log(facesPts);
  16743. // console.log("triangles", triangles.length, triangles);
  16744. // Returns array of faces with 3 element each
  16745. return facesPts;
  16746. },
  16747. */
  16748. isClockWise: function ( pts ) {
  16749. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  16750. },
  16751. // Bezier Curves formulas obtained from
  16752. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  16753. // Quad Bezier Functions
  16754. b2p0: function ( t, p ) {
  16755. var k = 1 - t;
  16756. return k * k * p;
  16757. },
  16758. b2p1: function ( t, p ) {
  16759. return 2 * ( 1 - t ) * t * p;
  16760. },
  16761. b2p2: function ( t, p ) {
  16762. return t * t * p;
  16763. },
  16764. b2: function ( t, p0, p1, p2 ) {
  16765. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  16766. },
  16767. // Cubic Bezier Functions
  16768. b3p0: function ( t, p ) {
  16769. var k = 1 - t;
  16770. return k * k * k * p;
  16771. },
  16772. b3p1: function ( t, p ) {
  16773. var k = 1 - t;
  16774. return 3 * k * k * t * p;
  16775. },
  16776. b3p2: function ( t, p ) {
  16777. var k = 1 - t;
  16778. return 3 * k * t * t * p;
  16779. },
  16780. b3p3: function ( t, p ) {
  16781. return t * t * t * p;
  16782. },
  16783. b3: function ( t, p0, p1, p2, p3 ) {
  16784. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  16785. }
  16786. };
  16787. /**
  16788. * @author mikael emtinger / http://gomo.se/
  16789. */
  16790. THREE.AnimationHandler = (function() {
  16791. var playing = [];
  16792. var library = {};
  16793. var that = {};
  16794. //--- update ---
  16795. that.update = function( deltaTimeMS ) {
  16796. for( var i = 0; i < playing.length; i ++ )
  16797. playing[ i ].update( deltaTimeMS );
  16798. };
  16799. //--- add ---
  16800. that.addToUpdate = function( animation ) {
  16801. if ( playing.indexOf( animation ) === -1 )
  16802. playing.push( animation );
  16803. };
  16804. //--- remove ---
  16805. that.removeFromUpdate = function( animation ) {
  16806. var index = playing.indexOf( animation );
  16807. if( index !== -1 )
  16808. playing.splice( index, 1 );
  16809. };
  16810. //--- add ---
  16811. that.add = function( data ) {
  16812. if ( library[ data.name ] !== undefined )
  16813. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  16814. library[ data.name ] = data;
  16815. initData( data );
  16816. };
  16817. //--- get ---
  16818. that.get = function( name ) {
  16819. if ( typeof name === "string" ) {
  16820. if ( library[ name ] ) {
  16821. return library[ name ];
  16822. } else {
  16823. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  16824. return null;
  16825. }
  16826. } else {
  16827. // todo: add simple tween library
  16828. }
  16829. };
  16830. //--- parse ---
  16831. that.parse = function( root ) {
  16832. // setup hierarchy
  16833. var hierarchy = [];
  16834. if ( root instanceof THREE.SkinnedMesh ) {
  16835. for( var b = 0; b < root.bones.length; b++ ) {
  16836. hierarchy.push( root.bones[ b ] );
  16837. }
  16838. } else {
  16839. parseRecurseHierarchy( root, hierarchy );
  16840. }
  16841. return hierarchy;
  16842. };
  16843. var parseRecurseHierarchy = function( root, hierarchy ) {
  16844. hierarchy.push( root );
  16845. for( var c = 0; c < root.children.length; c++ )
  16846. parseRecurseHierarchy( root.children[ c ], hierarchy );
  16847. }
  16848. //--- init data ---
  16849. var initData = function( data ) {
  16850. if( data.initialized === true )
  16851. return;
  16852. // loop through all keys
  16853. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  16854. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16855. // remove minus times
  16856. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  16857. data.hierarchy[ h ].keys[ k ].time = 0;
  16858. // create quaternions
  16859. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  16860. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  16861. var quat = data.hierarchy[ h ].keys[ k ].rot;
  16862. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  16863. }
  16864. }
  16865. // prepare morph target keys
  16866. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  16867. // get all used
  16868. var usedMorphTargets = {};
  16869. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16870. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16871. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  16872. usedMorphTargets[ morphTargetName ] = -1;
  16873. }
  16874. }
  16875. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  16876. // set all used on all frames
  16877. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16878. var influences = {};
  16879. for ( var morphTargetName in usedMorphTargets ) {
  16880. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16881. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  16882. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  16883. break;
  16884. }
  16885. }
  16886. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  16887. influences[ morphTargetName ] = 0;
  16888. }
  16889. }
  16890. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  16891. }
  16892. }
  16893. // remove all keys that are on the same time
  16894. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16895. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  16896. data.hierarchy[ h ].keys.splice( k, 1 );
  16897. k --;
  16898. }
  16899. }
  16900. // set index
  16901. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16902. data.hierarchy[ h ].keys[ k ].index = k;
  16903. }
  16904. }
  16905. // JIT
  16906. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  16907. data.JIT = {};
  16908. data.JIT.hierarchy = [];
  16909. for( var h = 0; h < data.hierarchy.length; h ++ )
  16910. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  16911. // done
  16912. data.initialized = true;
  16913. };
  16914. // interpolation types
  16915. that.LINEAR = 0;
  16916. that.CATMULLROM = 1;
  16917. that.CATMULLROM_FORWARD = 2;
  16918. return that;
  16919. }());
  16920. /**
  16921. * @author mikael emtinger / http://gomo.se/
  16922. * @author mrdoob / http://mrdoob.com/
  16923. * @author alteredq / http://alteredqualia.com/
  16924. */
  16925. THREE.Animation = function ( root, name, interpolationType ) {
  16926. this.root = root;
  16927. this.data = THREE.AnimationHandler.get( name );
  16928. this.hierarchy = THREE.AnimationHandler.parse( root );
  16929. this.currentTime = 0;
  16930. this.timeScale = 1;
  16931. this.isPlaying = false;
  16932. this.isPaused = true;
  16933. this.loop = true;
  16934. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  16935. this.points = [];
  16936. this.target = new THREE.Vector3();
  16937. };
  16938. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  16939. if ( this.isPlaying === false ) {
  16940. this.isPlaying = true;
  16941. this.loop = loop !== undefined ? loop : true;
  16942. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  16943. // reset key cache
  16944. var h, hl = this.hierarchy.length,
  16945. object;
  16946. for ( h = 0; h < hl; h ++ ) {
  16947. object = this.hierarchy[ h ];
  16948. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16949. object.useQuaternion = true;
  16950. }
  16951. object.matrixAutoUpdate = true;
  16952. if ( object.animationCache === undefined ) {
  16953. object.animationCache = {};
  16954. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  16955. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  16956. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  16957. }
  16958. var prevKey = object.animationCache.prevKey;
  16959. var nextKey = object.animationCache.nextKey;
  16960. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  16961. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  16962. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  16963. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  16964. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  16965. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  16966. }
  16967. this.update( 0 );
  16968. }
  16969. this.isPaused = false;
  16970. THREE.AnimationHandler.addToUpdate( this );
  16971. };
  16972. THREE.Animation.prototype.pause = function() {
  16973. if ( this.isPaused === true ) {
  16974. THREE.AnimationHandler.addToUpdate( this );
  16975. } else {
  16976. THREE.AnimationHandler.removeFromUpdate( this );
  16977. }
  16978. this.isPaused = !this.isPaused;
  16979. };
  16980. THREE.Animation.prototype.stop = function() {
  16981. this.isPlaying = false;
  16982. this.isPaused = false;
  16983. THREE.AnimationHandler.removeFromUpdate( this );
  16984. };
  16985. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  16986. // early out
  16987. if ( this.isPlaying === false ) return;
  16988. // vars
  16989. var types = [ "pos", "rot", "scl" ];
  16990. var type;
  16991. var scale;
  16992. var vector;
  16993. var prevXYZ, nextXYZ;
  16994. var prevKey, nextKey;
  16995. var object;
  16996. var animationCache;
  16997. var frame;
  16998. var JIThierarchy = this.data.JIT.hierarchy;
  16999. var currentTime, unloopedCurrentTime;
  17000. var currentPoint, forwardPoint, angle;
  17001. this.currentTime += deltaTimeMS * this.timeScale;
  17002. unloopedCurrentTime = this.currentTime;
  17003. currentTime = this.currentTime = this.currentTime % this.data.length;
  17004. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17005. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17006. object = this.hierarchy[ h ];
  17007. animationCache = object.animationCache;
  17008. // loop through pos/rot/scl
  17009. for ( var t = 0; t < 3; t ++ ) {
  17010. // get keys
  17011. type = types[ t ];
  17012. prevKey = animationCache.prevKey[ type ];
  17013. nextKey = animationCache.nextKey[ type ];
  17014. // switch keys?
  17015. if ( nextKey.time <= unloopedCurrentTime ) {
  17016. // did we loop?
  17017. if ( currentTime < unloopedCurrentTime ) {
  17018. if ( this.loop ) {
  17019. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17020. nextKey = this.getNextKeyWith( type, h, 1 );
  17021. while( nextKey.time < currentTime ) {
  17022. prevKey = nextKey;
  17023. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17024. }
  17025. } else {
  17026. this.stop();
  17027. return;
  17028. }
  17029. } else {
  17030. do {
  17031. prevKey = nextKey;
  17032. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17033. } while( nextKey.time < currentTime )
  17034. }
  17035. animationCache.prevKey[ type ] = prevKey;
  17036. animationCache.nextKey[ type ] = nextKey;
  17037. }
  17038. object.matrixAutoUpdate = true;
  17039. object.matrixWorldNeedsUpdate = true;
  17040. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17041. prevXYZ = prevKey[ type ];
  17042. nextXYZ = nextKey[ type ];
  17043. // check scale error
  17044. if ( scale < 0 || scale > 1 ) {
  17045. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17046. scale = scale < 0 ? 0 : 1;
  17047. }
  17048. // interpolate
  17049. if ( type === "pos" ) {
  17050. vector = object.position;
  17051. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17052. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17053. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17054. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17055. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17056. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17057. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17058. this.points[ 1 ] = prevXYZ;
  17059. this.points[ 2 ] = nextXYZ;
  17060. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17061. scale = scale * 0.33 + 0.33;
  17062. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17063. vector.x = currentPoint[ 0 ];
  17064. vector.y = currentPoint[ 1 ];
  17065. vector.z = currentPoint[ 2 ];
  17066. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17067. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17068. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17069. this.target.subSelf( vector );
  17070. this.target.y = 0;
  17071. this.target.normalize();
  17072. angle = Math.atan2( this.target.x, this.target.z );
  17073. object.rotation.set( 0, angle, 0 );
  17074. }
  17075. }
  17076. } else if ( type === "rot" ) {
  17077. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17078. } else if ( type === "scl" ) {
  17079. vector = object.scale;
  17080. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17081. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17082. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17083. }
  17084. }
  17085. }
  17086. };
  17087. // Catmull-Rom spline
  17088. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17089. var c = [], v3 = [],
  17090. point, intPoint, weight, w2, w3,
  17091. pa, pb, pc, pd;
  17092. point = ( points.length - 1 ) * scale;
  17093. intPoint = Math.floor( point );
  17094. weight = point - intPoint;
  17095. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17096. c[ 1 ] = intPoint;
  17097. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17098. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17099. pa = points[ c[ 0 ] ];
  17100. pb = points[ c[ 1 ] ];
  17101. pc = points[ c[ 2 ] ];
  17102. pd = points[ c[ 3 ] ];
  17103. w2 = weight * weight;
  17104. w3 = weight * w2;
  17105. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17106. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17107. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17108. return v3;
  17109. };
  17110. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17111. var v0 = ( p2 - p0 ) * 0.5,
  17112. v1 = ( p3 - p1 ) * 0.5;
  17113. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17114. };
  17115. // Get next key with
  17116. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17117. var keys = this.data.hierarchy[ h ].keys;
  17118. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17119. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17120. key = key < keys.length - 1 ? key : keys.length - 1;
  17121. } else {
  17122. key = key % keys.length;
  17123. }
  17124. for ( ; key < keys.length; key++ ) {
  17125. if ( keys[ key ][ type ] !== undefined ) {
  17126. return keys[ key ];
  17127. }
  17128. }
  17129. return this.data.hierarchy[ h ].keys[ 0 ];
  17130. };
  17131. // Get previous key with
  17132. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17133. var keys = this.data.hierarchy[ h ].keys;
  17134. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17135. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17136. key = key > 0 ? key : 0;
  17137. } else {
  17138. key = key >= 0 ? key : key + keys.length;
  17139. }
  17140. for ( ; key >= 0; key -- ) {
  17141. if ( keys[ key ][ type ] !== undefined ) {
  17142. return keys[ key ];
  17143. }
  17144. }
  17145. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17146. };
  17147. /**
  17148. * @author mikael emtinger / http://gomo.se/
  17149. * @author mrdoob / http://mrdoob.com/
  17150. * @author alteredq / http://alteredqualia.com/
  17151. * @author khang duong
  17152. * @author erik kitson
  17153. */
  17154. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17155. this.root = root;
  17156. this.data = THREE.AnimationHandler.get( data );
  17157. this.hierarchy = THREE.AnimationHandler.parse( root );
  17158. this.currentTime = 0;
  17159. this.timeScale = 0.001;
  17160. this.isPlaying = false;
  17161. this.isPaused = true;
  17162. this.loop = true;
  17163. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17164. // initialize to first keyframes
  17165. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17166. var keys = this.data.hierarchy[h].keys,
  17167. sids = this.data.hierarchy[h].sids,
  17168. obj = this.hierarchy[h];
  17169. if ( keys.length && sids ) {
  17170. for ( var s = 0; s < sids.length; s++ ) {
  17171. var sid = sids[ s ],
  17172. next = this.getNextKeyWith( sid, h, 0 );
  17173. if ( next ) {
  17174. next.apply( sid );
  17175. }
  17176. }
  17177. obj.matrixAutoUpdate = false;
  17178. this.data.hierarchy[h].node.updateMatrix();
  17179. obj.matrixWorldNeedsUpdate = true;
  17180. }
  17181. }
  17182. };
  17183. // Play
  17184. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  17185. if( !this.isPlaying ) {
  17186. this.isPlaying = true;
  17187. this.loop = loop !== undefined ? loop : true;
  17188. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17189. this.startTimeMs = startTimeMS;
  17190. this.startTime = 10000000;
  17191. this.endTime = -this.startTime;
  17192. // reset key cache
  17193. var h, hl = this.hierarchy.length,
  17194. object,
  17195. node;
  17196. for ( h = 0; h < hl; h++ ) {
  17197. object = this.hierarchy[ h ];
  17198. node = this.data.hierarchy[ h ];
  17199. object.useQuaternion = true;
  17200. if ( node.animationCache === undefined ) {
  17201. node.animationCache = {};
  17202. node.animationCache.prevKey = null;
  17203. node.animationCache.nextKey = null;
  17204. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17205. }
  17206. var keys = this.data.hierarchy[h].keys;
  17207. if (keys.length) {
  17208. node.animationCache.prevKey = keys[ 0 ];
  17209. node.animationCache.nextKey = keys[ 1 ];
  17210. this.startTime = Math.min( keys[0].time, this.startTime );
  17211. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17212. }
  17213. }
  17214. this.update( 0 );
  17215. }
  17216. this.isPaused = false;
  17217. THREE.AnimationHandler.addToUpdate( this );
  17218. };
  17219. // Pause
  17220. THREE.KeyFrameAnimation.prototype.pause = function() {
  17221. if( this.isPaused ) {
  17222. THREE.AnimationHandler.addToUpdate( this );
  17223. } else {
  17224. THREE.AnimationHandler.removeFromUpdate( this );
  17225. }
  17226. this.isPaused = !this.isPaused;
  17227. };
  17228. // Stop
  17229. THREE.KeyFrameAnimation.prototype.stop = function() {
  17230. this.isPlaying = false;
  17231. this.isPaused = false;
  17232. THREE.AnimationHandler.removeFromUpdate( this );
  17233. // reset JIT matrix and remove cache
  17234. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  17235. var obj = this.hierarchy[ h ];
  17236. var node = this.data.hierarchy[ h ];
  17237. if ( node.animationCache !== undefined ) {
  17238. var original = node.animationCache.originalMatrix;
  17239. if( obj instanceof THREE.Bone ) {
  17240. original.copy( obj.skinMatrix );
  17241. obj.skinMatrix = original;
  17242. } else {
  17243. original.copy( obj.matrix );
  17244. obj.matrix = original;
  17245. }
  17246. delete node.animationCache;
  17247. }
  17248. }
  17249. };
  17250. // Update
  17251. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  17252. // early out
  17253. if( !this.isPlaying ) return;
  17254. // vars
  17255. var prevKey, nextKey;
  17256. var object;
  17257. var node;
  17258. var frame;
  17259. var JIThierarchy = this.data.JIT.hierarchy;
  17260. var currentTime, unloopedCurrentTime;
  17261. var looped;
  17262. // update
  17263. this.currentTime += deltaTimeMS * this.timeScale;
  17264. unloopedCurrentTime = this.currentTime;
  17265. currentTime = this.currentTime = this.currentTime % this.data.length;
  17266. // if looped around, the current time should be based on the startTime
  17267. if ( currentTime < this.startTimeMs ) {
  17268. currentTime = this.currentTime = this.startTimeMs + currentTime;
  17269. }
  17270. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17271. looped = currentTime < unloopedCurrentTime;
  17272. if ( looped && !this.loop ) {
  17273. // Set the animation to the last keyframes and stop
  17274. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17275. var keys = this.data.hierarchy[h].keys,
  17276. sids = this.data.hierarchy[h].sids,
  17277. end = keys.length-1,
  17278. obj = this.hierarchy[h];
  17279. if ( keys.length ) {
  17280. for ( var s = 0; s < sids.length; s++ ) {
  17281. var sid = sids[ s ],
  17282. prev = this.getPrevKeyWith( sid, h, end );
  17283. if ( prev ) {
  17284. prev.apply( sid );
  17285. }
  17286. }
  17287. this.data.hierarchy[h].node.updateMatrix();
  17288. obj.matrixWorldNeedsUpdate = true;
  17289. }
  17290. }
  17291. this.stop();
  17292. return;
  17293. }
  17294. // check pre-infinity
  17295. if ( currentTime < this.startTime ) {
  17296. return;
  17297. }
  17298. // update
  17299. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17300. object = this.hierarchy[ h ];
  17301. node = this.data.hierarchy[ h ];
  17302. var keys = node.keys,
  17303. animationCache = node.animationCache;
  17304. // use JIT?
  17305. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  17306. if( object instanceof THREE.Bone ) {
  17307. object.skinMatrix = JIThierarchy[ h ][ frame ];
  17308. object.matrixWorldNeedsUpdate = false;
  17309. } else {
  17310. object.matrix = JIThierarchy[ h ][ frame ];
  17311. object.matrixWorldNeedsUpdate = true;
  17312. }
  17313. // use interpolation
  17314. } else if ( keys.length ) {
  17315. // make sure so original matrix and not JIT matrix is set
  17316. if ( this.JITCompile && animationCache ) {
  17317. if( object instanceof THREE.Bone ) {
  17318. object.skinMatrix = animationCache.originalMatrix;
  17319. } else {
  17320. object.matrix = animationCache.originalMatrix;
  17321. }
  17322. }
  17323. prevKey = animationCache.prevKey;
  17324. nextKey = animationCache.nextKey;
  17325. if ( prevKey && nextKey ) {
  17326. // switch keys?
  17327. if ( nextKey.time <= unloopedCurrentTime ) {
  17328. // did we loop?
  17329. if ( looped && this.loop ) {
  17330. prevKey = keys[ 0 ];
  17331. nextKey = keys[ 1 ];
  17332. while ( nextKey.time < currentTime ) {
  17333. prevKey = nextKey;
  17334. nextKey = keys[ prevKey.index + 1 ];
  17335. }
  17336. } else if ( !looped ) {
  17337. var lastIndex = keys.length - 1;
  17338. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  17339. prevKey = nextKey;
  17340. nextKey = keys[ prevKey.index + 1 ];
  17341. }
  17342. }
  17343. animationCache.prevKey = prevKey;
  17344. animationCache.nextKey = nextKey;
  17345. }
  17346. if(nextKey.time >= currentTime)
  17347. prevKey.interpolate( nextKey, currentTime );
  17348. else
  17349. prevKey.interpolate( nextKey, nextKey.time);
  17350. }
  17351. this.data.hierarchy[h].node.updateMatrix();
  17352. object.matrixWorldNeedsUpdate = true;
  17353. }
  17354. }
  17355. // update JIT?
  17356. if ( this.JITCompile ) {
  17357. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  17358. this.hierarchy[ 0 ].updateMatrixWorld( true );
  17359. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  17360. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  17361. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  17362. } else {
  17363. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  17364. }
  17365. }
  17366. }
  17367. }
  17368. };
  17369. // Get next key with
  17370. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  17371. var keys = this.data.hierarchy[ h ].keys;
  17372. key = key % keys.length;
  17373. for ( ; key < keys.length; key++ ) {
  17374. if ( keys[ key ].hasTarget( sid ) ) {
  17375. return keys[ key ];
  17376. }
  17377. }
  17378. return keys[ 0 ];
  17379. };
  17380. // Get previous key with
  17381. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  17382. var keys = this.data.hierarchy[ h ].keys;
  17383. key = key >= 0 ? key : key + keys.length;
  17384. for ( ; key >= 0; key-- ) {
  17385. if ( keys[ key ].hasTarget( sid ) ) {
  17386. return keys[ key ];
  17387. }
  17388. }
  17389. return keys[ keys.length - 1 ];
  17390. };
  17391. /**
  17392. * Camera for rendering cube maps
  17393. * - renders scene into axis-aligned cube
  17394. *
  17395. * @author alteredq / http://alteredqualia.com/
  17396. */
  17397. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  17398. THREE.Object3D.call( this );
  17399. var fov = 90, aspect = 1;
  17400. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17401. cameraPX.up.set( 0, -1, 0 );
  17402. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  17403. this.add( cameraPX );
  17404. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17405. cameraNX.up.set( 0, -1, 0 );
  17406. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  17407. this.add( cameraNX );
  17408. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17409. cameraPY.up.set( 0, 0, 1 );
  17410. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  17411. this.add( cameraPY );
  17412. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17413. cameraNY.up.set( 0, 0, -1 );
  17414. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  17415. this.add( cameraNY );
  17416. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17417. cameraPZ.up.set( 0, -1, 0 );
  17418. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  17419. this.add( cameraPZ );
  17420. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17421. cameraNZ.up.set( 0, -1, 0 );
  17422. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  17423. this.add( cameraNZ );
  17424. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  17425. this.updateCubeMap = function ( renderer, scene ) {
  17426. var renderTarget = this.renderTarget;
  17427. var generateMipmaps = renderTarget.generateMipmaps;
  17428. renderTarget.generateMipmaps = false;
  17429. renderTarget.activeCubeFace = 0;
  17430. renderer.render( scene, cameraPX, renderTarget );
  17431. renderTarget.activeCubeFace = 1;
  17432. renderer.render( scene, cameraNX, renderTarget );
  17433. renderTarget.activeCubeFace = 2;
  17434. renderer.render( scene, cameraPY, renderTarget );
  17435. renderTarget.activeCubeFace = 3;
  17436. renderer.render( scene, cameraNY, renderTarget );
  17437. renderTarget.activeCubeFace = 4;
  17438. renderer.render( scene, cameraPZ, renderTarget );
  17439. renderTarget.generateMipmaps = generateMipmaps;
  17440. renderTarget.activeCubeFace = 5;
  17441. renderer.render( scene, cameraNZ, renderTarget );
  17442. };
  17443. };
  17444. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  17445. /*
  17446. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  17447. *
  17448. * A general perpose camera, for setting FOV, Lens Focal Length,
  17449. * and switching between perspective and orthographic views easily.
  17450. * Use this only if you do not wish to manage
  17451. * both a Orthographic and Perspective Camera
  17452. *
  17453. */
  17454. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  17455. THREE.Camera.call( this );
  17456. this.fov = fov;
  17457. this.left = -width / 2;
  17458. this.right = width / 2
  17459. this.top = height / 2;
  17460. this.bottom = -height / 2;
  17461. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  17462. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  17463. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  17464. this.zoom = 1;
  17465. this.toPerspective();
  17466. var aspect = width/height;
  17467. };
  17468. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  17469. THREE.CombinedCamera.prototype.toPerspective = function () {
  17470. // Switches to the Perspective Camera
  17471. this.near = this.cameraP.near;
  17472. this.far = this.cameraP.far;
  17473. this.cameraP.fov = this.fov / this.zoom ;
  17474. this.cameraP.updateProjectionMatrix();
  17475. this.projectionMatrix = this.cameraP.projectionMatrix;
  17476. this.inPerspectiveMode = true;
  17477. this.inOrthographicMode = false;
  17478. };
  17479. THREE.CombinedCamera.prototype.toOrthographic = function () {
  17480. // Switches to the Orthographic camera estimating viewport from Perspective
  17481. var fov = this.fov;
  17482. var aspect = this.cameraP.aspect;
  17483. var near = this.cameraP.near;
  17484. var far = this.cameraP.far;
  17485. // The size that we set is the mid plane of the viewing frustum
  17486. var hyperfocus = ( near + far ) / 2;
  17487. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  17488. var planeHeight = 2 * halfHeight;
  17489. var planeWidth = planeHeight * aspect;
  17490. var halfWidth = planeWidth / 2;
  17491. halfHeight /= this.zoom;
  17492. halfWidth /= this.zoom;
  17493. this.cameraO.left = -halfWidth;
  17494. this.cameraO.right = halfWidth;
  17495. this.cameraO.top = halfHeight;
  17496. this.cameraO.bottom = -halfHeight;
  17497. // this.cameraO.left = -farHalfWidth;
  17498. // this.cameraO.right = farHalfWidth;
  17499. // this.cameraO.top = farHalfHeight;
  17500. // this.cameraO.bottom = -farHalfHeight;
  17501. // this.cameraO.left = this.left / this.zoom;
  17502. // this.cameraO.right = this.right / this.zoom;
  17503. // this.cameraO.top = this.top / this.zoom;
  17504. // this.cameraO.bottom = this.bottom / this.zoom;
  17505. this.cameraO.updateProjectionMatrix();
  17506. this.near = this.cameraO.near;
  17507. this.far = this.cameraO.far;
  17508. this.projectionMatrix = this.cameraO.projectionMatrix;
  17509. this.inPerspectiveMode = false;
  17510. this.inOrthographicMode = true;
  17511. };
  17512. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  17513. this.cameraP.aspect = width / height;
  17514. this.left = -width / 2;
  17515. this.right = width / 2
  17516. this.top = height / 2;
  17517. this.bottom = -height / 2;
  17518. };
  17519. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  17520. this.fov = fov;
  17521. if ( this.inPerspectiveMode ) {
  17522. this.toPerspective();
  17523. } else {
  17524. this.toOrthographic();
  17525. }
  17526. };
  17527. // For mantaining similar API with PerspectiveCamera
  17528. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  17529. if ( this.inPerspectiveMode ) {
  17530. this.toPerspective();
  17531. } else {
  17532. this.toPerspective();
  17533. this.toOrthographic();
  17534. }
  17535. };
  17536. /*
  17537. * Uses Focal Length (in mm) to estimate and set FOV
  17538. * 35mm (fullframe) camera is used if frame size is not specified;
  17539. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  17540. */
  17541. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  17542. if ( frameHeight === undefined ) frameHeight = 24;
  17543. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  17544. this.setFov( fov );
  17545. return fov;
  17546. };
  17547. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  17548. this.zoom = zoom;
  17549. if ( this.inPerspectiveMode ) {
  17550. this.toPerspective();
  17551. } else {
  17552. this.toOrthographic();
  17553. }
  17554. };
  17555. THREE.CombinedCamera.prototype.toFrontView = function() {
  17556. this.rotation.x = 0;
  17557. this.rotation.y = 0;
  17558. this.rotation.z = 0;
  17559. // should we be modifing the matrix instead?
  17560. this.rotationAutoUpdate = false;
  17561. };
  17562. THREE.CombinedCamera.prototype.toBackView = function() {
  17563. this.rotation.x = 0;
  17564. this.rotation.y = Math.PI;
  17565. this.rotation.z = 0;
  17566. this.rotationAutoUpdate = false;
  17567. };
  17568. THREE.CombinedCamera.prototype.toLeftView = function() {
  17569. this.rotation.x = 0;
  17570. this.rotation.y = - Math.PI / 2;
  17571. this.rotation.z = 0;
  17572. this.rotationAutoUpdate = false;
  17573. };
  17574. THREE.CombinedCamera.prototype.toRightView = function() {
  17575. this.rotation.x = 0;
  17576. this.rotation.y = Math.PI / 2;
  17577. this.rotation.z = 0;
  17578. this.rotationAutoUpdate = false;
  17579. };
  17580. THREE.CombinedCamera.prototype.toTopView = function() {
  17581. this.rotation.x = - Math.PI / 2;
  17582. this.rotation.y = 0;
  17583. this.rotation.z = 0;
  17584. this.rotationAutoUpdate = false;
  17585. };
  17586. THREE.CombinedCamera.prototype.toBottomView = function() {
  17587. this.rotation.x = Math.PI / 2;
  17588. this.rotation.y = 0;
  17589. this.rotation.z = 0;
  17590. this.rotationAutoUpdate = false;
  17591. };
  17592. /**
  17593. * @author alteredq / http://alteredqualia.com/
  17594. *
  17595. * - 3d asterisk shape (for line pieces THREE.Line)
  17596. */
  17597. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  17598. THREE.Geometry.call( this );
  17599. var sd = innerRadius;
  17600. var ed = outerRadius;
  17601. var sd2 = 0.707 * sd;
  17602. var ed2 = 0.707 * ed;
  17603. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  17604. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  17605. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  17606. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  17607. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  17608. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  17609. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  17610. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  17611. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  17612. ];
  17613. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  17614. var x = rays[ i ][ 0 ];
  17615. var y = rays[ i ][ 1 ];
  17616. var z = rays[ i ][ 2 ];
  17617. this.vertices.push( new THREE.Vector3( x, y, z ) );
  17618. }
  17619. };
  17620. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  17621. * @author hughes
  17622. */
  17623. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  17624. THREE.Geometry.call( this );
  17625. radius = radius || 50;
  17626. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17627. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17628. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17629. var i, uvs = [],
  17630. center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );
  17631. this.vertices.push(center);
  17632. uvs.push( centerUV );
  17633. for ( i = 0; i <= segments; i ++ ) {
  17634. var vertex = new THREE.Vector3();
  17635. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  17636. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  17637. this.vertices.push( vertex );
  17638. uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  17639. }
  17640. var n = new THREE.Vector3( 0, 0, -1 );
  17641. for ( i = 1; i <= segments; i ++ ) {
  17642. var v1 = i;
  17643. var v2 = i + 1 ;
  17644. var v3 = 0;
  17645. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  17646. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  17647. }
  17648. this.computeCentroids();
  17649. this.computeFaceNormals();
  17650. this.boundingSphere = { radius: radius };
  17651. };
  17652. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17653. /**
  17654. * @author mrdoob / http://mrdoob.com/
  17655. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  17656. */
  17657. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  17658. THREE.Geometry.call( this );
  17659. var scope = this;
  17660. this.width = width;
  17661. this.height = height;
  17662. this.depth = depth;
  17663. this.widthSegments = widthSegments || 1;
  17664. this.heightSegments = heightSegments || 1;
  17665. this.depthSegments = depthSegments || 1;
  17666. var width_half = this.width / 2;
  17667. var height_half = this.height / 2;
  17668. var depth_half = this.depth / 2;
  17669. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  17670. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  17671. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  17672. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  17673. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  17674. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  17675. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  17676. var w, ix, iy,
  17677. gridX = scope.widthSegments,
  17678. gridY = scope.heightSegments,
  17679. width_half = width / 2,
  17680. height_half = height / 2,
  17681. offset = scope.vertices.length;
  17682. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  17683. w = 'z';
  17684. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  17685. w = 'y';
  17686. gridY = scope.depthSegments;
  17687. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  17688. w = 'x';
  17689. gridX = scope.depthSegments;
  17690. }
  17691. var gridX1 = gridX + 1,
  17692. gridY1 = gridY + 1,
  17693. segment_width = width / gridX,
  17694. segment_height = height / gridY,
  17695. normal = new THREE.Vector3();
  17696. normal[ w ] = depth > 0 ? 1 : - 1;
  17697. for ( iy = 0; iy < gridY1; iy ++ ) {
  17698. for ( ix = 0; ix < gridX1; ix ++ ) {
  17699. var vector = new THREE.Vector3();
  17700. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  17701. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  17702. vector[ w ] = depth;
  17703. scope.vertices.push( vector );
  17704. }
  17705. }
  17706. for ( iy = 0; iy < gridY; iy++ ) {
  17707. for ( ix = 0; ix < gridX; ix++ ) {
  17708. var a = ix + gridX1 * iy;
  17709. var b = ix + gridX1 * ( iy + 1 );
  17710. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  17711. var d = ( ix + 1 ) + gridX1 * iy;
  17712. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  17713. face.normal.copy( normal );
  17714. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  17715. face.materialIndex = materialIndex;
  17716. scope.faces.push( face );
  17717. scope.faceVertexUvs[ 0 ].push( [
  17718. new THREE.UV( ix / gridX, 1 - iy / gridY ),
  17719. new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  17720. new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  17721. new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
  17722. ] );
  17723. }
  17724. }
  17725. }
  17726. this.computeCentroids();
  17727. this.mergeVertices();
  17728. };
  17729. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17730. /**
  17731. * @author mrdoob / http://mrdoob.com/
  17732. */
  17733. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  17734. THREE.Geometry.call( this );
  17735. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  17736. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  17737. height = height !== undefined ? height : 100;
  17738. var heightHalf = height / 2;
  17739. var segmentsX = radiusSegments || 8;
  17740. var segmentsY = heightSegments || 1;
  17741. var x, y, vertices = [], uvs = [];
  17742. for ( y = 0; y <= segmentsY; y ++ ) {
  17743. var verticesRow = [];
  17744. var uvsRow = [];
  17745. var v = y / segmentsY;
  17746. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17747. for ( x = 0; x <= segmentsX; x ++ ) {
  17748. var u = x / segmentsX;
  17749. var vertex = new THREE.Vector3();
  17750. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  17751. vertex.y = - v * height + heightHalf;
  17752. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  17753. this.vertices.push( vertex );
  17754. verticesRow.push( this.vertices.length - 1 );
  17755. uvsRow.push( new THREE.UV( u, 1 - v ) );
  17756. }
  17757. vertices.push( verticesRow );
  17758. uvs.push( uvsRow );
  17759. }
  17760. var tanTheta = ( radiusBottom - radiusTop ) / height;
  17761. var na, nb;
  17762. for ( x = 0; x < segmentsX; x ++ ) {
  17763. if ( radiusTop !== 0 ) {
  17764. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  17765. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  17766. } else {
  17767. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  17768. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  17769. }
  17770. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  17771. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  17772. for ( y = 0; y < segmentsY; y ++ ) {
  17773. var v1 = vertices[ y ][ x ];
  17774. var v2 = vertices[ y + 1 ][ x ];
  17775. var v3 = vertices[ y + 1 ][ x + 1 ];
  17776. var v4 = vertices[ y ][ x + 1 ];
  17777. var n1 = na.clone();
  17778. var n2 = na.clone();
  17779. var n3 = nb.clone();
  17780. var n4 = nb.clone();
  17781. var uv1 = uvs[ y ][ x ].clone();
  17782. var uv2 = uvs[ y + 1 ][ x ].clone();
  17783. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  17784. var uv4 = uvs[ y ][ x + 1 ].clone();
  17785. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  17786. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  17787. }
  17788. }
  17789. // top cap
  17790. if ( !openEnded && radiusTop > 0 ) {
  17791. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  17792. for ( x = 0; x < segmentsX; x ++ ) {
  17793. var v1 = vertices[ 0 ][ x ];
  17794. var v2 = vertices[ 0 ][ x + 1 ];
  17795. var v3 = this.vertices.length - 1;
  17796. var n1 = new THREE.Vector3( 0, 1, 0 );
  17797. var n2 = new THREE.Vector3( 0, 1, 0 );
  17798. var n3 = new THREE.Vector3( 0, 1, 0 );
  17799. var uv1 = uvs[ 0 ][ x ].clone();
  17800. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  17801. var uv3 = new THREE.UV( uv2.u, 0 );
  17802. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  17803. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  17804. }
  17805. }
  17806. // bottom cap
  17807. if ( !openEnded && radiusBottom > 0 ) {
  17808. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  17809. for ( x = 0; x < segmentsX; x ++ ) {
  17810. var v1 = vertices[ y ][ x + 1 ];
  17811. var v2 = vertices[ y ][ x ];
  17812. var v3 = this.vertices.length - 1;
  17813. var n1 = new THREE.Vector3( 0, - 1, 0 );
  17814. var n2 = new THREE.Vector3( 0, - 1, 0 );
  17815. var n3 = new THREE.Vector3( 0, - 1, 0 );
  17816. var uv1 = uvs[ y ][ x + 1 ].clone();
  17817. var uv2 = uvs[ y ][ x ].clone();
  17818. var uv3 = new THREE.UV( uv2.u, 1 );
  17819. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  17820. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  17821. }
  17822. }
  17823. this.computeCentroids();
  17824. this.computeFaceNormals();
  17825. }
  17826. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17827. /**
  17828. * @author zz85 / http://www.lab4games.net/zz85/blog
  17829. *
  17830. * Creates extruded geometry from a path shape.
  17831. *
  17832. * parameters = {
  17833. *
  17834. * size: <float>, // size of the text
  17835. * height: <float>, // thickness to extrude text
  17836. * curveSegments: <int>, // number of points on the curves
  17837. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  17838. * amount: <int>, // Amount
  17839. *
  17840. * bevelEnabled: <bool>, // turn on bevel
  17841. * bevelThickness: <float>, // how deep into text bevel goes
  17842. * bevelSize: <float>, // how far from text outline is bevel
  17843. * bevelSegments: <int>, // number of bevel layers
  17844. *
  17845. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  17846. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  17847. *
  17848. * material: <int> // material index for front and back faces
  17849. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  17850. * uvGenerator: <Object> // object that provides UV generator functions
  17851. *
  17852. * }
  17853. **/
  17854. THREE.ExtrudeGeometry = function ( shapes, options ) {
  17855. if ( typeof( shapes ) === "undefined" ) {
  17856. shapes = [];
  17857. return;
  17858. }
  17859. THREE.Geometry.call( this );
  17860. shapes = shapes instanceof Array ? shapes : [ shapes ];
  17861. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  17862. this.addShapeList( shapes, options );
  17863. this.computeCentroids();
  17864. this.computeFaceNormals();
  17865. // can't really use automatic vertex normals
  17866. // as then front and back sides get smoothed too
  17867. // should do separate smoothing just for sides
  17868. //this.computeVertexNormals();
  17869. //console.log( "took", ( Date.now() - startTime ) );
  17870. };
  17871. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17872. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  17873. var sl = shapes.length;
  17874. for ( var s = 0; s < sl; s ++ ) {
  17875. var shape = shapes[ s ];
  17876. this.addShape( shape, options );
  17877. }
  17878. };
  17879. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  17880. var amount = options.amount !== undefined ? options.amount : 100;
  17881. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  17882. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  17883. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  17884. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  17885. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  17886. var steps = options.steps !== undefined ? options.steps : 1;
  17887. var extrudePath = options.extrudePath;
  17888. var extrudePts, extrudeByPath = false;
  17889. var material = options.material;
  17890. var extrudeMaterial = options.extrudeMaterial;
  17891. // Use default WorldUVGenerator if no UV generators are specified.
  17892. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  17893. var shapebb = this.shapebb;
  17894. //shapebb = shape.getBoundingBox();
  17895. var splineTube, binormal, normal, position2;
  17896. if ( extrudePath ) {
  17897. extrudePts = extrudePath.getSpacedPoints( steps );
  17898. extrudeByPath = true;
  17899. bevelEnabled = false; // bevels not supported for path extrusion
  17900. // SETUP TNB variables
  17901. // Reuse TNB from TubeGeomtry for now.
  17902. // TODO1 - have a .isClosed in spline?
  17903. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  17904. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  17905. binormal = new THREE.Vector3();
  17906. normal = new THREE.Vector3();
  17907. position2 = new THREE.Vector3();
  17908. }
  17909. // Safeguards if bevels are not enabled
  17910. if ( ! bevelEnabled ) {
  17911. bevelSegments = 0;
  17912. bevelThickness = 0;
  17913. bevelSize = 0;
  17914. }
  17915. // Variables initalization
  17916. var ahole, h, hl; // looping of holes
  17917. var scope = this;
  17918. var bevelPoints = [];
  17919. var shapesOffset = this.vertices.length;
  17920. var shapePoints = shape.extractPoints();
  17921. var vertices = shapePoints.shape;
  17922. var holes = shapePoints.holes;
  17923. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  17924. if ( reverse ) {
  17925. vertices = vertices.reverse();
  17926. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  17927. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  17928. ahole = holes[ h ];
  17929. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  17930. holes[ h ] = ahole.reverse();
  17931. }
  17932. }
  17933. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  17934. }
  17935. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  17936. /* Vertices */
  17937. var contour = vertices; // vertices has all points but contour has only points of circumference
  17938. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  17939. ahole = holes[ h ];
  17940. vertices = vertices.concat( ahole );
  17941. }
  17942. function scalePt2 ( pt, vec, size ) {
  17943. if ( !vec ) console.log( "die" );
  17944. return vec.clone().multiplyScalar( size ).addSelf( pt );
  17945. }
  17946. var b, bs, t, z,
  17947. vert, vlen = vertices.length,
  17948. face, flen = faces.length,
  17949. cont, clen = contour.length;
  17950. // Find directions for point movement
  17951. var RAD_TO_DEGREES = 180 / Math.PI;
  17952. function getBevelVec( pt_i, pt_j, pt_k ) {
  17953. // Algorithm 2
  17954. return getBevelVec2( pt_i, pt_j, pt_k );
  17955. }
  17956. function getBevelVec1( pt_i, pt_j, pt_k ) {
  17957. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  17958. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  17959. if ( anglea > angleb ) {
  17960. angleb += Math.PI * 2;
  17961. }
  17962. var anglec = ( anglea + angleb ) / 2;
  17963. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  17964. var x = - Math.cos( anglec );
  17965. var y = - Math.sin( anglec );
  17966. var vec = new THREE.Vector2( x, y ); //.normalize();
  17967. return vec;
  17968. }
  17969. function getBevelVec2( pt_i, pt_j, pt_k ) {
  17970. var a = THREE.ExtrudeGeometry.__v1,
  17971. b = THREE.ExtrudeGeometry.__v2,
  17972. v_hat = THREE.ExtrudeGeometry.__v3,
  17973. w_hat = THREE.ExtrudeGeometry.__v4,
  17974. p = THREE.ExtrudeGeometry.__v5,
  17975. q = THREE.ExtrudeGeometry.__v6,
  17976. v, w,
  17977. v_dot_w_hat, q_sub_p_dot_w_hat,
  17978. s, intersection;
  17979. // good reading for line-line intersection
  17980. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  17981. // define a as vector j->i
  17982. // define b as vectot k->i
  17983. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  17984. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  17985. // get unit vectors
  17986. v = a.normalize();
  17987. w = b.normalize();
  17988. // normals from pt i
  17989. v_hat.set( -v.y, v.x );
  17990. w_hat.set( w.y, -w.x );
  17991. // pts from i
  17992. p.copy( pt_i ).addSelf( v_hat );
  17993. q.copy( pt_i ).addSelf( w_hat );
  17994. if ( p.equals( q ) ) {
  17995. //console.log("Warning: lines are straight");
  17996. return w_hat.clone();
  17997. }
  17998. // Points from j, k. helps prevents points cross overover most of the time
  17999. p.copy( pt_j ).addSelf( v_hat );
  18000. q.copy( pt_k ).addSelf( w_hat );
  18001. v_dot_w_hat = v.dot( w_hat );
  18002. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  18003. // We should not reach these conditions
  18004. if ( v_dot_w_hat === 0 ) {
  18005. console.log( "Either infinite or no solutions!" );
  18006. if ( q_sub_p_dot_w_hat === 0 ) {
  18007. console.log( "Its finite solutions." );
  18008. } else {
  18009. console.log( "Too bad, no solutions." );
  18010. }
  18011. }
  18012. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18013. if ( s < 0 ) {
  18014. // in case of emergecy, revert to algorithm 1.
  18015. return getBevelVec1( pt_i, pt_j, pt_k );
  18016. }
  18017. intersection = v.multiplyScalar( s ).addSelf( p );
  18018. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18019. }
  18020. var contourMovements = [];
  18021. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18022. if ( j === il ) j = 0;
  18023. if ( k === il ) k = 0;
  18024. // (j)---(i)---(k)
  18025. // console.log('i,j,k', i, j , k)
  18026. var pt_i = contour[ i ];
  18027. var pt_j = contour[ j ];
  18028. var pt_k = contour[ k ];
  18029. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18030. }
  18031. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18032. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18033. ahole = holes[ h ];
  18034. oneHoleMovements = [];
  18035. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18036. if ( j === il ) j = 0;
  18037. if ( k === il ) k = 0;
  18038. // (j)---(i)---(k)
  18039. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18040. }
  18041. holesMovements.push( oneHoleMovements );
  18042. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18043. }
  18044. // Loop bevelSegments, 1 for the front, 1 for the back
  18045. for ( b = 0; b < bevelSegments; b ++ ) {
  18046. //for ( b = bevelSegments; b > 0; b -- ) {
  18047. t = b / bevelSegments;
  18048. z = bevelThickness * ( 1 - t );
  18049. //z = bevelThickness * t;
  18050. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18051. //bs = bevelSize * t ; // linear
  18052. // contract shape
  18053. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18054. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18055. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18056. v( vert.x, vert.y, - z );
  18057. }
  18058. // expand holes
  18059. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18060. ahole = holes[ h ];
  18061. oneHoleMovements = holesMovements[ h ];
  18062. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18063. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18064. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18065. v( vert.x, vert.y, -z );
  18066. }
  18067. }
  18068. }
  18069. bs = bevelSize;
  18070. // Back facing vertices
  18071. for ( i = 0; i < vlen; i ++ ) {
  18072. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18073. if ( !extrudeByPath ) {
  18074. v( vert.x, vert.y, 0 );
  18075. } else {
  18076. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18077. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18078. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18079. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  18080. v( position2.x, position2.y, position2.z );
  18081. }
  18082. }
  18083. // Add stepped vertices...
  18084. // Including front facing vertices
  18085. var s;
  18086. for ( s = 1; s <= steps; s ++ ) {
  18087. for ( i = 0; i < vlen; i ++ ) {
  18088. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18089. if ( !extrudeByPath ) {
  18090. v( vert.x, vert.y, amount / steps * s );
  18091. } else {
  18092. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18093. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18094. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18095. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  18096. v( position2.x, position2.y, position2.z );
  18097. }
  18098. }
  18099. }
  18100. // Add bevel segments planes
  18101. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18102. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18103. t = b / bevelSegments;
  18104. z = bevelThickness * ( 1 - t );
  18105. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18106. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18107. // contract shape
  18108. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18109. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18110. v( vert.x, vert.y, amount + z );
  18111. }
  18112. // expand holes
  18113. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18114. ahole = holes[ h ];
  18115. oneHoleMovements = holesMovements[ h ];
  18116. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18117. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18118. if ( !extrudeByPath ) {
  18119. v( vert.x, vert.y, amount + z );
  18120. } else {
  18121. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18122. }
  18123. }
  18124. }
  18125. }
  18126. /* Faces */
  18127. // Top and bottom faces
  18128. buildLidFaces();
  18129. // Sides faces
  18130. buildSideFaces();
  18131. ///// Internal functions
  18132. function buildLidFaces() {
  18133. if ( bevelEnabled ) {
  18134. var layer = 0 ; // steps + 1
  18135. var offset = vlen * layer;
  18136. // Bottom faces
  18137. for ( i = 0; i < flen; i ++ ) {
  18138. face = faces[ i ];
  18139. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18140. }
  18141. layer = steps + bevelSegments * 2;
  18142. offset = vlen * layer;
  18143. // Top faces
  18144. for ( i = 0; i < flen; i ++ ) {
  18145. face = faces[ i ];
  18146. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18147. }
  18148. } else {
  18149. // Bottom faces
  18150. for ( i = 0; i < flen; i++ ) {
  18151. face = faces[ i ];
  18152. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18153. }
  18154. // Top faces
  18155. for ( i = 0; i < flen; i ++ ) {
  18156. face = faces[ i ];
  18157. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18158. }
  18159. }
  18160. }
  18161. // Create faces for the z-sides of the shape
  18162. function buildSideFaces() {
  18163. var layeroffset = 0;
  18164. sidewalls( contour, layeroffset );
  18165. layeroffset += contour.length;
  18166. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18167. ahole = holes[ h ];
  18168. sidewalls( ahole, layeroffset );
  18169. //, true
  18170. layeroffset += ahole.length;
  18171. }
  18172. }
  18173. function sidewalls( contour, layeroffset ) {
  18174. var j, k;
  18175. i = contour.length;
  18176. while ( --i >= 0 ) {
  18177. j = i;
  18178. k = i - 1;
  18179. if ( k < 0 ) k = contour.length - 1;
  18180. //console.log('b', i,j, i-1, k,vertices.length);
  18181. var s = 0, sl = steps + bevelSegments * 2;
  18182. for ( s = 0; s < sl; s ++ ) {
  18183. var slen1 = vlen * s;
  18184. var slen2 = vlen * ( s + 1 );
  18185. var a = layeroffset + j + slen1,
  18186. b = layeroffset + k + slen1,
  18187. c = layeroffset + k + slen2,
  18188. d = layeroffset + j + slen2;
  18189. f4( a, b, c, d, contour, s, sl, j, k );
  18190. }
  18191. }
  18192. }
  18193. function v( x, y, z ) {
  18194. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18195. }
  18196. function f3( a, b, c, isBottom ) {
  18197. a += shapesOffset;
  18198. b += shapesOffset;
  18199. c += shapesOffset;
  18200. // normal, color, material
  18201. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18202. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18203. scope.faceVertexUvs[ 0 ].push( uvs );
  18204. }
  18205. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18206. a += shapesOffset;
  18207. b += shapesOffset;
  18208. c += shapesOffset;
  18209. d += shapesOffset;
  18210. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18211. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18212. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18213. scope.faceVertexUvs[ 0 ].push( uvs );
  18214. }
  18215. };
  18216. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18217. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18218. var ax = geometry.vertices[ indexA ].x,
  18219. ay = geometry.vertices[ indexA ].y,
  18220. bx = geometry.vertices[ indexB ].x,
  18221. by = geometry.vertices[ indexB ].y,
  18222. cx = geometry.vertices[ indexC ].x,
  18223. cy = geometry.vertices[ indexC ].y;
  18224. return [
  18225. new THREE.UV( ax, ay ),
  18226. new THREE.UV( bx, by ),
  18227. new THREE.UV( cx, cy )
  18228. ];
  18229. },
  18230. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18231. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18232. },
  18233. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18234. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18235. contourIndex1, contourIndex2 ) {
  18236. var ax = geometry.vertices[ indexA ].x,
  18237. ay = geometry.vertices[ indexA ].y,
  18238. az = geometry.vertices[ indexA ].z,
  18239. bx = geometry.vertices[ indexB ].x,
  18240. by = geometry.vertices[ indexB ].y,
  18241. bz = geometry.vertices[ indexB ].z,
  18242. cx = geometry.vertices[ indexC ].x,
  18243. cy = geometry.vertices[ indexC ].y,
  18244. cz = geometry.vertices[ indexC ].z,
  18245. dx = geometry.vertices[ indexD ].x,
  18246. dy = geometry.vertices[ indexD ].y,
  18247. dz = geometry.vertices[ indexD ].z;
  18248. if ( Math.abs( ay - by ) < 0.01 ) {
  18249. return [
  18250. new THREE.UV( ax, 1 - az ),
  18251. new THREE.UV( bx, 1 - bz ),
  18252. new THREE.UV( cx, 1 - cz ),
  18253. new THREE.UV( dx, 1 - dz )
  18254. ];
  18255. } else {
  18256. return [
  18257. new THREE.UV( ay, 1 - az ),
  18258. new THREE.UV( by, 1 - bz ),
  18259. new THREE.UV( cy, 1 - cz ),
  18260. new THREE.UV( dy, 1 - dz )
  18261. ];
  18262. }
  18263. }
  18264. };
  18265. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18266. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18267. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18268. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18269. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18270. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18271. /**
  18272. * @author jonobr1 / http://jonobr1.com
  18273. *
  18274. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18275. * ExtrudeGeometry.
  18276. *
  18277. * parameters = {
  18278. *
  18279. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18280. *
  18281. * material: <int> // material index for front and back faces
  18282. * uvGenerator: <Object> // object that provides UV generator functions
  18283. *
  18284. * }
  18285. **/
  18286. THREE.ShapeGeometry = function ( shapes, options ) {
  18287. THREE.Geometry.call( this );
  18288. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  18289. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18290. this.addShapeList( shapes, options );
  18291. this.computeCentroids();
  18292. this.computeFaceNormals();
  18293. };
  18294. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18295. /**
  18296. * Add an array of shapes to THREE.ShapeGeometry.
  18297. */
  18298. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18299. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  18300. this.addShape( shapes[ i ], options );
  18301. }
  18302. return this;
  18303. };
  18304. /**
  18305. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18306. */
  18307. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18308. if ( options === undefined ) options = {};
  18309. var material = options.material;
  18310. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18311. var shapebb = this.shapebb;
  18312. //
  18313. var i, l, hole, s;
  18314. var shapesOffset = this.vertices.length;
  18315. var shapePoints = shape.extractPoints();
  18316. var vertices = shapePoints.shape;
  18317. var holes = shapePoints.holes;
  18318. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  18319. if ( reverse ) {
  18320. vertices = vertices.reverse();
  18321. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18322. for ( i = 0, l = holes.length; i < l; i++ ) {
  18323. hole = holes[ i ];
  18324. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  18325. holes[ i ] = hole.reverse();
  18326. }
  18327. }
  18328. reverse = false;
  18329. }
  18330. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  18331. // Vertices
  18332. var contour = vertices;
  18333. for ( i = 0, l = holes.length; i < l; i++ ) {
  18334. hole = holes[ i ];
  18335. vertices = vertices.concat( hole );
  18336. }
  18337. //
  18338. var vert, vlen = vertices.length;
  18339. var face, flen = faces.length;
  18340. var cont, clen = contour.length;
  18341. for ( i = 0; i < vlen; i++ ) {
  18342. vert = vertices[ i ];
  18343. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  18344. }
  18345. for ( i = 0; i < flen; i++ ) {
  18346. face = faces[ i ];
  18347. var a = face[ 0 ] + shapesOffset;
  18348. var b = face[ 1 ] + shapesOffset;
  18349. var c = face[ 2 ] + shapesOffset;
  18350. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18351. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  18352. }
  18353. };
  18354. /**
  18355. * @author astrodud / http://astrodud.isgreat.org/
  18356. * @author zz85 / https://github.com/zz85
  18357. */
  18358. THREE.LatheGeometry = function ( points, steps, angle ) {
  18359. THREE.Geometry.call( this );
  18360. var _steps = steps || 12;
  18361. var _angle = angle || 2 * Math.PI;
  18362. var _newV = [];
  18363. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  18364. for ( var j = 0; j < points.length; j ++ ) {
  18365. _newV[ j ] = points[ j ].clone();
  18366. this.vertices.push( _newV[ j ] );
  18367. }
  18368. var i, il = _steps + 1;
  18369. for ( i = 0; i < il; i ++ ) {
  18370. for ( var j = 0; j < _newV.length; j ++ ) {
  18371. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  18372. this.vertices.push( _newV[ j ] );
  18373. }
  18374. }
  18375. for ( i = 0; i < _steps; i ++ ) {
  18376. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  18377. var a = i * kl + k;
  18378. var b = ( ( i + 1 ) % il ) * kl + k;
  18379. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  18380. var d = i * kl + ( k + 1 ) % kl;
  18381. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18382. this.faceVertexUvs[ 0 ].push( [
  18383. new THREE.UV( 1 - i / _steps, k / kl ),
  18384. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  18385. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  18386. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  18387. ] );
  18388. }
  18389. }
  18390. this.computeCentroids();
  18391. this.computeFaceNormals();
  18392. this.computeVertexNormals();
  18393. };
  18394. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18395. /**
  18396. * @author mrdoob / http://mrdoob.com/
  18397. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18398. */
  18399. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  18400. THREE.Geometry.call( this );
  18401. this.width = width;
  18402. this.height = height;
  18403. this.widthSegments = widthSegments || 1;
  18404. this.heightSegments = heightSegments || 1;
  18405. var ix, iz;
  18406. var width_half = width / 2;
  18407. var height_half = height / 2;
  18408. var gridX = this.widthSegments;
  18409. var gridZ = this.heightSegments;
  18410. var gridX1 = gridX + 1;
  18411. var gridZ1 = gridZ + 1;
  18412. var segment_width = this.width / gridX;
  18413. var segment_height = this.height / gridZ;
  18414. var normal = new THREE.Vector3( 0, 0, 1 );
  18415. for ( iz = 0; iz < gridZ1; iz ++ ) {
  18416. for ( ix = 0; ix < gridX1; ix ++ ) {
  18417. var x = ix * segment_width - width_half;
  18418. var y = iz * segment_height - height_half;
  18419. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  18420. }
  18421. }
  18422. for ( iz = 0; iz < gridZ; iz ++ ) {
  18423. for ( ix = 0; ix < gridX; ix ++ ) {
  18424. var a = ix + gridX1 * iz;
  18425. var b = ix + gridX1 * ( iz + 1 );
  18426. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  18427. var d = ( ix + 1 ) + gridX1 * iz;
  18428. var face = new THREE.Face4( a, b, c, d );
  18429. face.normal.copy( normal );
  18430. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18431. this.faces.push( face );
  18432. this.faceVertexUvs[ 0 ].push( [
  18433. new THREE.UV( ix / gridX, 1 - iz / gridZ ),
  18434. new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  18435. new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  18436. new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  18437. ] );
  18438. }
  18439. }
  18440. this.computeCentroids();
  18441. };
  18442. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18443. /**
  18444. * @author mrdoob / http://mrdoob.com/
  18445. */
  18446. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  18447. THREE.Geometry.call( this );
  18448. this.radius = radius || 50;
  18449. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  18450. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  18451. phiStart = phiStart !== undefined ? phiStart : 0;
  18452. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18453. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18454. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18455. var x, y, vertices = [], uvs = [];
  18456. for ( y = 0; y <= this.heightSegments; y ++ ) {
  18457. var verticesRow = [];
  18458. var uvsRow = [];
  18459. for ( x = 0; x <= this.widthSegments; x ++ ) {
  18460. var u = x / this.widthSegments;
  18461. var v = y / this.heightSegments;
  18462. var vertex = new THREE.Vector3();
  18463. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18464. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  18465. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18466. this.vertices.push( vertex );
  18467. verticesRow.push( this.vertices.length - 1 );
  18468. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18469. }
  18470. vertices.push( verticesRow );
  18471. uvs.push( uvsRow );
  18472. }
  18473. for ( y = 0; y < this.heightSegments; y ++ ) {
  18474. for ( x = 0; x < this.widthSegments; x ++ ) {
  18475. var v1 = vertices[ y ][ x + 1 ];
  18476. var v2 = vertices[ y ][ x ];
  18477. var v3 = vertices[ y + 1 ][ x ];
  18478. var v4 = vertices[ y + 1 ][ x + 1 ];
  18479. var n1 = this.vertices[ v1 ].clone().normalize();
  18480. var n2 = this.vertices[ v2 ].clone().normalize();
  18481. var n3 = this.vertices[ v3 ].clone().normalize();
  18482. var n4 = this.vertices[ v4 ].clone().normalize();
  18483. var uv1 = uvs[ y ][ x + 1 ].clone();
  18484. var uv2 = uvs[ y ][ x ].clone();
  18485. var uv3 = uvs[ y + 1 ][ x ].clone();
  18486. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  18487. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  18488. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  18489. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  18490. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  18491. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18492. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18493. } else {
  18494. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18495. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18496. }
  18497. }
  18498. }
  18499. this.computeCentroids();
  18500. this.computeFaceNormals();
  18501. this.boundingSphere = { radius: this.radius };
  18502. };
  18503. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18504. /**
  18505. * @author zz85 / http://www.lab4games.net/zz85/blog
  18506. * @author alteredq / http://alteredqualia.com/
  18507. *
  18508. * For creating 3D text geometry in three.js
  18509. *
  18510. * Text = 3D Text
  18511. *
  18512. * parameters = {
  18513. * size: <float>, // size of the text
  18514. * height: <float>, // thickness to extrude text
  18515. * curveSegments: <int>, // number of points on the curves
  18516. *
  18517. * font: <string>, // font name
  18518. * weight: <string>, // font weight (normal, bold)
  18519. * style: <string>, // font style (normal, italics)
  18520. *
  18521. * bevelEnabled: <bool>, // turn on bevel
  18522. * bevelThickness: <float>, // how deep into text bevel goes
  18523. * bevelSize: <float>, // how far from text outline is bevel
  18524. * }
  18525. *
  18526. */
  18527. /* Usage Examples
  18528. // TextGeometry wrapper
  18529. var text3d = new TextGeometry( text, options );
  18530. // Complete manner
  18531. var textShapes = THREE.FontUtils.generateShapes( text, options );
  18532. var text3d = new ExtrudeGeometry( textShapes, options );
  18533. */
  18534. THREE.TextGeometry = function ( text, parameters ) {
  18535. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  18536. // translate parameters to ExtrudeGeometry API
  18537. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  18538. // defaults
  18539. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  18540. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  18541. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  18542. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  18543. };
  18544. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  18545. /**
  18546. * @author oosmoxiecode
  18547. * @author mrdoob / http://mrdoob.com/
  18548. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  18549. */
  18550. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  18551. THREE.Geometry.call( this );
  18552. var scope = this;
  18553. this.radius = radius || 100;
  18554. this.tube = tube || 40;
  18555. this.radialSegments = radialSegments || 8;
  18556. this.tubularSegments = tubularSegments || 6;
  18557. this.arc = arc || Math.PI * 2;
  18558. var center = new THREE.Vector3(), uvs = [], normals = [];
  18559. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  18560. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  18561. var u = i / this.tubularSegments * this.arc;
  18562. var v = j / this.radialSegments * Math.PI * 2;
  18563. center.x = this.radius * Math.cos( u );
  18564. center.y = this.radius * Math.sin( u );
  18565. var vertex = new THREE.Vector3();
  18566. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  18567. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  18568. vertex.z = this.tube * Math.sin( v );
  18569. this.vertices.push( vertex );
  18570. uvs.push( new THREE.UV( i / this.tubularSegments, j / this.radialSegments ) );
  18571. normals.push( vertex.clone().subSelf( center ).normalize() );
  18572. }
  18573. }
  18574. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  18575. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  18576. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  18577. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  18578. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  18579. var d = ( this.tubularSegments + 1 ) * j + i;
  18580. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  18581. face.normal.addSelf( normals[ a ] );
  18582. face.normal.addSelf( normals[ b ] );
  18583. face.normal.addSelf( normals[ c ] );
  18584. face.normal.addSelf( normals[ d ] );
  18585. face.normal.normalize();
  18586. this.faces.push( face );
  18587. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  18588. }
  18589. }
  18590. this.computeCentroids();
  18591. };
  18592. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18593. /**
  18594. * @author oosmoxiecode
  18595. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  18596. */
  18597. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  18598. THREE.Geometry.call( this );
  18599. var scope = this;
  18600. this.radius = radius || 200;
  18601. this.tube = tube || 40;
  18602. this.radialSegments = radialSegments || 64;
  18603. this.tubularSegments = tubularSegments || 8;
  18604. this.p = p || 2;
  18605. this.q = q || 3;
  18606. this.heightScale = heightScale || 1;
  18607. this.grid = new Array(this.radialSegments);
  18608. var tang = new THREE.Vector3();
  18609. var n = new THREE.Vector3();
  18610. var bitan = new THREE.Vector3();
  18611. for ( var i = 0; i < this.radialSegments; ++ i ) {
  18612. this.grid[ i ] = new Array( this.tubularSegments );
  18613. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  18614. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  18615. var v = j / this.tubularSegments * 2 * Math.PI;
  18616. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  18617. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  18618. var cx, cy;
  18619. tang.sub( p2, p1 );
  18620. n.add( p2, p1 );
  18621. bitan.cross( tang, n );
  18622. n.cross( bitan, tang );
  18623. bitan.normalize();
  18624. n.normalize();
  18625. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18626. cy = this.tube * Math.sin( v );
  18627. p1.x += cx * n.x + cy * bitan.x;
  18628. p1.y += cx * n.y + cy * bitan.y;
  18629. p1.z += cx * n.z + cy * bitan.z;
  18630. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  18631. }
  18632. }
  18633. for ( var i = 0; i < this.radialSegments; ++ i ) {
  18634. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  18635. var ip = ( i + 1 ) % this.radialSegments;
  18636. var jp = ( j + 1 ) % this.tubularSegments;
  18637. var a = this.grid[ i ][ j ];
  18638. var b = this.grid[ ip ][ j ];
  18639. var c = this.grid[ ip ][ jp ];
  18640. var d = this.grid[ i ][ jp ];
  18641. var uva = new THREE.UV( i / this.radialSegments, j / this.tubularSegments );
  18642. var uvb = new THREE.UV( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  18643. var uvc = new THREE.UV( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  18644. var uvd = new THREE.UV( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  18645. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18646. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  18647. }
  18648. }
  18649. this.computeCentroids();
  18650. this.computeFaceNormals();
  18651. this.computeVertexNormals();
  18652. function vert( x, y, z ) {
  18653. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18654. }
  18655. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  18656. var cu = Math.cos( u );
  18657. var cv = Math.cos( v );
  18658. var su = Math.sin( u );
  18659. var quOverP = in_q / in_p * u;
  18660. var cs = Math.cos( quOverP );
  18661. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  18662. var ty = radius * ( 2 + cs ) * su * 0.5;
  18663. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  18664. return new THREE.Vector3( tx, ty, tz );
  18665. }
  18666. };
  18667. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18668. /**
  18669. * @author WestLangley / https://github.com/WestLangley
  18670. * @author zz85 / https://github.com/zz85
  18671. * @author miningold / https://github.com/miningold
  18672. *
  18673. * Modified from the TorusKnotGeometry by @oosmoxiecode
  18674. *
  18675. * Creates a tube which extrudes along a 3d spline
  18676. *
  18677. * Uses parallel transport frames as described in
  18678. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18679. */
  18680. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  18681. THREE.Geometry.call( this );
  18682. this.path = path;
  18683. this.segments = segments || 64;
  18684. this.radius = radius || 1;
  18685. this.radiusSegments = radiusSegments || 8;
  18686. this.closed = closed || false;
  18687. if ( debug ) this.debug = new THREE.Object3D();
  18688. this.grid = [];
  18689. var scope = this,
  18690. tangent,
  18691. normal,
  18692. binormal,
  18693. numpoints = this.segments + 1,
  18694. x, y, z,
  18695. tx, ty, tz,
  18696. u, v,
  18697. cx, cy,
  18698. pos, pos2 = new THREE.Vector3(),
  18699. i, j,
  18700. ip, jp,
  18701. a, b, c, d,
  18702. uva, uvb, uvc, uvd;
  18703. var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
  18704. tangents = frames.tangents,
  18705. normals = frames.normals,
  18706. binormals = frames.binormals;
  18707. // proxy internals
  18708. this.tangents = tangents;
  18709. this.normals = normals;
  18710. this.binormals = binormals;
  18711. function vert( x, y, z ) {
  18712. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18713. }
  18714. // consruct the grid
  18715. for ( i = 0; i < numpoints; i++ ) {
  18716. this.grid[ i ] = [];
  18717. u = i / ( numpoints - 1 );
  18718. pos = path.getPointAt( u );
  18719. tangent = tangents[ i ];
  18720. normal = normals[ i ];
  18721. binormal = binormals[ i ];
  18722. if ( this.debug ) {
  18723. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  18724. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  18725. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  18726. }
  18727. for ( j = 0; j < this.radiusSegments; j++ ) {
  18728. v = j / this.radiusSegments * 2 * Math.PI;
  18729. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18730. cy = this.radius * Math.sin( v );
  18731. pos2.copy( pos );
  18732. pos2.x += cx * normal.x + cy * binormal.x;
  18733. pos2.y += cx * normal.y + cy * binormal.y;
  18734. pos2.z += cx * normal.z + cy * binormal.z;
  18735. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  18736. }
  18737. }
  18738. // construct the mesh
  18739. for ( i = 0; i < this.segments; i++ ) {
  18740. for ( j = 0; j < this.radiusSegments; j++ ) {
  18741. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  18742. jp = (j + 1) % this.radiusSegments;
  18743. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  18744. b = this.grid[ ip ][ j ];
  18745. c = this.grid[ ip ][ jp ];
  18746. d = this.grid[ i ][ jp ];
  18747. uva = new THREE.UV( i / this.segments, j / this.radiusSegments );
  18748. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.radiusSegments );
  18749. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  18750. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.radiusSegments );
  18751. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18752. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  18753. }
  18754. }
  18755. this.computeCentroids();
  18756. this.computeFaceNormals();
  18757. this.computeVertexNormals();
  18758. };
  18759. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18760. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  18761. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  18762. var
  18763. tangent = new THREE.Vector3(),
  18764. normal = new THREE.Vector3(),
  18765. binormal = new THREE.Vector3(),
  18766. tangents = [],
  18767. normals = [],
  18768. binormals = [],
  18769. vec = new THREE.Vector3(),
  18770. mat = new THREE.Matrix4(),
  18771. numpoints = segments + 1,
  18772. theta,
  18773. epsilon = 0.0001,
  18774. smallest,
  18775. tx, ty, tz,
  18776. i, u, v;
  18777. // expose internals
  18778. this.tangents = tangents;
  18779. this.normals = normals;
  18780. this.binormals = binormals;
  18781. // compute the tangent vectors for each segment on the path
  18782. for ( i = 0; i < numpoints; i++ ) {
  18783. u = i / ( numpoints - 1 );
  18784. tangents[ i ] = path.getTangentAt( u );
  18785. tangents[ i ].normalize();
  18786. }
  18787. initialNormal3();
  18788. function initialNormal1(lastBinormal) {
  18789. // fixed start binormal. Has dangers of 0 vectors
  18790. normals[ 0 ] = new THREE.Vector3();
  18791. binormals[ 0 ] = new THREE.Vector3();
  18792. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  18793. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  18794. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18795. }
  18796. function initialNormal2() {
  18797. // This uses the Frenet-Serret formula for deriving binormal
  18798. var t2 = path.getTangentAt( epsilon );
  18799. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  18800. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  18801. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  18802. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18803. }
  18804. function initialNormal3() {
  18805. // select an initial normal vector perpenicular to the first tangent vector,
  18806. // and in the direction of the smallest tangent xyz component
  18807. normals[ 0 ] = new THREE.Vector3();
  18808. binormals[ 0 ] = new THREE.Vector3();
  18809. smallest = Number.MAX_VALUE;
  18810. tx = Math.abs( tangents[ 0 ].x );
  18811. ty = Math.abs( tangents[ 0 ].y );
  18812. tz = Math.abs( tangents[ 0 ].z );
  18813. if ( tx <= smallest ) {
  18814. smallest = tx;
  18815. normal.set( 1, 0, 0 );
  18816. }
  18817. if ( ty <= smallest ) {
  18818. smallest = ty;
  18819. normal.set( 0, 1, 0 );
  18820. }
  18821. if ( tz <= smallest ) {
  18822. normal.set( 0, 0, 1 );
  18823. }
  18824. vec.cross( tangents[ 0 ], normal ).normalize();
  18825. normals[ 0 ].cross( tangents[ 0 ], vec );
  18826. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  18827. }
  18828. // compute the slowly-varying normal and binormal vectors for each segment on the path
  18829. for ( i = 1; i < numpoints; i++ ) {
  18830. normals[ i ] = normals[ i-1 ].clone();
  18831. binormals[ i ] = binormals[ i-1 ].clone();
  18832. vec.cross( tangents[ i-1 ], tangents[ i ] );
  18833. if ( vec.length() > epsilon ) {
  18834. vec.normalize();
  18835. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  18836. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  18837. }
  18838. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  18839. }
  18840. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18841. if ( closed ) {
  18842. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  18843. theta /= ( numpoints - 1 );
  18844. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  18845. theta = -theta;
  18846. }
  18847. for ( i = 1; i < numpoints; i++ ) {
  18848. // twist a little...
  18849. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  18850. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  18851. }
  18852. }
  18853. };
  18854. /**
  18855. * @author clockworkgeek / https://github.com/clockworkgeek
  18856. * @author timothypratley / https://github.com/timothypratley
  18857. */
  18858. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  18859. THREE.Geometry.call( this );
  18860. radius = radius || 1;
  18861. detail = detail || 0;
  18862. var that = this;
  18863. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  18864. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  18865. }
  18866. var midpoints = [], p = this.vertices;
  18867. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  18868. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  18869. }
  18870. this.mergeVertices();
  18871. // Apply radius
  18872. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  18873. this.vertices[ i ].multiplyScalar( radius );
  18874. }
  18875. // Project vector onto sphere's surface
  18876. function prepare( vector ) {
  18877. var vertex = vector.normalize().clone();
  18878. vertex.index = that.vertices.push( vertex ) - 1;
  18879. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  18880. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  18881. var v = inclination( vector ) / Math.PI + 0.5;
  18882. vertex.uv = new THREE.UV( u, 1 - v );
  18883. return vertex;
  18884. }
  18885. // Approximate a curved face with recursively sub-divided triangles.
  18886. function make( v1, v2, v3, detail ) {
  18887. if ( detail < 1 ) {
  18888. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  18889. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  18890. face.normal = face.centroid.clone().normalize();
  18891. that.faces.push( face );
  18892. var azi = azimuth( face.centroid );
  18893. that.faceVertexUvs[ 0 ].push( [
  18894. correctUV( v1.uv, v1, azi ),
  18895. correctUV( v2.uv, v2, azi ),
  18896. correctUV( v3.uv, v3, azi )
  18897. ] );
  18898. } else {
  18899. detail -= 1;
  18900. // split triangle into 4 smaller triangles
  18901. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  18902. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  18903. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  18904. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  18905. }
  18906. }
  18907. function midpoint( v1, v2 ) {
  18908. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  18909. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  18910. var mid = midpoints[ v1.index ][ v2.index ];
  18911. if ( mid === undefined ) {
  18912. // generate mean point and project to surface with prepare()
  18913. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  18914. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  18915. );
  18916. }
  18917. return mid;
  18918. }
  18919. // Angle around the Y axis, counter-clockwise when looking from above.
  18920. function azimuth( vector ) {
  18921. return Math.atan2( vector.z, -vector.x );
  18922. }
  18923. // Angle above the XZ plane.
  18924. function inclination( vector ) {
  18925. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  18926. }
  18927. // Texture fixing helper. Spheres have some odd behaviours.
  18928. function correctUV( uv, vector, azimuth ) {
  18929. if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
  18930. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  18931. return uv;
  18932. }
  18933. this.computeCentroids();
  18934. this.boundingSphere = { radius: radius };
  18935. };
  18936. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18937. /**
  18938. * @author timothypratley / https://github.com/timothypratley
  18939. */
  18940. THREE.IcosahedronGeometry = function ( radius, detail ) {
  18941. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18942. var vertices = [
  18943. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  18944. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  18945. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  18946. ];
  18947. var faces = [
  18948. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  18949. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  18950. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  18951. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  18952. ];
  18953. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  18954. };
  18955. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18956. /**
  18957. * @author timothypratley / https://github.com/timothypratley
  18958. */
  18959. THREE.OctahedronGeometry = function ( radius, detail ) {
  18960. var vertices = [
  18961. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  18962. ];
  18963. var faces = [
  18964. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  18965. ];
  18966. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  18967. };
  18968. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18969. /**
  18970. * @author timothypratley / https://github.com/timothypratley
  18971. */
  18972. THREE.TetrahedronGeometry = function ( radius, detail ) {
  18973. var vertices = [
  18974. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  18975. ];
  18976. var faces = [
  18977. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  18978. ];
  18979. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  18980. };
  18981. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18982. /**
  18983. * @author zz85 / https://github.com/zz85
  18984. * Parametric Surfaces Geometry
  18985. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  18986. *
  18987. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  18988. *
  18989. */
  18990. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  18991. THREE.Geometry.call( this );
  18992. var verts = this.vertices;
  18993. var faces = this.faces;
  18994. var uvs = this.faceVertexUvs[ 0 ];
  18995. useTris = (useTris === undefined) ? false : useTris;
  18996. var i, il, j, p;
  18997. var u, v;
  18998. var stackCount = stacks + 1;
  18999. var sliceCount = slices + 1;
  19000. for ( i = 0; i <= stacks; i ++ ) {
  19001. v = i / stacks;
  19002. for ( j = 0; j <= slices; j ++ ) {
  19003. u = j / slices;
  19004. p = func( u, v );
  19005. verts.push( p );
  19006. }
  19007. }
  19008. var a, b, c, d;
  19009. var uva, uvb, uvc, uvd;
  19010. for ( i = 0; i < stacks; i ++ ) {
  19011. for ( j = 0; j < slices; j ++ ) {
  19012. a = i * sliceCount + j;
  19013. b = i * sliceCount + j + 1;
  19014. c = (i + 1) * sliceCount + j;
  19015. d = (i + 1) * sliceCount + j + 1;
  19016. uva = new THREE.UV( j / slices, i / stacks );
  19017. uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
  19018. uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
  19019. uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19020. if ( useTris ) {
  19021. faces.push( new THREE.Face3( a, b, c ) );
  19022. faces.push( new THREE.Face3( b, d, c ) );
  19023. uvs.push( [ uva, uvb, uvc ] );
  19024. uvs.push( [ uvb, uvd, uvc ] );
  19025. } else {
  19026. faces.push( new THREE.Face4( a, b, d, c ) );
  19027. uvs.push( [ uva, uvb, uvd, uvc ] );
  19028. }
  19029. }
  19030. }
  19031. // console.log(this);
  19032. // magic bullet
  19033. // var diff = this.mergeVertices();
  19034. // console.log('removed ', diff, ' vertices by merging');
  19035. this.computeCentroids();
  19036. this.computeFaceNormals();
  19037. this.computeVertexNormals();
  19038. };
  19039. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19040. /**
  19041. * @author qiao / https://github.com/qiao
  19042. * @fileoverview This is a convex hull generator using the incremental method.
  19043. * The complexity is O(n^2) where n is the number of vertices.
  19044. * O(nlogn) algorithms do exist, but they are much more complicated.
  19045. *
  19046. * Benchmark:
  19047. *
  19048. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19049. *
  19050. * Num Vertices Time(ms)
  19051. *
  19052. * 10 1
  19053. * 20 3
  19054. * 30 19
  19055. * 40 48
  19056. * 50 107
  19057. */
  19058. THREE.ConvexGeometry = function( vertices ) {
  19059. THREE.Geometry.call( this );
  19060. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19061. for ( var i = 3; i < vertices.length; i++ ) {
  19062. addPoint( i );
  19063. }
  19064. function addPoint( vertexId ) {
  19065. var vertex = vertices[ vertexId ].clone();
  19066. var mag = vertex.length();
  19067. vertex.x += mag * randomOffset();
  19068. vertex.y += mag * randomOffset();
  19069. vertex.z += mag * randomOffset();
  19070. var hole = [];
  19071. for ( var f = 0; f < faces.length; ) {
  19072. var face = faces[ f ];
  19073. // for each face, if the vertex can see it,
  19074. // then we try to add the face's edges into the hole.
  19075. if ( visible( face, vertex ) ) {
  19076. for ( var e = 0; e < 3; e++ ) {
  19077. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19078. var boundary = true;
  19079. // remove duplicated edges.
  19080. for ( var h = 0; h < hole.length; h++ ) {
  19081. if ( equalEdge( hole[ h ], edge ) ) {
  19082. hole[ h ] = hole[ hole.length - 1 ];
  19083. hole.pop();
  19084. boundary = false;
  19085. break;
  19086. }
  19087. }
  19088. if ( boundary ) {
  19089. hole.push( edge );
  19090. }
  19091. }
  19092. // remove faces[ f ]
  19093. faces[ f ] = faces[ faces.length - 1 ];
  19094. faces.pop();
  19095. } else { // not visible
  19096. f++;
  19097. }
  19098. }
  19099. // construct the new faces formed by the edges of the hole and the vertex
  19100. for ( var h = 0; h < hole.length; h++ ) {
  19101. faces.push( [
  19102. hole[ h ][ 0 ],
  19103. hole[ h ][ 1 ],
  19104. vertexId
  19105. ] );
  19106. }
  19107. }
  19108. /**
  19109. * Whether the face is visible from the vertex
  19110. */
  19111. function visible( face, vertex ) {
  19112. var va = vertices[ face[ 0 ] ];
  19113. var vb = vertices[ face[ 1 ] ];
  19114. var vc = vertices[ face[ 2 ] ];
  19115. var n = normal( va, vb, vc );
  19116. // distance from face to origin
  19117. var dist = n.dot( va );
  19118. return n.dot( vertex ) >= dist;
  19119. }
  19120. /**
  19121. * Face normal
  19122. */
  19123. function normal( va, vb, vc ) {
  19124. var cb = new THREE.Vector3();
  19125. var ab = new THREE.Vector3();
  19126. cb.sub( vc, vb );
  19127. ab.sub( va, vb );
  19128. cb.crossSelf( ab );
  19129. cb.normalize();
  19130. return cb;
  19131. }
  19132. /**
  19133. * Detect whether two edges are equal.
  19134. * Note that when constructing the convex hull, two same edges can only
  19135. * be of the negative direction.
  19136. */
  19137. function equalEdge( ea, eb ) {
  19138. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19139. }
  19140. /**
  19141. * Create a random offset between -1e-6 and 1e-6.
  19142. */
  19143. function randomOffset() {
  19144. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19145. }
  19146. /**
  19147. * XXX: Not sure if this is the correct approach. Need someone to review.
  19148. */
  19149. function vertexUv( vertex ) {
  19150. var mag = vertex.length();
  19151. return new THREE.UV( vertex.x / mag, vertex.y / mag );
  19152. }
  19153. // Push vertices into `this.vertices`, skipping those inside the hull
  19154. var id = 0;
  19155. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19156. for ( var i = 0; i < faces.length; i++ ) {
  19157. var face = faces[ i ];
  19158. for ( var j = 0; j < 3; j++ ) {
  19159. if ( newId[ face[ j ] ] === undefined ) {
  19160. newId[ face[ j ] ] = id++;
  19161. this.vertices.push( vertices[ face[ j ] ] );
  19162. }
  19163. face[ j ] = newId[ face[ j ] ];
  19164. }
  19165. }
  19166. // Convert faces into instances of THREE.Face3
  19167. for ( var i = 0; i < faces.length; i++ ) {
  19168. this.faces.push( new THREE.Face3(
  19169. faces[ i ][ 0 ],
  19170. faces[ i ][ 1 ],
  19171. faces[ i ][ 2 ]
  19172. ) );
  19173. }
  19174. // Compute UVs
  19175. for ( var i = 0; i < this.faces.length; i++ ) {
  19176. var face = this.faces[ i ];
  19177. this.faceVertexUvs[ 0 ].push( [
  19178. vertexUv( this.vertices[ face.a ] ),
  19179. vertexUv( this.vertices[ face.b ] ),
  19180. vertexUv( this.vertices[ face.c ])
  19181. ] );
  19182. }
  19183. this.computeCentroids();
  19184. this.computeFaceNormals();
  19185. this.computeVertexNormals();
  19186. };
  19187. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19188. /**
  19189. * @author sroucheray / http://sroucheray.org/
  19190. * @author mrdoob / http://mrdoob.com/
  19191. */
  19192. THREE.AxisHelper = function ( size ) {
  19193. var geometry = new THREE.Geometry();
  19194. geometry.vertices.push(
  19195. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  19196. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  19197. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  19198. );
  19199. geometry.colors.push(
  19200. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  19201. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  19202. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  19203. );
  19204. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19205. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19206. };
  19207. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19208. /**
  19209. * @author WestLangley / http://github.com/WestLangley
  19210. * @author zz85 / https://github.com/zz85
  19211. *
  19212. * Creates an arrow for visualizing directions
  19213. *
  19214. * Parameters:
  19215. * dir - Vector3
  19216. * origin - Vector3
  19217. * length - Number
  19218. * hex - color in hex value
  19219. */
  19220. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19221. THREE.Object3D.call( this );
  19222. if ( hex === undefined ) hex = 0xffff00;
  19223. if ( length === undefined ) length = 20;
  19224. var lineGeometry = new THREE.Geometry();
  19225. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19226. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19227. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19228. this.add( this.line );
  19229. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19230. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19231. this.cone.position.set( 0, 1, 0 );
  19232. this.add( this.cone );
  19233. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19234. this.setDirection( dir );
  19235. this.setLength( length );
  19236. };
  19237. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19238. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19239. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  19240. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  19241. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  19242. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  19243. };
  19244. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19245. this.scale.set( length, length, length );
  19246. };
  19247. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  19248. this.line.material.color.setHex( hex );
  19249. this.cone.material.color.setHex( hex );
  19250. };
  19251. /**
  19252. * @author alteredq / http://alteredqualia.com/
  19253. *
  19254. * - shows frustum, line of sight and up of the camera
  19255. * - suitable for fast updates
  19256. * - based on frustum visualization in lightgl.js shadowmap example
  19257. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  19258. */
  19259. THREE.CameraHelper = function ( camera ) {
  19260. THREE.Line.call( this );
  19261. var scope = this;
  19262. this.geometry = new THREE.Geometry();
  19263. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  19264. this.type = THREE.LinePieces;
  19265. this.matrixWorld = camera.matrixWorld;
  19266. this.matrixAutoUpdate = false;
  19267. this.pointMap = {};
  19268. // colors
  19269. var hexFrustum = 0xffaa00;
  19270. var hexCone = 0xff0000;
  19271. var hexUp = 0x00aaff;
  19272. var hexTarget = 0xffffff;
  19273. var hexCross = 0x333333;
  19274. // near
  19275. addLine( "n1", "n2", hexFrustum );
  19276. addLine( "n2", "n4", hexFrustum );
  19277. addLine( "n4", "n3", hexFrustum );
  19278. addLine( "n3", "n1", hexFrustum );
  19279. // far
  19280. addLine( "f1", "f2", hexFrustum );
  19281. addLine( "f2", "f4", hexFrustum );
  19282. addLine( "f4", "f3", hexFrustum );
  19283. addLine( "f3", "f1", hexFrustum );
  19284. // sides
  19285. addLine( "n1", "f1", hexFrustum );
  19286. addLine( "n2", "f2", hexFrustum );
  19287. addLine( "n3", "f3", hexFrustum );
  19288. addLine( "n4", "f4", hexFrustum );
  19289. // cone
  19290. addLine( "p", "n1", hexCone );
  19291. addLine( "p", "n2", hexCone );
  19292. addLine( "p", "n3", hexCone );
  19293. addLine( "p", "n4", hexCone );
  19294. // up
  19295. addLine( "u1", "u2", hexUp );
  19296. addLine( "u2", "u3", hexUp );
  19297. addLine( "u3", "u1", hexUp );
  19298. // target
  19299. addLine( "c", "t", hexTarget );
  19300. addLine( "p", "c", hexCross );
  19301. // cross
  19302. addLine( "cn1", "cn2", hexCross );
  19303. addLine( "cn3", "cn4", hexCross );
  19304. addLine( "cf1", "cf2", hexCross );
  19305. addLine( "cf3", "cf4", hexCross );
  19306. this.camera = camera;
  19307. function addLine( a, b, hex ) {
  19308. addPoint( a, hex );
  19309. addPoint( b, hex );
  19310. }
  19311. function addPoint( id, hex ) {
  19312. scope.geometry.vertices.push( new THREE.Vector3() );
  19313. scope.geometry.colors.push( new THREE.Color( hex ) );
  19314. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  19315. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  19316. }
  19317. this.update( camera );
  19318. };
  19319. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  19320. THREE.CameraHelper.prototype.update = function () {
  19321. var scope = this;
  19322. var w = 1, h = 1;
  19323. // we need just camera projection matrix
  19324. // world matrix must be identity
  19325. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  19326. // center / target
  19327. setPoint( "c", 0, 0, -1 );
  19328. setPoint( "t", 0, 0, 1 );
  19329. // near
  19330. setPoint( "n1", -w, -h, -1 );
  19331. setPoint( "n2", w, -h, -1 );
  19332. setPoint( "n3", -w, h, -1 );
  19333. setPoint( "n4", w, h, -1 );
  19334. // far
  19335. setPoint( "f1", -w, -h, 1 );
  19336. setPoint( "f2", w, -h, 1 );
  19337. setPoint( "f3", -w, h, 1 );
  19338. setPoint( "f4", w, h, 1 );
  19339. // up
  19340. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  19341. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  19342. setPoint( "u3", 0, h * 2, -1 );
  19343. // cross
  19344. setPoint( "cf1", -w, 0, 1 );
  19345. setPoint( "cf2", w, 0, 1 );
  19346. setPoint( "cf3", 0, -h, 1 );
  19347. setPoint( "cf4", 0, h, 1 );
  19348. setPoint( "cn1", -w, 0, -1 );
  19349. setPoint( "cn2", w, 0, -1 );
  19350. setPoint( "cn3", 0, -h, -1 );
  19351. setPoint( "cn4", 0, h, -1 );
  19352. function setPoint( point, x, y, z ) {
  19353. THREE.CameraHelper.__v.set( x, y, z );
  19354. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  19355. var points = scope.pointMap[ point ];
  19356. if ( points !== undefined ) {
  19357. for ( var i = 0, il = points.length; i < il; i ++ ) {
  19358. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  19359. }
  19360. }
  19361. }
  19362. this.geometry.verticesNeedUpdate = true;
  19363. };
  19364. THREE.CameraHelper.__projector = new THREE.Projector();
  19365. THREE.CameraHelper.__v = new THREE.Vector3();
  19366. THREE.CameraHelper.__c = new THREE.Camera();
  19367. /**
  19368. * @author alteredq / http://alteredqualia.com/
  19369. *
  19370. * - shows directional light color, intensity, position, orientation and target
  19371. */
  19372. THREE.DirectionalLightHelper = function ( light, sphereSize, arrowLength ) {
  19373. THREE.Object3D.call( this );
  19374. this.light = light;
  19375. // position
  19376. this.position = light.position;
  19377. // direction
  19378. this.direction = new THREE.Vector3();
  19379. this.direction.sub( light.target.position, light.position );
  19380. // color
  19381. this.color = light.color.clone();
  19382. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19383. this.color.r *= intensity;
  19384. this.color.g *= intensity;
  19385. this.color.b *= intensity;
  19386. var hexColor = this.color.getHex();
  19387. // light helper
  19388. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19389. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19390. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19391. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19392. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  19393. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19394. this.lightArrow.cone.material.fog = false;
  19395. this.lightArrow.line.material.fog = false;
  19396. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19397. this.add( this.lightArrow );
  19398. this.add( this.lightSphere );
  19399. this.add( this.lightRays );
  19400. this.lightSphere.properties.isGizmo = true;
  19401. this.lightSphere.properties.gizmoSubject = light;
  19402. this.lightSphere.properties.gizmoRoot = this;
  19403. // light target helper
  19404. this.targetSphere = null;
  19405. if ( light.target.properties.targetInverse ) {
  19406. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  19407. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  19408. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  19409. this.targetSphere.position = light.target.position;
  19410. this.targetSphere.properties.isGizmo = true;
  19411. this.targetSphere.properties.gizmoSubject = light.target;
  19412. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  19413. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  19414. var lineGeometry = new THREE.Geometry();
  19415. lineGeometry.vertices.push( this.position.clone() );
  19416. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  19417. lineGeometry.computeLineDistances();
  19418. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  19419. this.targetLine.properties.isGizmo = true;
  19420. }
  19421. //
  19422. this.properties.isGizmo = true;
  19423. }
  19424. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19425. THREE.DirectionalLightHelper.prototype.update = function () {
  19426. // update arrow orientation
  19427. // pointing from light to target
  19428. this.direction.sub( this.light.target.position, this.light.position );
  19429. this.lightArrow.setDirection( this.direction );
  19430. // update arrow, spheres, rays and line colors to light color * light intensity
  19431. this.color.copy( this.light.color );
  19432. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19433. this.color.r *= intensity;
  19434. this.color.g *= intensity;
  19435. this.color.b *= intensity;
  19436. this.lightArrow.setColor( this.color.getHex() );
  19437. this.lightSphere.material.color.copy( this.color );
  19438. this.lightRays.material.color.copy( this.color );
  19439. this.targetSphere.material.color.copy( this.color );
  19440. this.targetLine.material.color.copy( this.color );
  19441. // update target line vertices
  19442. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  19443. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  19444. this.targetLine.geometry.computeLineDistances();
  19445. this.targetLine.geometry.verticesNeedUpdate = true;
  19446. }
  19447. /**
  19448. * @author alteredq / http://alteredqualia.com/
  19449. *
  19450. * - shows hemisphere light intensity, sky and ground colors and directions
  19451. */
  19452. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  19453. THREE.Object3D.call( this );
  19454. this.light = light;
  19455. // position
  19456. this.position = light.position;
  19457. //
  19458. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19459. // sky color
  19460. this.color = light.color.clone();
  19461. this.color.r *= intensity;
  19462. this.color.g *= intensity;
  19463. this.color.b *= intensity;
  19464. var hexColor = this.color.getHex();
  19465. // ground color
  19466. this.groundColor = light.groundColor.clone();
  19467. this.groundColor.r *= intensity;
  19468. this.groundColor.g *= intensity;
  19469. this.groundColor.b *= intensity;
  19470. var hexColorGround = this.groundColor.getHex();
  19471. // double colored light bulb
  19472. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  19473. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  19474. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19475. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  19476. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  19477. bulbGeometry.faces[ i ].materialIndex = 0;
  19478. }
  19479. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  19480. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  19481. }
  19482. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  19483. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  19484. // arrows for sky and ground light directions
  19485. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  19486. this.lightArrow.rotation.x = Math.PI;
  19487. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  19488. var joint = new THREE.Object3D();
  19489. joint.rotation.x = -Math.PI * 0.5;
  19490. joint.add( this.lightSphere );
  19491. joint.add( this.lightArrow );
  19492. joint.add( this.lightArrowGround );
  19493. this.add( joint );
  19494. //
  19495. this.lightSphere.properties.isGizmo = true;
  19496. this.lightSphere.properties.gizmoSubject = light;
  19497. this.lightSphere.properties.gizmoRoot = this;
  19498. //
  19499. this.properties.isGizmo = true;
  19500. //
  19501. this.target = new THREE.Vector3();
  19502. this.lookAt( this.target );
  19503. }
  19504. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19505. THREE.HemisphereLightHelper.prototype.update = function () {
  19506. // update sphere sky and ground colors to light color * light intensity
  19507. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19508. this.color.copy( this.light.color );
  19509. this.groundColor.copy( this.light.groundColor );
  19510. this.color.r *= intensity;
  19511. this.color.g *= intensity;
  19512. this.color.b *= intensity;
  19513. this.groundColor.r *= intensity;
  19514. this.groundColor.g *= intensity;
  19515. this.groundColor.b *= intensity;
  19516. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  19517. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  19518. this.lightArrow.setColor( this.color.getHex() );
  19519. this.lightArrowGround.setColor( this.groundColor.getHex() );
  19520. this.lookAt( this.target );
  19521. }
  19522. /**
  19523. * @author alteredq / http://alteredqualia.com/
  19524. *
  19525. * - shows point light color, intensity, position and distance
  19526. */
  19527. THREE.PointLightHelper = function ( light, sphereSize ) {
  19528. THREE.Object3D.call( this );
  19529. this.light = light;
  19530. // position
  19531. this.position = light.position;
  19532. // color
  19533. this.color = light.color.clone();
  19534. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19535. this.color.r *= intensity;
  19536. this.color.g *= intensity;
  19537. this.color.b *= intensity;
  19538. var hexColor = this.color.getHex();
  19539. // light helper
  19540. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19541. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19542. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  19543. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19544. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19545. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  19546. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19547. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19548. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  19549. var d = light.distance;
  19550. if ( d === 0.0 ) {
  19551. this.lightDistance.visible = false;
  19552. } else {
  19553. this.lightDistance.scale.set( d, d, d );
  19554. }
  19555. this.add( this.lightSphere );
  19556. this.add( this.lightRays );
  19557. this.add( this.lightDistance );
  19558. //
  19559. this.lightSphere.properties.isGizmo = true;
  19560. this.lightSphere.properties.gizmoSubject = light;
  19561. this.lightSphere.properties.gizmoRoot = this;
  19562. //
  19563. this.properties.isGizmo = true;
  19564. }
  19565. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19566. THREE.PointLightHelper.prototype.update = function () {
  19567. // update sphere and rays colors to light color * light intensity
  19568. this.color.copy( this.light.color );
  19569. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19570. this.color.r *= intensity;
  19571. this.color.g *= intensity;
  19572. this.color.b *= intensity;
  19573. this.lightSphere.material.color.copy( this.color );
  19574. this.lightRays.material.color.copy( this.color );
  19575. this.lightDistance.material.color.copy( this.color );
  19576. //
  19577. var d = this.light.distance;
  19578. if ( d === 0.0 ) {
  19579. this.lightDistance.visible = false;
  19580. } else {
  19581. this.lightDistance.visible = true;
  19582. this.lightDistance.scale.set( d, d, d );
  19583. }
  19584. }
  19585. /**
  19586. * @author alteredq / http://alteredqualia.com/
  19587. *
  19588. * - shows spot light color, intensity, position, orientation, light cone and target
  19589. */
  19590. THREE.SpotLightHelper = function ( light, sphereSize, arrowLength ) {
  19591. THREE.Object3D.call( this );
  19592. this.light = light;
  19593. // position
  19594. this.position = light.position;
  19595. // direction
  19596. this.direction = new THREE.Vector3();
  19597. this.direction.sub( light.target.position, light.position );
  19598. // color
  19599. this.color = light.color.clone();
  19600. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19601. this.color.r *= intensity;
  19602. this.color.g *= intensity;
  19603. this.color.b *= intensity;
  19604. var hexColor = this.color.getHex();
  19605. // light helper
  19606. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19607. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19608. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  19609. var coneMatrix = new THREE.Matrix4();
  19610. coneMatrix.rotateX( -Math.PI/2 );
  19611. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  19612. coneGeometry.applyMatrix( coneMatrix );
  19613. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19614. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19615. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  19616. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  19617. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19618. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  19619. var coneLength = light.distance ? light.distance : 10000;
  19620. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  19621. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  19622. this.lightArrow.cone.material.fog = false;
  19623. this.lightArrow.line.material.fog = false;
  19624. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19625. this.gyroscope = new THREE.Gyroscope();
  19626. this.gyroscope.add( this.lightArrow );
  19627. this.gyroscope.add( this.lightSphere );
  19628. this.gyroscope.add( this.lightRays );
  19629. this.add( this.gyroscope );
  19630. this.add( this.lightCone );
  19631. this.lookAt( light.target.position );
  19632. this.lightSphere.properties.isGizmo = true;
  19633. this.lightSphere.properties.gizmoSubject = light;
  19634. this.lightSphere.properties.gizmoRoot = this;
  19635. // light target helper
  19636. this.targetSphere = null;
  19637. if ( light.target.properties.targetInverse ) {
  19638. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  19639. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  19640. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  19641. this.targetSphere.position = light.target.position;
  19642. this.targetSphere.properties.isGizmo = true;
  19643. this.targetSphere.properties.gizmoSubject = light.target;
  19644. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  19645. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  19646. var lineGeometry = new THREE.Geometry();
  19647. lineGeometry.vertices.push( this.position.clone() );
  19648. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  19649. lineGeometry.computeLineDistances();
  19650. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  19651. this.targetLine.properties.isGizmo = true;
  19652. }
  19653. //
  19654. this.properties.isGizmo = true;
  19655. }
  19656. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19657. THREE.SpotLightHelper.prototype.update = function () {
  19658. // update arrow orientation
  19659. // pointing from light to target
  19660. this.direction.sub( this.light.target.position, this.light.position );
  19661. this.lightArrow.setDirection( this.direction );
  19662. // update light cone orientation and size
  19663. this.lookAt( this.light.target.position );
  19664. var coneLength = this.light.distance ? this.light.distance : 10000;
  19665. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  19666. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  19667. // update arrow, spheres, rays and line colors to light color * light intensity
  19668. this.color.copy( this.light.color );
  19669. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19670. this.color.r *= intensity;
  19671. this.color.g *= intensity;
  19672. this.color.b *= intensity;
  19673. this.lightArrow.setColor( this.color.getHex() );
  19674. this.lightSphere.material.color.copy( this.color );
  19675. this.lightRays.material.color.copy( this.color );
  19676. this.lightCone.material.color.copy( this.color );
  19677. this.targetSphere.material.color.copy( this.color );
  19678. this.targetLine.material.color.copy( this.color );
  19679. // update target line vertices
  19680. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  19681. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  19682. this.targetLine.geometry.computeLineDistances();
  19683. this.targetLine.geometry.verticesNeedUpdate = true;
  19684. }
  19685. /*
  19686. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19687. *
  19688. * Subdivision Geometry Modifier
  19689. * using Catmull-Clark Subdivision Surfaces
  19690. * for creating smooth geometry meshes
  19691. *
  19692. * Note: a modifier modifies vertices and faces of geometry,
  19693. * so use geometry.clone() if original geometry needs to be retained
  19694. *
  19695. * Readings:
  19696. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19697. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  19698. * http://xrt.wikidot.com/blog:31
  19699. * "Subdivision Surfaces in Character Animation"
  19700. *
  19701. * (on boundary edges)
  19702. * http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19703. * https://graphics.stanford.edu/wikis/cs148-09-summer/Assignment3Description
  19704. *
  19705. * Supports:
  19706. * Closed and Open geometries.
  19707. *
  19708. * TODO:
  19709. * crease vertex and "semi-sharp" features
  19710. * selective subdivision
  19711. */
  19712. THREE.SubdivisionModifier = function( subdivisions ) {
  19713. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  19714. // Settings
  19715. this.useOldVertexColors = false;
  19716. this.supportUVs = true;
  19717. this.debug = false;
  19718. };
  19719. // Applies the "modify" pattern
  19720. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  19721. var repeats = this.subdivisions;
  19722. while ( repeats-- > 0 ) {
  19723. this.smooth( geometry );
  19724. }
  19725. };
  19726. /// REFACTORING THIS OUT
  19727. THREE.GeometryUtils.orderedKey = function ( a, b ) {
  19728. return Math.min( a, b ) + "_" + Math.max( a, b );
  19729. };
  19730. // Returns a hashmap - of { edge_key: face_index }
  19731. THREE.GeometryUtils.computeEdgeFaces = function ( geometry ) {
  19732. var i, il, v1, v2, j, k,
  19733. face, faceIndices, faceIndex,
  19734. edge,
  19735. hash,
  19736. edgeFaceMap = {};
  19737. var orderedKey = THREE.GeometryUtils.orderedKey;
  19738. function mapEdgeHash( hash, i ) {
  19739. if ( edgeFaceMap[ hash ] === undefined ) {
  19740. edgeFaceMap[ hash ] = [];
  19741. }
  19742. edgeFaceMap[ hash ].push( i );
  19743. }
  19744. // construct vertex -> face map
  19745. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  19746. face = geometry.faces[ i ];
  19747. if ( face instanceof THREE.Face3 ) {
  19748. hash = orderedKey( face.a, face.b );
  19749. mapEdgeHash( hash, i );
  19750. hash = orderedKey( face.b, face.c );
  19751. mapEdgeHash( hash, i );
  19752. hash = orderedKey( face.c, face.a );
  19753. mapEdgeHash( hash, i );
  19754. } else if ( face instanceof THREE.Face4 ) {
  19755. hash = orderedKey( face.a, face.b );
  19756. mapEdgeHash( hash, i );
  19757. hash = orderedKey( face.b, face.c );
  19758. mapEdgeHash( hash, i );
  19759. hash = orderedKey( face.c, face.d );
  19760. mapEdgeHash( hash, i );
  19761. hash = orderedKey( face.d, face.a );
  19762. mapEdgeHash( hash, i );
  19763. }
  19764. }
  19765. // extract faces
  19766. // var edges = [];
  19767. //
  19768. // var numOfEdges = 0;
  19769. // for (i in edgeFaceMap) {
  19770. // numOfEdges++;
  19771. //
  19772. // edge = edgeFaceMap[i];
  19773. // edges.push(edge);
  19774. //
  19775. // }
  19776. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  19777. return edgeFaceMap;
  19778. }
  19779. /////////////////////////////
  19780. // Performs an iteration of Catmull-Clark Subdivision
  19781. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  19782. //debug( 'running smooth' );
  19783. // New set of vertices, faces and uvs
  19784. var newVertices = [], newFaces = [], newUVs = [];
  19785. function v( x, y, z ) {
  19786. newVertices.push( new THREE.Vector3( x, y, z ) );
  19787. }
  19788. var scope = this;
  19789. var orderedKey = THREE.GeometryUtils.orderedKey;
  19790. var computeEdgeFaces = THREE.GeometryUtils.computeEdgeFaces;
  19791. function assert() {
  19792. if (scope.debug && console && console.assert) console.assert.apply(console, arguments);
  19793. }
  19794. function debug() {
  19795. if (scope.debug) console.log.apply(console, arguments);
  19796. }
  19797. function warn() {
  19798. if (console)
  19799. console.log.apply(console, arguments);
  19800. }
  19801. function f4( a, b, c, d, oldFace, orders, facei ) {
  19802. // TODO move vertex selection over here!
  19803. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  19804. if (scope.useOldVertexColors) {
  19805. newFace.vertexColors = [];
  19806. var color, tmpColor, order;
  19807. for (var i=0;i<4;i++) {
  19808. order = orders[i];
  19809. color = new THREE.Color(),
  19810. color.setRGB(0,0,0);
  19811. for (var j=0, jl=0; j<order.length;j++) {
  19812. tmpColor = oldFace.vertexColors[order[j]-1];
  19813. color.r += tmpColor.r;
  19814. color.g += tmpColor.g;
  19815. color.b += tmpColor.b;
  19816. }
  19817. color.r /= order.length;
  19818. color.g /= order.length;
  19819. color.b /= order.length;
  19820. newFace.vertexColors[i] = color;
  19821. }
  19822. }
  19823. newFaces.push( newFace );
  19824. if (scope.supportUVs) {
  19825. var aUv = [
  19826. getUV(a, ''),
  19827. getUV(b, facei),
  19828. getUV(c, facei),
  19829. getUV(d, facei)
  19830. ];
  19831. if (!aUv[0]) debug('a :( ', a+':'+facei);
  19832. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  19833. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  19834. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  19835. else
  19836. newUVs.push( aUv );
  19837. }
  19838. }
  19839. var originalPoints = oldGeometry.vertices;
  19840. var originalFaces = oldGeometry.faces;
  19841. var originalVerticesLength = originalPoints.length;
  19842. var newPoints = originalPoints.concat(); // New set of vertices to work on
  19843. var facePoints = [], // these are new points on exisiting faces
  19844. edgePoints = {}; // these are new points on exisiting edges
  19845. var sharpEdges = {}, sharpVertices = []; // Mark edges and vertices to prevent smoothening on them
  19846. // TODO: handle this correctly.
  19847. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  19848. function debugCoreStuff() {
  19849. console.log('facePoints', facePoints, 'edgePoints', edgePoints);
  19850. console.log('edgeFaceMap', edgeFaceMap, 'vertexEdgeMap', vertexEdgeMap);
  19851. }
  19852. function getUV(vertexNo, oldFaceNo) {
  19853. var j,jl;
  19854. var key = vertexNo+':'+oldFaceNo;
  19855. var theUV = uvForVertices[key];
  19856. if (!theUV) {
  19857. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  19858. debug('face pt');
  19859. } else {
  19860. debug('edge pt');
  19861. }
  19862. warn('warning, UV not found for', key);
  19863. return null;
  19864. }
  19865. return theUV;
  19866. // Original faces -> Vertex Nos.
  19867. // new Facepoint -> Vertex Nos.
  19868. // edge Points
  19869. }
  19870. function addUV(vertexNo, oldFaceNo, value) {
  19871. var key = vertexNo+':'+oldFaceNo;
  19872. if (!(key in uvForVertices)) {
  19873. uvForVertices[key] = value;
  19874. } else {
  19875. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  19876. }
  19877. }
  19878. // Step 1
  19879. // For each face, add a face point
  19880. // Set each face point to be the centroid of all original points for the respective face.
  19881. // debug(oldGeometry);
  19882. var i, il, j, jl, face;
  19883. // For Uvs
  19884. var uvs = oldGeometry.faceVertexUvs[0];
  19885. var abcd = 'abcd', vertice;
  19886. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  19887. if (scope.supportUVs)
  19888. for (i=0, il = uvs.length; i<il; i++ ) {
  19889. for (j=0,jl=uvs[i].length;j<jl;j++) {
  19890. vertice = originalFaces[i][abcd.charAt(j)];
  19891. addUV(vertice, i, uvs[i][j]);
  19892. }
  19893. }
  19894. if (uvs.length == 0) scope.supportUVs = false;
  19895. // Additional UVs check, if we index original
  19896. var uvCount = 0;
  19897. for (var u in uvForVertices) {
  19898. uvCount++;
  19899. }
  19900. if (!uvCount) {
  19901. scope.supportUVs = false;
  19902. debug('no uvs');
  19903. }
  19904. var avgUv ;
  19905. for (i=0, il = originalFaces.length; i<il ;i++) {
  19906. face = originalFaces[ i ];
  19907. facePoints.push( face.centroid );
  19908. newPoints.push( face.centroid );
  19909. if (!scope.supportUVs) continue;
  19910. // Prepare subdivided uv
  19911. avgUv = new THREE.UV();
  19912. if ( face instanceof THREE.Face3 ) {
  19913. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  19914. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  19915. avgUv.u /= 3;
  19916. avgUv.v /= 3;
  19917. } else if ( face instanceof THREE.Face4 ) {
  19918. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  19919. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  19920. avgUv.u /= 4;
  19921. avgUv.v /= 4;
  19922. }
  19923. addUV(originalVerticesLength + i, '', avgUv);
  19924. }
  19925. // Step 2
  19926. // For each edge, add an edge point.
  19927. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  19928. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index eg { edge_key: [face_index, face_index2 ]}
  19929. var edge, faceIndexA, faceIndexB, avg;
  19930. // debug('edgeFaceMap', edgeFaceMap);
  19931. var edgeCount = 0;
  19932. var edgeVertex, edgeVertexA, edgeVertexB;
  19933. ////
  19934. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  19935. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  19936. function addVertexEdgeMap(vertex, edge) {
  19937. if (vertexEdgeMap[vertex]===undefined) {
  19938. vertexEdgeMap[vertex] = [];
  19939. }
  19940. vertexEdgeMap[vertex].push(edge);
  19941. }
  19942. function addVertexFaceMap(vertex, face, edge) {
  19943. if (vertexFaceMap[vertex]===undefined) {
  19944. vertexFaceMap[vertex] = {};
  19945. }
  19946. vertexFaceMap[vertex][face] = edge;
  19947. // vertexFaceMap[vertex][face] = null;
  19948. }
  19949. // Prepares vertexEdgeMap and vertexFaceMap
  19950. for (i in edgeFaceMap) { // This is for every edge
  19951. edge = edgeFaceMap[i];
  19952. edgeVertex = i.split('_');
  19953. edgeVertexA = edgeVertex[0];
  19954. edgeVertexB = edgeVertex[1];
  19955. // Maps an edgeVertex to connecting edges
  19956. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  19957. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  19958. for (j=0,jl=edge.length;j<jl;j++) {
  19959. face = edge[j];
  19960. addVertexFaceMap(edgeVertexA, face, i);
  19961. addVertexFaceMap(edgeVertexB, face, i);
  19962. }
  19963. // {edge vertex: { face1: edge_key, face2: edge_key.. } }
  19964. // this thing is fishy right now.
  19965. if (edge.length < 2) {
  19966. // edge is "sharp";
  19967. sharpEdges[i] = true;
  19968. sharpVertices[edgeVertexA] = true;
  19969. sharpVertices[edgeVertexB] = true;
  19970. }
  19971. }
  19972. for (i in edgeFaceMap) {
  19973. edge = edgeFaceMap[i];
  19974. faceIndexA = edge[0]; // face index a
  19975. faceIndexB = edge[1]; // face index b
  19976. edgeVertex = i.split('_');
  19977. edgeVertexA = edgeVertex[0];
  19978. edgeVertexB = edgeVertex[1];
  19979. avg = new THREE.Vector3();
  19980. //debug(i, faceIndexB,facePoints[faceIndexB]);
  19981. assert(edge.length > 0, 'an edge without faces?!');
  19982. if (edge.length==1) {
  19983. avg.addSelf(originalPoints[edgeVertexA]);
  19984. avg.addSelf(originalPoints[edgeVertexB]);
  19985. avg.multiplyScalar(0.5);
  19986. sharpVertices[newPoints.length] = true;
  19987. } else {
  19988. avg.addSelf(facePoints[faceIndexA]);
  19989. avg.addSelf(facePoints[faceIndexB]);
  19990. avg.addSelf(originalPoints[edgeVertexA]);
  19991. avg.addSelf(originalPoints[edgeVertexB]);
  19992. avg.multiplyScalar(0.25);
  19993. }
  19994. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  19995. newPoints.push( avg );
  19996. edgeCount ++;
  19997. if (!scope.supportUVs) {
  19998. continue;
  19999. }
  20000. // Prepare subdivided uv
  20001. avgUv = new THREE.UV();
  20002. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  20003. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  20004. avgUv.u /= 2;
  20005. avgUv.v /= 2;
  20006. addUV(edgePoints[i], faceIndexA, avgUv);
  20007. if (edge.length>=2) {
  20008. assert(edge.length == 2, 'did we plan for more than 2 edges?');
  20009. avgUv = new THREE.UV();
  20010. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  20011. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  20012. avgUv.u /= 2;
  20013. avgUv.v /= 2;
  20014. addUV(edgePoints[i], faceIndexB, avgUv);
  20015. }
  20016. }
  20017. debug('-- Step 2 done');
  20018. // Step 3
  20019. // For each face point, add an edge for every edge of the face,
  20020. // connecting the face point to each edge point for the face.
  20021. var facePt, currentVerticeIndex;
  20022. var hashAB, hashBC, hashCD, hashDA, hashCA;
  20023. var abc123 = ['123', '12', '2', '23'];
  20024. var bca123 = ['123', '23', '3', '31'];
  20025. var cab123 = ['123', '31', '1', '12'];
  20026. var abc1234 = ['1234', '12', '2', '23'];
  20027. var bcd1234 = ['1234', '23', '3', '34'];
  20028. var cda1234 = ['1234', '34', '4', '41'];
  20029. var dab1234 = ['1234', '41', '1', '12'];
  20030. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  20031. facePt = facePoints[i];
  20032. face = originalFaces[i];
  20033. currentVerticeIndex = originalVerticesLength+ i;
  20034. if ( face instanceof THREE.Face3 ) {
  20035. // create 3 face4s
  20036. hashAB = orderedKey( face.a, face.b );
  20037. hashBC = orderedKey( face.b, face.c );
  20038. hashCA = orderedKey( face.c, face.a );
  20039. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  20040. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  20041. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  20042. } else if ( face instanceof THREE.Face4 ) {
  20043. // create 4 face4s
  20044. hashAB = orderedKey( face.a, face.b );
  20045. hashBC = orderedKey( face.b, face.c );
  20046. hashCD = orderedKey( face.c, face.d );
  20047. hashDA = orderedKey( face.d, face.a );
  20048. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  20049. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  20050. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  20051. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  20052. } else {
  20053. debug('face should be a face!', face);
  20054. }
  20055. }
  20056. newVertices = newPoints;
  20057. // Step 4
  20058. // For each original point P,
  20059. // take the average F of all n face points for faces touching P,
  20060. // and take the average R of all n edge midpoints for edges touching P,
  20061. // where each edge midpoint is the average of its two endpoint vertices.
  20062. // Move each original point to the point
  20063. var F = new THREE.Vector3();
  20064. var R = new THREE.Vector3();
  20065. var n;
  20066. for (i=0, il = originalPoints.length; i<il; i++) {
  20067. // (F + 2R + (n-3)P) / n
  20068. if (vertexEdgeMap[i]===undefined) continue;
  20069. F.set(0,0,0);
  20070. R.set(0,0,0);
  20071. var newPos = new THREE.Vector3(0,0,0);
  20072. var f = 0; // this counts number of faces, original vertex is connected to (also known as valance?)
  20073. for (j in vertexFaceMap[i]) {
  20074. F.addSelf(facePoints[j]);
  20075. f++;
  20076. }
  20077. var sharpEdgeCount = 0;
  20078. n = vertexEdgeMap[i].length; // given a vertex, return its connecting edges
  20079. // Are we on the border?
  20080. var boundary_case = f != n;
  20081. // if (boundary_case) {
  20082. // console.error('moo', 'o', i, 'faces touched', f, 'edges', n, n == 2);
  20083. // }
  20084. for (j=0;j<n;j++) {
  20085. if (
  20086. sharpEdges[
  20087. orderedKey(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  20088. ]) {
  20089. sharpEdgeCount++;
  20090. }
  20091. }
  20092. // if ( sharpEdgeCount==2 ) {
  20093. // continue;
  20094. // // Do not move vertex if there's 2 connecting sharp edges.
  20095. // }
  20096. /*
  20097. if (sharpEdgeCount>2) {
  20098. // TODO
  20099. }
  20100. */
  20101. F.divideScalar(f);
  20102. var boundary_edges = 0;
  20103. if (boundary_case) {
  20104. var bb_edge;
  20105. for (j=0; j<n;j++) {
  20106. edge = vertexEdgeMap[i][j];
  20107. bb_edge = edgeFaceMap[orderedKey(edge[0], edge[1])].length == 1
  20108. if (bb_edge) {
  20109. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20110. R.addSelf(midPt);
  20111. boundary_edges++;
  20112. }
  20113. }
  20114. R.divideScalar(4);
  20115. // console.log(j + ' --- ' + n + ' --- ' + boundary_edges);
  20116. assert(boundary_edges == 2, 'should have only 2 boundary edges');
  20117. } else {
  20118. for (j=0; j<n;j++) {
  20119. edge = vertexEdgeMap[i][j];
  20120. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20121. R.addSelf(midPt);
  20122. }
  20123. R.divideScalar(n);
  20124. }
  20125. // Sum the formula
  20126. newPos.addSelf(originalPoints[i]);
  20127. if (boundary_case) {
  20128. newPos.divideScalar(2);
  20129. newPos.addSelf(R);
  20130. } else {
  20131. newPos.multiplyScalar(n - 3);
  20132. newPos.addSelf(F);
  20133. newPos.addSelf(R.multiplyScalar(2));
  20134. newPos.divideScalar(n);
  20135. }
  20136. newVertices[i] = newPos;
  20137. }
  20138. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  20139. newGeometry.vertices = newVertices;
  20140. newGeometry.faces = newFaces;
  20141. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  20142. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  20143. newGeometry.computeCentroids();
  20144. newGeometry.computeFaceNormals();
  20145. newGeometry.computeVertexNormals();
  20146. };
  20147. /**
  20148. * @author alteredq / http://alteredqualia.com/
  20149. */
  20150. THREE.ImmediateRenderObject = function ( ) {
  20151. THREE.Object3D.call( this );
  20152. this.render = function ( renderCallback ) { };
  20153. };
  20154. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20155. /**
  20156. * @author mikael emtinger / http://gomo.se/
  20157. * @author alteredq / http://alteredqualia.com/
  20158. */
  20159. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20160. THREE.Object3D.call( this );
  20161. this.lensFlares = [];
  20162. this.positionScreen = new THREE.Vector3();
  20163. this.customUpdateCallback = undefined;
  20164. if( texture !== undefined ) {
  20165. this.add( texture, size, distance, blending, color );
  20166. }
  20167. };
  20168. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20169. /*
  20170. * Add: adds another flare
  20171. */
  20172. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20173. if( size === undefined ) size = -1;
  20174. if( distance === undefined ) distance = 0;
  20175. if( opacity === undefined ) opacity = 1;
  20176. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20177. if( blending === undefined ) blending = THREE.NormalBlending;
  20178. distance = Math.min( distance, Math.max( 0, distance ) );
  20179. this.lensFlares.push( { texture: texture, // THREE.Texture
  20180. size: size, // size in pixels (-1 = use texture.width)
  20181. distance: distance, // distance (0-1) from light source (0=at light source)
  20182. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20183. scale: 1, // scale
  20184. rotation: 1, // rotation
  20185. opacity: opacity, // opacity
  20186. color: color, // color
  20187. blending: blending } ); // blending
  20188. };
  20189. /*
  20190. * Update lens flares update positions on all flares based on the screen position
  20191. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20192. */
  20193. THREE.LensFlare.prototype.updateLensFlares = function () {
  20194. var f, fl = this.lensFlares.length;
  20195. var flare;
  20196. var vecX = -this.positionScreen.x * 2;
  20197. var vecY = -this.positionScreen.y * 2;
  20198. for( f = 0; f < fl; f ++ ) {
  20199. flare = this.lensFlares[ f ];
  20200. flare.x = this.positionScreen.x + vecX * flare.distance;
  20201. flare.y = this.positionScreen.y + vecY * flare.distance;
  20202. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20203. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20204. }
  20205. };
  20206. /**
  20207. * @author alteredq / http://alteredqualia.com/
  20208. */
  20209. THREE.MorphBlendMesh = function( geometry, material ) {
  20210. THREE.Mesh.call( this, geometry, material );
  20211. this.animationsMap = {};
  20212. this.animationsList = [];
  20213. // prepare default animation
  20214. // (all frames played together in 1 second)
  20215. var numFrames = this.geometry.morphTargets.length;
  20216. var name = "__default";
  20217. var startFrame = 0;
  20218. var endFrame = numFrames - 1;
  20219. var fps = numFrames / 1;
  20220. this.createAnimation( name, startFrame, endFrame, fps );
  20221. this.setAnimationWeight( name, 1 );
  20222. };
  20223. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20224. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20225. var animation = {
  20226. startFrame: start,
  20227. endFrame: end,
  20228. length: end - start + 1,
  20229. fps: fps,
  20230. duration: ( end - start ) / fps,
  20231. lastFrame: 0,
  20232. currentFrame: 0,
  20233. active: false,
  20234. time: 0,
  20235. direction: 1,
  20236. weight: 1,
  20237. directionBackwards: false,
  20238. mirroredLoop: false
  20239. };
  20240. this.animationsMap[ name ] = animation;
  20241. this.animationsList.push( animation );
  20242. };
  20243. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20244. var pattern = /([a-z]+)(\d+)/;
  20245. var firstAnimation, frameRanges = {};
  20246. var geometry = this.geometry;
  20247. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20248. var morph = geometry.morphTargets[ i ];
  20249. var chunks = morph.name.match( pattern );
  20250. if ( chunks && chunks.length > 1 ) {
  20251. var name = chunks[ 1 ];
  20252. var num = chunks[ 2 ];
  20253. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20254. var range = frameRanges[ name ];
  20255. if ( i < range.start ) range.start = i;
  20256. if ( i > range.end ) range.end = i;
  20257. if ( ! firstAnimation ) firstAnimation = name;
  20258. }
  20259. }
  20260. for ( var name in frameRanges ) {
  20261. var range = frameRanges[ name ];
  20262. this.createAnimation( name, range.start, range.end, fps );
  20263. }
  20264. this.firstAnimation = firstAnimation;
  20265. };
  20266. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20267. var animation = this.animationsMap[ name ];
  20268. if ( animation ) {
  20269. animation.direction = 1;
  20270. animation.directionBackwards = false;
  20271. }
  20272. };
  20273. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20274. var animation = this.animationsMap[ name ];
  20275. if ( animation ) {
  20276. animation.direction = -1;
  20277. animation.directionBackwards = true;
  20278. }
  20279. };
  20280. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20281. var animation = this.animationsMap[ name ];
  20282. if ( animation ) {
  20283. animation.fps = fps;
  20284. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20285. }
  20286. };
  20287. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20288. var animation = this.animationsMap[ name ];
  20289. if ( animation ) {
  20290. animation.duration = duration;
  20291. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20292. }
  20293. };
  20294. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20295. var animation = this.animationsMap[ name ];
  20296. if ( animation ) {
  20297. animation.weight = weight;
  20298. }
  20299. };
  20300. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20301. var animation = this.animationsMap[ name ];
  20302. if ( animation ) {
  20303. animation.time = time;
  20304. }
  20305. };
  20306. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20307. var time = 0;
  20308. var animation = this.animationsMap[ name ];
  20309. if ( animation ) {
  20310. time = animation.time;
  20311. }
  20312. return time;
  20313. };
  20314. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20315. var duration = -1;
  20316. var animation = this.animationsMap[ name ];
  20317. if ( animation ) {
  20318. duration = animation.duration;
  20319. }
  20320. return duration;
  20321. };
  20322. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20323. var animation = this.animationsMap[ name ];
  20324. if ( animation ) {
  20325. animation.time = 0;
  20326. animation.active = true;
  20327. } else {
  20328. console.warn( "animation[" + name + "] undefined" );
  20329. }
  20330. };
  20331. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20332. var animation = this.animationsMap[ name ];
  20333. if ( animation ) {
  20334. animation.active = false;
  20335. }
  20336. };
  20337. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20338. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20339. var animation = this.animationsList[ i ];
  20340. if ( ! animation.active ) continue;
  20341. var frameTime = animation.duration / animation.length;
  20342. animation.time += animation.direction * delta;
  20343. if ( animation.mirroredLoop ) {
  20344. if ( animation.time > animation.duration || animation.time < 0 ) {
  20345. animation.direction *= -1;
  20346. if ( animation.time > animation.duration ) {
  20347. animation.time = animation.duration;
  20348. animation.directionBackwards = true;
  20349. }
  20350. if ( animation.time < 0 ) {
  20351. animation.time = 0;
  20352. animation.directionBackwards = false;
  20353. }
  20354. }
  20355. } else {
  20356. animation.time = animation.time % animation.duration;
  20357. if ( animation.time < 0 ) animation.time += animation.duration;
  20358. }
  20359. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20360. var weight = animation.weight;
  20361. if ( keyframe !== animation.currentFrame ) {
  20362. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20363. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20364. this.morphTargetInfluences[ keyframe ] = 0;
  20365. animation.lastFrame = animation.currentFrame;
  20366. animation.currentFrame = keyframe;
  20367. }
  20368. var mix = ( animation.time % frameTime ) / frameTime;
  20369. if ( animation.directionBackwards ) mix = 1 - mix;
  20370. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20371. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20372. }
  20373. };
  20374. /**
  20375. * @author mikael emtinger / http://gomo.se/
  20376. * @author alteredq / http://alteredqualia.com/
  20377. */
  20378. THREE.LensFlarePlugin = function ( ) {
  20379. var _gl, _renderer, _lensFlare = {};
  20380. this.init = function ( renderer ) {
  20381. _gl = renderer.context;
  20382. _renderer = renderer;
  20383. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20384. _lensFlare.faces = new Uint16Array( 6 );
  20385. var i = 0;
  20386. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20387. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20388. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20389. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20390. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20391. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20392. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20393. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20394. i = 0;
  20395. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20396. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20397. // buffers
  20398. _lensFlare.vertexBuffer = _gl.createBuffer();
  20399. _lensFlare.elementBuffer = _gl.createBuffer();
  20400. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20401. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20402. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20403. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20404. // textures
  20405. _lensFlare.tempTexture = _gl.createTexture();
  20406. _lensFlare.occlusionTexture = _gl.createTexture();
  20407. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20408. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20409. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20410. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20411. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20412. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20413. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20414. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20415. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20416. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20417. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20418. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20419. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20420. _lensFlare.hasVertexTexture = false;
  20421. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  20422. } else {
  20423. _lensFlare.hasVertexTexture = true;
  20424. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  20425. }
  20426. _lensFlare.attributes = {};
  20427. _lensFlare.uniforms = {};
  20428. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20429. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20430. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20431. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20432. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20433. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20434. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20435. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20436. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20437. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20438. };
  20439. /*
  20440. * Render lens flares
  20441. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20442. * reads these back and calculates occlusion.
  20443. * Then _lensFlare.update_lensFlares() is called to re-position and
  20444. * update transparency of flares. Then they are rendered.
  20445. *
  20446. */
  20447. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20448. var flares = scene.__webglFlares,
  20449. nFlares = flares.length;
  20450. if ( ! nFlares ) return;
  20451. var tempPosition = new THREE.Vector3();
  20452. var invAspect = viewportHeight / viewportWidth,
  20453. halfViewportWidth = viewportWidth * 0.5,
  20454. halfViewportHeight = viewportHeight * 0.5;
  20455. var size = 16 / viewportHeight,
  20456. scale = new THREE.Vector2( size * invAspect, size );
  20457. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20458. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20459. var uniforms = _lensFlare.uniforms,
  20460. attributes = _lensFlare.attributes;
  20461. // set _lensFlare program and reset blending
  20462. _gl.useProgram( _lensFlare.program );
  20463. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20464. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20465. // loop through all lens flares to update their occlusion and positions
  20466. // setup gl and common used attribs/unforms
  20467. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20468. _gl.uniform1i( uniforms.map, 1 );
  20469. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20470. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20471. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20472. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20473. _gl.disable( _gl.CULL_FACE );
  20474. _gl.depthMask( false );
  20475. var i, j, jl, flare, sprite;
  20476. for ( i = 0; i < nFlares; i ++ ) {
  20477. size = 16 / viewportHeight;
  20478. scale.set( size * invAspect, size );
  20479. // calc object screen position
  20480. flare = flares[ i ];
  20481. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20482. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  20483. camera.projectionMatrix.multiplyVector3( tempPosition );
  20484. // setup arrays for gl programs
  20485. screenPosition.copy( tempPosition )
  20486. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20487. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20488. // screen cull
  20489. if ( _lensFlare.hasVertexTexture || (
  20490. screenPositionPixels.x > 0 &&
  20491. screenPositionPixels.x < viewportWidth &&
  20492. screenPositionPixels.y > 0 &&
  20493. screenPositionPixels.y < viewportHeight ) ) {
  20494. // save current RGB to temp texture
  20495. _gl.activeTexture( _gl.TEXTURE1 );
  20496. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20497. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20498. // render pink quad
  20499. _gl.uniform1i( uniforms.renderType, 0 );
  20500. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20501. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20502. _gl.disable( _gl.BLEND );
  20503. _gl.enable( _gl.DEPTH_TEST );
  20504. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20505. // copy result to occlusionMap
  20506. _gl.activeTexture( _gl.TEXTURE0 );
  20507. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20508. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20509. // restore graphics
  20510. _gl.uniform1i( uniforms.renderType, 1 );
  20511. _gl.disable( _gl.DEPTH_TEST );
  20512. _gl.activeTexture( _gl.TEXTURE1 );
  20513. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20514. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20515. // update object positions
  20516. flare.positionScreen.copy( screenPosition )
  20517. if ( flare.customUpdateCallback ) {
  20518. flare.customUpdateCallback( flare );
  20519. } else {
  20520. flare.updateLensFlares();
  20521. }
  20522. // render flares
  20523. _gl.uniform1i( uniforms.renderType, 2 );
  20524. _gl.enable( _gl.BLEND );
  20525. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20526. sprite = flare.lensFlares[ j ];
  20527. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20528. screenPosition.x = sprite.x;
  20529. screenPosition.y = sprite.y;
  20530. screenPosition.z = sprite.z;
  20531. size = sprite.size * sprite.scale / viewportHeight;
  20532. scale.x = size * invAspect;
  20533. scale.y = size;
  20534. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20535. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20536. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20537. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20538. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20539. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20540. _renderer.setTexture( sprite.texture, 1 );
  20541. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20542. }
  20543. }
  20544. }
  20545. }
  20546. // restore gl
  20547. _gl.enable( _gl.CULL_FACE );
  20548. _gl.enable( _gl.DEPTH_TEST );
  20549. _gl.depthMask( true );
  20550. };
  20551. function createProgram ( shader ) {
  20552. var program = _gl.createProgram();
  20553. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20554. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20555. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20556. _gl.shaderSource( vertexShader, shader.vertexShader );
  20557. _gl.compileShader( fragmentShader );
  20558. _gl.compileShader( vertexShader );
  20559. _gl.attachShader( program, fragmentShader );
  20560. _gl.attachShader( program, vertexShader );
  20561. _gl.linkProgram( program );
  20562. return program;
  20563. };
  20564. };/**
  20565. * @author alteredq / http://alteredqualia.com/
  20566. */
  20567. THREE.ShadowMapPlugin = function ( ) {
  20568. var _gl,
  20569. _renderer,
  20570. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20571. _frustum = new THREE.Frustum(),
  20572. _projScreenMatrix = new THREE.Matrix4(),
  20573. _min = new THREE.Vector3(),
  20574. _max = new THREE.Vector3();
  20575. this.init = function ( renderer ) {
  20576. _gl = renderer.context;
  20577. _renderer = renderer;
  20578. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20579. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20580. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20581. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20582. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20583. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20584. _depthMaterial._shadowPass = true;
  20585. _depthMaterialMorph._shadowPass = true;
  20586. _depthMaterialSkin._shadowPass = true;
  20587. _depthMaterialMorphSkin._shadowPass = true;
  20588. };
  20589. this.render = function ( scene, camera ) {
  20590. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20591. this.update( scene, camera );
  20592. };
  20593. this.update = function ( scene, camera ) {
  20594. var i, il, j, jl, n,
  20595. shadowMap, shadowMatrix, shadowCamera,
  20596. program, buffer, material,
  20597. webglObject, object, light,
  20598. renderList,
  20599. lights = [],
  20600. k = 0,
  20601. fog = null;
  20602. // set GL state for depth map
  20603. _gl.clearColor( 1, 1, 1, 1 );
  20604. _gl.disable( _gl.BLEND );
  20605. _gl.enable( _gl.CULL_FACE );
  20606. _gl.frontFace( _gl.CCW );
  20607. if ( _renderer.shadowMapCullFrontFaces ) {
  20608. _gl.cullFace( _gl.FRONT );
  20609. } else {
  20610. _gl.cullFace( _gl.BACK );
  20611. }
  20612. _renderer.setDepthTest( true );
  20613. // preprocess lights
  20614. // - skip lights that are not casting shadows
  20615. // - create virtual lights for cascaded shadow maps
  20616. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20617. light = scene.__lights[ i ];
  20618. if ( ! light.castShadow ) continue;
  20619. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20620. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20621. var virtualLight;
  20622. if ( ! light.shadowCascadeArray[ n ] ) {
  20623. virtualLight = createVirtualLight( light, n );
  20624. virtualLight.originalCamera = camera;
  20625. var gyro = new THREE.Gyroscope();
  20626. gyro.position = light.shadowCascadeOffset;
  20627. gyro.add( virtualLight );
  20628. gyro.add( virtualLight.target );
  20629. camera.add( gyro );
  20630. light.shadowCascadeArray[ n ] = virtualLight;
  20631. console.log( "Created virtualLight", virtualLight );
  20632. } else {
  20633. virtualLight = light.shadowCascadeArray[ n ];
  20634. }
  20635. updateVirtualLight( light, n );
  20636. lights[ k ] = virtualLight;
  20637. k ++;
  20638. }
  20639. } else {
  20640. lights[ k ] = light;
  20641. k ++;
  20642. }
  20643. }
  20644. // render depth map
  20645. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20646. light = lights[ i ];
  20647. if ( ! light.shadowMap ) {
  20648. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  20649. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20650. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20651. light.shadowMatrix = new THREE.Matrix4();
  20652. }
  20653. if ( ! light.shadowCamera ) {
  20654. if ( light instanceof THREE.SpotLight ) {
  20655. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20656. } else if ( light instanceof THREE.DirectionalLight ) {
  20657. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20658. } else {
  20659. console.error( "Unsupported light type for shadow" );
  20660. continue;
  20661. }
  20662. scene.add( light.shadowCamera );
  20663. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20664. }
  20665. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20666. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20667. light.shadowCamera.add( light.cameraHelper );
  20668. }
  20669. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20670. updateShadowCamera( camera, light );
  20671. }
  20672. shadowMap = light.shadowMap;
  20673. shadowMatrix = light.shadowMatrix;
  20674. shadowCamera = light.shadowCamera;
  20675. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  20676. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  20677. shadowCamera.updateMatrixWorld();
  20678. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20679. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  20680. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20681. // compute shadow matrix
  20682. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20683. 0.0, 0.5, 0.0, 0.5,
  20684. 0.0, 0.0, 0.5, 0.5,
  20685. 0.0, 0.0, 0.0, 1.0 );
  20686. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  20687. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  20688. // update camera matrices and frustum
  20689. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  20690. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  20691. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  20692. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  20693. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20694. _frustum.setFromMatrix( _projScreenMatrix );
  20695. // render shadow map
  20696. _renderer.setRenderTarget( shadowMap );
  20697. _renderer.clear();
  20698. // set object matrices & frustum culling
  20699. renderList = scene.__webglObjects;
  20700. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20701. webglObject = renderList[ j ];
  20702. object = webglObject.object;
  20703. webglObject.render = false;
  20704. if ( object.visible && object.castShadow ) {
  20705. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  20706. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20707. webglObject.render = true;
  20708. }
  20709. }
  20710. }
  20711. // render regular objects
  20712. var objectMaterial, useMorphing, useSkinning;
  20713. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20714. webglObject = renderList[ j ];
  20715. if ( webglObject.render ) {
  20716. object = webglObject.object;
  20717. buffer = webglObject.buffer;
  20718. // culling is overriden globally for all objects
  20719. // while rendering depth map
  20720. // need to deal with MeshFaceMaterial somehow
  20721. // in that case just use the first of material.materials for now
  20722. // (proper solution would require to break objects by materials
  20723. // similarly to regular rendering and then set corresponding
  20724. // depth materials per each chunk instead of just once per object)
  20725. objectMaterial = getObjectMaterial( object );
  20726. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  20727. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  20728. if ( object.customDepthMaterial ) {
  20729. material = object.customDepthMaterial;
  20730. } else if ( useSkinning ) {
  20731. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  20732. } else if ( useMorphing ) {
  20733. material = _depthMaterialMorph;
  20734. } else {
  20735. material = _depthMaterial;
  20736. }
  20737. if ( buffer instanceof THREE.BufferGeometry ) {
  20738. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  20739. } else {
  20740. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  20741. }
  20742. }
  20743. }
  20744. // set matrices and render immediate objects
  20745. renderList = scene.__webglObjectsImmediate;
  20746. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20747. webglObject = renderList[ j ];
  20748. object = webglObject.object;
  20749. if ( object.visible && object.castShadow ) {
  20750. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20751. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  20752. }
  20753. }
  20754. }
  20755. // restore GL state
  20756. var clearColor = _renderer.getClearColor(),
  20757. clearAlpha = _renderer.getClearAlpha();
  20758. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20759. _gl.enable( _gl.BLEND );
  20760. if ( _renderer.shadowMapCullFrontFaces ) {
  20761. _gl.cullFace( _gl.BACK );
  20762. }
  20763. };
  20764. function createVirtualLight( light, cascade ) {
  20765. var virtualLight = new THREE.DirectionalLight();
  20766. virtualLight.isVirtual = true;
  20767. virtualLight.onlyShadow = true;
  20768. virtualLight.castShadow = true;
  20769. virtualLight.shadowCameraNear = light.shadowCameraNear;
  20770. virtualLight.shadowCameraFar = light.shadowCameraFar;
  20771. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  20772. virtualLight.shadowCameraRight = light.shadowCameraRight;
  20773. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  20774. virtualLight.shadowCameraTop = light.shadowCameraTop;
  20775. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20776. virtualLight.shadowDarkness = light.shadowDarkness;
  20777. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20778. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  20779. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  20780. virtualLight.pointsWorld = [];
  20781. virtualLight.pointsFrustum = [];
  20782. var pointsWorld = virtualLight.pointsWorld,
  20783. pointsFrustum = virtualLight.pointsFrustum;
  20784. for ( var i = 0; i < 8; i ++ ) {
  20785. pointsWorld[ i ] = new THREE.Vector3();
  20786. pointsFrustum[ i ] = new THREE.Vector3();
  20787. }
  20788. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20789. var farZ = light.shadowCascadeFarZ[ cascade ];
  20790. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  20791. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  20792. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  20793. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  20794. pointsFrustum[ 4 ].set( -1, -1, farZ );
  20795. pointsFrustum[ 5 ].set( 1, -1, farZ );
  20796. pointsFrustum[ 6 ].set( -1, 1, farZ );
  20797. pointsFrustum[ 7 ].set( 1, 1, farZ );
  20798. return virtualLight;
  20799. }
  20800. // Synchronize virtual light with the original light
  20801. function updateVirtualLight( light, cascade ) {
  20802. var virtualLight = light.shadowCascadeArray[ cascade ];
  20803. virtualLight.position.copy( light.position );
  20804. virtualLight.target.position.copy( light.target.position );
  20805. virtualLight.lookAt( virtualLight.target );
  20806. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20807. virtualLight.shadowDarkness = light.shadowDarkness;
  20808. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20809. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20810. var farZ = light.shadowCascadeFarZ[ cascade ];
  20811. var pointsFrustum = virtualLight.pointsFrustum;
  20812. pointsFrustum[ 0 ].z = nearZ;
  20813. pointsFrustum[ 1 ].z = nearZ;
  20814. pointsFrustum[ 2 ].z = nearZ;
  20815. pointsFrustum[ 3 ].z = nearZ;
  20816. pointsFrustum[ 4 ].z = farZ;
  20817. pointsFrustum[ 5 ].z = farZ;
  20818. pointsFrustum[ 6 ].z = farZ;
  20819. pointsFrustum[ 7 ].z = farZ;
  20820. }
  20821. // Fit shadow camera's ortho frustum to camera frustum
  20822. function updateShadowCamera( camera, light ) {
  20823. var shadowCamera = light.shadowCamera,
  20824. pointsFrustum = light.pointsFrustum,
  20825. pointsWorld = light.pointsWorld;
  20826. _min.set( Infinity, Infinity, Infinity );
  20827. _max.set( -Infinity, -Infinity, -Infinity );
  20828. for ( var i = 0; i < 8; i ++ ) {
  20829. var p = pointsWorld[ i ];
  20830. p.copy( pointsFrustum[ i ] );
  20831. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  20832. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  20833. if ( p.x < _min.x ) _min.x = p.x;
  20834. if ( p.x > _max.x ) _max.x = p.x;
  20835. if ( p.y < _min.y ) _min.y = p.y;
  20836. if ( p.y > _max.y ) _max.y = p.y;
  20837. if ( p.z < _min.z ) _min.z = p.z;
  20838. if ( p.z > _max.z ) _max.z = p.z;
  20839. }
  20840. shadowCamera.left = _min.x;
  20841. shadowCamera.right = _max.x;
  20842. shadowCamera.top = _max.y;
  20843. shadowCamera.bottom = _min.y;
  20844. // can't really fit near/far
  20845. //shadowCamera.near = _min.z;
  20846. //shadowCamera.far = _max.z;
  20847. shadowCamera.updateProjectionMatrix();
  20848. }
  20849. // For the moment just ignore objects that have multiple materials with different animation methods
  20850. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  20851. function getObjectMaterial( object ) {
  20852. return object.material instanceof THREE.MeshFaceMaterial
  20853. ? object.material.materials[ 0 ]
  20854. : object.material;
  20855. };
  20856. };
  20857. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  20858. /**
  20859. * @author mikael emtinger / http://gomo.se/
  20860. * @author alteredq / http://alteredqualia.com/
  20861. */
  20862. THREE.SpritePlugin = function ( ) {
  20863. var _gl, _renderer, _sprite = {};
  20864. this.init = function ( renderer ) {
  20865. _gl = renderer.context;
  20866. _renderer = renderer;
  20867. _sprite.vertices = new Float32Array( 8 + 8 );
  20868. _sprite.faces = new Uint16Array( 6 );
  20869. var i = 0;
  20870. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  20871. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  20872. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  20873. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  20874. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  20875. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  20876. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  20877. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  20878. i = 0;
  20879. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  20880. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  20881. _sprite.vertexBuffer = _gl.createBuffer();
  20882. _sprite.elementBuffer = _gl.createBuffer();
  20883. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20884. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  20885. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20886. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  20887. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  20888. _sprite.attributes = {};
  20889. _sprite.uniforms = {};
  20890. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  20891. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  20892. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  20893. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  20894. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  20895. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  20896. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  20897. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  20898. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  20899. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  20900. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  20901. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  20902. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  20903. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  20904. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  20905. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  20906. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  20907. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  20908. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  20909. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  20910. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  20911. };
  20912. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20913. var sprites = scene.__webglSprites,
  20914. nSprites = sprites.length;
  20915. if ( ! nSprites ) return;
  20916. var attributes = _sprite.attributes,
  20917. uniforms = _sprite.uniforms;
  20918. var invAspect = viewportHeight / viewportWidth;
  20919. var halfViewportWidth = viewportWidth * 0.5,
  20920. halfViewportHeight = viewportHeight * 0.5;
  20921. // setup gl
  20922. _gl.useProgram( _sprite.program );
  20923. _gl.enableVertexAttribArray( attributes.position );
  20924. _gl.enableVertexAttribArray( attributes.uv );
  20925. _gl.disable( _gl.CULL_FACE );
  20926. _gl.enable( _gl.BLEND );
  20927. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20928. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20929. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20930. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20931. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  20932. _gl.activeTexture( _gl.TEXTURE0 );
  20933. _gl.uniform1i( uniforms.map, 0 );
  20934. var oldFogType = 0;
  20935. var sceneFogType = 0;
  20936. var fog = scene.fog;
  20937. if ( fog ) {
  20938. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  20939. if ( fog instanceof THREE.Fog ) {
  20940. _gl.uniform1f( uniforms.fogNear, fog.near );
  20941. _gl.uniform1f( uniforms.fogFar, fog.far );
  20942. _gl.uniform1i( uniforms.fogType, 1 );
  20943. oldFogType = 1;
  20944. sceneFogType = 1;
  20945. } else if ( fog instanceof THREE.FogExp2 ) {
  20946. _gl.uniform1f( uniforms.fogDensity, fog.density );
  20947. _gl.uniform1i( uniforms.fogType, 2 );
  20948. oldFogType = 2;
  20949. sceneFogType = 2;
  20950. }
  20951. } else {
  20952. _gl.uniform1i( uniforms.fogType, 0 );
  20953. oldFogType = 0;
  20954. sceneFogType = 0;
  20955. }
  20956. // update positions and sort
  20957. var i, sprite, material, screenPosition, size, fogType, scale = [];
  20958. for( i = 0; i < nSprites; i ++ ) {
  20959. sprite = sprites[ i ];
  20960. material = sprite.material;
  20961. if ( ! sprite.visible || material.opacity === 0 ) continue;
  20962. if ( ! material.useScreenCoordinates ) {
  20963. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  20964. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  20965. } else {
  20966. sprite.z = - sprite.position.z;
  20967. }
  20968. }
  20969. sprites.sort( painterSortStable );
  20970. // render all sprites
  20971. for( i = 0; i < nSprites; i ++ ) {
  20972. sprite = sprites[ i ];
  20973. material = sprite.material;
  20974. if ( ! sprite.visible || material.opacity === 0 ) continue;
  20975. if ( material.map && material.map.image && material.map.image.width ) {
  20976. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  20977. if ( material.useScreenCoordinates ) {
  20978. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  20979. _gl.uniform3f(
  20980. uniforms.screenPosition,
  20981. ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  20982. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  20983. Math.max( 0, Math.min( 1, sprite.position.z ) )
  20984. );
  20985. } else {
  20986. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  20987. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  20988. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  20989. }
  20990. if ( scene.fog && material.fog ) {
  20991. fogType = sceneFogType;
  20992. } else {
  20993. fogType = 0;
  20994. }
  20995. if ( oldFogType !== fogType ) {
  20996. _gl.uniform1i( uniforms.fogType, fogType );
  20997. oldFogType = fogType;
  20998. }
  20999. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21000. scale[ 0 ] = size * invAspect * sprite.scale.x;
  21001. scale[ 1 ] = size * sprite.scale.y;
  21002. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21003. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21004. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21005. _gl.uniform1f( uniforms.opacity, material.opacity );
  21006. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21007. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21008. _gl.uniform2fv( uniforms.scale, scale );
  21009. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21010. _renderer.setDepthTest( material.depthTest );
  21011. _renderer.setDepthWrite( material.depthWrite );
  21012. _renderer.setTexture( material.map, 0 );
  21013. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21014. }
  21015. }
  21016. // restore gl
  21017. _gl.enable( _gl.CULL_FACE );
  21018. };
  21019. function createProgram ( shader ) {
  21020. var program = _gl.createProgram();
  21021. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21022. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21023. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21024. _gl.shaderSource( vertexShader, shader.vertexShader );
  21025. _gl.compileShader( fragmentShader );
  21026. _gl.compileShader( vertexShader );
  21027. _gl.attachShader( program, fragmentShader );
  21028. _gl.attachShader( program, vertexShader );
  21029. _gl.linkProgram( program );
  21030. return program;
  21031. };
  21032. function painterSortStable ( a, b ) {
  21033. if ( a.z !== b.z ) {
  21034. return b.z - a.z;
  21035. } else {
  21036. return b.id - a.id;
  21037. }
  21038. };
  21039. };/**
  21040. * @author alteredq / http://alteredqualia.com/
  21041. */
  21042. THREE.DepthPassPlugin = function ( ) {
  21043. this.enabled = false;
  21044. this.renderTarget = null;
  21045. var _gl,
  21046. _renderer,
  21047. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21048. _frustum = new THREE.Frustum(),
  21049. _projScreenMatrix = new THREE.Matrix4();
  21050. this.init = function ( renderer ) {
  21051. _gl = renderer.context;
  21052. _renderer = renderer;
  21053. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21054. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21055. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21056. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21057. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21058. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21059. _depthMaterial._shadowPass = true;
  21060. _depthMaterialMorph._shadowPass = true;
  21061. _depthMaterialSkin._shadowPass = true;
  21062. _depthMaterialMorphSkin._shadowPass = true;
  21063. };
  21064. this.render = function ( scene, camera ) {
  21065. if ( ! this.enabled ) return;
  21066. this.update( scene, camera );
  21067. };
  21068. this.update = function ( scene, camera ) {
  21069. var i, il, j, jl, n,
  21070. program, buffer, material,
  21071. webglObject, object, light,
  21072. renderList,
  21073. fog = null;
  21074. // set GL state for depth map
  21075. _gl.clearColor( 1, 1, 1, 1 );
  21076. _gl.disable( _gl.BLEND );
  21077. _renderer.setDepthTest( true );
  21078. // update scene
  21079. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21080. // update camera matrices and frustum
  21081. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  21082. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  21083. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21084. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  21085. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  21086. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21087. _frustum.setFromMatrix( _projScreenMatrix );
  21088. // render depth map
  21089. _renderer.setRenderTarget( this.renderTarget );
  21090. _renderer.clear();
  21091. // set object matrices & frustum culling
  21092. renderList = scene.__webglObjects;
  21093. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21094. webglObject = renderList[ j ];
  21095. object = webglObject.object;
  21096. webglObject.render = false;
  21097. if ( object.visible ) {
  21098. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21099. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21100. webglObject.render = true;
  21101. }
  21102. }
  21103. }
  21104. // render regular objects
  21105. var objectMaterial, useMorphing, useSkinning;
  21106. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21107. webglObject = renderList[ j ];
  21108. if ( webglObject.render ) {
  21109. object = webglObject.object;
  21110. buffer = webglObject.buffer;
  21111. // todo: create proper depth material for particles
  21112. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21113. objectMaterial = getObjectMaterial( object );
  21114. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21115. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21116. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21117. if ( object.customDepthMaterial ) {
  21118. material = object.customDepthMaterial;
  21119. } else if ( useSkinning ) {
  21120. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21121. } else if ( useMorphing ) {
  21122. material = _depthMaterialMorph;
  21123. } else {
  21124. material = _depthMaterial;
  21125. }
  21126. if ( buffer instanceof THREE.BufferGeometry ) {
  21127. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21128. } else {
  21129. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21130. }
  21131. }
  21132. }
  21133. // set matrices and render immediate objects
  21134. renderList = scene.__webglObjectsImmediate;
  21135. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21136. webglObject = renderList[ j ];
  21137. object = webglObject.object;
  21138. if ( object.visible ) {
  21139. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21140. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21141. }
  21142. }
  21143. // restore GL state
  21144. var clearColor = _renderer.getClearColor(),
  21145. clearAlpha = _renderer.getClearAlpha();
  21146. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21147. _gl.enable( _gl.BLEND );
  21148. };
  21149. // For the moment just ignore objects that have multiple materials with different animation methods
  21150. // Only the first material will be taken into account for deciding which depth material to use
  21151. function getObjectMaterial( object ) {
  21152. return object.material instanceof THREE.MeshFaceMaterial
  21153. ? object.material.materials[ 0 ]
  21154. : object.material;
  21155. };
  21156. };
  21157. /**
  21158. * @author mikael emtinger / http://gomo.se/
  21159. *
  21160. */
  21161. THREE.ShaderFlares = {
  21162. 'lensFlareVertexTexture': {
  21163. vertexShader: [
  21164. "uniform vec3 screenPosition;",
  21165. "uniform vec2 scale;",
  21166. "uniform float rotation;",
  21167. "uniform int renderType;",
  21168. "uniform sampler2D occlusionMap;",
  21169. "attribute vec2 position;",
  21170. "attribute vec2 uv;",
  21171. "varying vec2 vUV;",
  21172. "varying float vVisibility;",
  21173. "void main() {",
  21174. "vUV = uv;",
  21175. "vec2 pos = position;",
  21176. "if( renderType == 2 ) {",
  21177. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21178. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21179. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21180. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21181. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21182. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21183. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21184. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21185. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21186. "vVisibility = ( visibility.r / 9.0 ) *",
  21187. "( 1.0 - visibility.g / 9.0 ) *",
  21188. "( visibility.b / 9.0 ) *",
  21189. "( 1.0 - visibility.a / 9.0 );",
  21190. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21191. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21192. "}",
  21193. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21194. "}"
  21195. ].join( "\n" ),
  21196. fragmentShader: [
  21197. "precision mediump float;",
  21198. "uniform sampler2D map;",
  21199. "uniform float opacity;",
  21200. "uniform int renderType;",
  21201. "uniform vec3 color;",
  21202. "varying vec2 vUV;",
  21203. "varying float vVisibility;",
  21204. "void main() {",
  21205. // pink square
  21206. "if( renderType == 0 ) {",
  21207. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21208. // restore
  21209. "} else if( renderType == 1 ) {",
  21210. "gl_FragColor = texture2D( map, vUV );",
  21211. // flare
  21212. "} else {",
  21213. "vec4 texture = texture2D( map, vUV );",
  21214. "texture.a *= opacity * vVisibility;",
  21215. "gl_FragColor = texture;",
  21216. "gl_FragColor.rgb *= color;",
  21217. "}",
  21218. "}"
  21219. ].join( "\n" )
  21220. },
  21221. 'lensFlare': {
  21222. vertexShader: [
  21223. "uniform vec3 screenPosition;",
  21224. "uniform vec2 scale;",
  21225. "uniform float rotation;",
  21226. "uniform int renderType;",
  21227. "attribute vec2 position;",
  21228. "attribute vec2 uv;",
  21229. "varying vec2 vUV;",
  21230. "void main() {",
  21231. "vUV = uv;",
  21232. "vec2 pos = position;",
  21233. "if( renderType == 2 ) {",
  21234. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21235. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21236. "}",
  21237. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21238. "}"
  21239. ].join( "\n" ),
  21240. fragmentShader: [
  21241. "precision mediump float;",
  21242. "uniform sampler2D map;",
  21243. "uniform sampler2D occlusionMap;",
  21244. "uniform float opacity;",
  21245. "uniform int renderType;",
  21246. "uniform vec3 color;",
  21247. "varying vec2 vUV;",
  21248. "void main() {",
  21249. // pink square
  21250. "if( renderType == 0 ) {",
  21251. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21252. // restore
  21253. "} else if( renderType == 1 ) {",
  21254. "gl_FragColor = texture2D( map, vUV );",
  21255. // flare
  21256. "} else {",
  21257. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21258. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21259. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21260. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21261. "visibility = ( 1.0 - visibility / 4.0 );",
  21262. "vec4 texture = texture2D( map, vUV );",
  21263. "texture.a *= opacity * visibility;",
  21264. "gl_FragColor = texture;",
  21265. "gl_FragColor.rgb *= color;",
  21266. "}",
  21267. "}"
  21268. ].join( "\n" )
  21269. }
  21270. };
  21271. /**
  21272. * @author mikael emtinger / http://gomo.se/
  21273. * @author alteredq / http://alteredqualia.com/
  21274. *
  21275. */
  21276. THREE.ShaderSprite = {
  21277. 'sprite': {
  21278. vertexShader: [
  21279. "uniform int useScreenCoordinates;",
  21280. "uniform int sizeAttenuation;",
  21281. "uniform vec3 screenPosition;",
  21282. "uniform mat4 modelViewMatrix;",
  21283. "uniform mat4 projectionMatrix;",
  21284. "uniform float rotation;",
  21285. "uniform vec2 scale;",
  21286. "uniform vec2 alignment;",
  21287. "uniform vec2 uvOffset;",
  21288. "uniform vec2 uvScale;",
  21289. "attribute vec2 position;",
  21290. "attribute vec2 uv;",
  21291. "varying vec2 vUV;",
  21292. "void main() {",
  21293. "vUV = uvOffset + uv * uvScale;",
  21294. "vec2 alignedPosition = position + alignment;",
  21295. "vec2 rotatedPosition;",
  21296. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21297. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21298. "vec4 finalPosition;",
  21299. "if( useScreenCoordinates != 0 ) {",
  21300. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21301. "} else {",
  21302. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21303. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21304. "}",
  21305. "gl_Position = finalPosition;",
  21306. "}"
  21307. ].join( "\n" ),
  21308. fragmentShader: [
  21309. "precision mediump float;",
  21310. "uniform vec3 color;",
  21311. "uniform sampler2D map;",
  21312. "uniform float opacity;",
  21313. "uniform int fogType;",
  21314. "uniform vec3 fogColor;",
  21315. "uniform float fogDensity;",
  21316. "uniform float fogNear;",
  21317. "uniform float fogFar;",
  21318. "uniform float alphaTest;",
  21319. "varying vec2 vUV;",
  21320. "void main() {",
  21321. "vec4 texture = texture2D( map, vUV );",
  21322. "if ( texture.a < alphaTest ) discard;",
  21323. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21324. "if ( fogType > 0 ) {",
  21325. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21326. "float fogFactor = 0.0;",
  21327. "if ( fogType == 1 ) {",
  21328. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21329. "} else {",
  21330. "const float LOG2 = 1.442695;",
  21331. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21332. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21333. "}",
  21334. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21335. "}",
  21336. "}"
  21337. ].join( "\n" )
  21338. }
  21339. };
粤ICP备19079148号