three.js 819 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '55dev' };
  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. // GL STATE CONSTANTS
  53. THREE.CullFaceNone = 0;
  54. THREE.CullFaceBack = 1;
  55. THREE.CullFaceFront = 2;
  56. THREE.CullFaceFrontBack = 3;
  57. THREE.FrontFaceDirectionCW = 0;
  58. THREE.FrontFaceDirectionCCW = 1;
  59. // SHADOWING TYPES
  60. THREE.BasicShadowMap = 0;
  61. THREE.PCFShadowMap = 1;
  62. THREE.PCFSoftShadowMap = 2;
  63. // MATERIAL CONSTANTS
  64. // side
  65. THREE.FrontSide = 0;
  66. THREE.BackSide = 1;
  67. THREE.DoubleSide = 2;
  68. // shading
  69. THREE.NoShading = 0;
  70. THREE.FlatShading = 1;
  71. THREE.SmoothShading = 2;
  72. // colors
  73. THREE.NoColors = 0;
  74. THREE.FaceColors = 1;
  75. THREE.VertexColors = 2;
  76. // blending modes
  77. THREE.NoBlending = 0;
  78. THREE.NormalBlending = 1;
  79. THREE.AdditiveBlending = 2;
  80. THREE.SubtractiveBlending = 3;
  81. THREE.MultiplyBlending = 4;
  82. THREE.CustomBlending = 5;
  83. // custom blending equations
  84. // (numbers start from 100 not to clash with other
  85. // mappings to OpenGL constants defined in Texture.js)
  86. THREE.AddEquation = 100;
  87. THREE.SubtractEquation = 101;
  88. THREE.ReverseSubtractEquation = 102;
  89. // custom blending destination factors
  90. THREE.ZeroFactor = 200;
  91. THREE.OneFactor = 201;
  92. THREE.SrcColorFactor = 202;
  93. THREE.OneMinusSrcColorFactor = 203;
  94. THREE.SrcAlphaFactor = 204;
  95. THREE.OneMinusSrcAlphaFactor = 205;
  96. THREE.DstAlphaFactor = 206;
  97. THREE.OneMinusDstAlphaFactor = 207;
  98. // custom blending source factors
  99. //THREE.ZeroFactor = 200;
  100. //THREE.OneFactor = 201;
  101. //THREE.SrcAlphaFactor = 204;
  102. //THREE.OneMinusSrcAlphaFactor = 205;
  103. //THREE.DstAlphaFactor = 206;
  104. //THREE.OneMinusDstAlphaFactor = 207;
  105. THREE.DstColorFactor = 208;
  106. THREE.OneMinusDstColorFactor = 209;
  107. THREE.SrcAlphaSaturateFactor = 210;
  108. // TEXTURE CONSTANTS
  109. THREE.MultiplyOperation = 0;
  110. THREE.MixOperation = 1;
  111. THREE.AddOperation = 2;
  112. // Mapping modes
  113. THREE.UVMapping = function () {};
  114. THREE.CubeReflectionMapping = function () {};
  115. THREE.CubeRefractionMapping = function () {};
  116. THREE.SphericalReflectionMapping = function () {};
  117. THREE.SphericalRefractionMapping = function () {};
  118. // Wrapping modes
  119. THREE.RepeatWrapping = 1000;
  120. THREE.ClampToEdgeWrapping = 1001;
  121. THREE.MirroredRepeatWrapping = 1002;
  122. // Filters
  123. THREE.NearestFilter = 1003;
  124. THREE.NearestMipMapNearestFilter = 1004;
  125. THREE.NearestMipMapLinearFilter = 1005;
  126. THREE.LinearFilter = 1006;
  127. THREE.LinearMipMapNearestFilter = 1007;
  128. THREE.LinearMipMapLinearFilter = 1008;
  129. // Data types
  130. THREE.UnsignedByteType = 1009;
  131. THREE.ByteType = 1010;
  132. THREE.ShortType = 1011;
  133. THREE.UnsignedShortType = 1012;
  134. THREE.IntType = 1013;
  135. THREE.UnsignedIntType = 1014;
  136. THREE.FloatType = 1015;
  137. // Pixel types
  138. //THREE.UnsignedByteType = 1009;
  139. THREE.UnsignedShort4444Type = 1016;
  140. THREE.UnsignedShort5551Type = 1017;
  141. THREE.UnsignedShort565Type = 1018;
  142. // Pixel formats
  143. THREE.AlphaFormat = 1019;
  144. THREE.RGBFormat = 1020;
  145. THREE.RGBAFormat = 1021;
  146. THREE.LuminanceFormat = 1022;
  147. THREE.LuminanceAlphaFormat = 1023;
  148. // Compressed texture formats
  149. THREE.RGB_S3TC_DXT1_Format = 2001;
  150. THREE.RGBA_S3TC_DXT1_Format = 2002;
  151. THREE.RGBA_S3TC_DXT3_Format = 2003;
  152. THREE.RGBA_S3TC_DXT5_Format = 2004;
  153. /*
  154. // Potential future PVRTC compressed texture formats
  155. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  156. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  157. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  158. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  159. */
  160. /**
  161. * @author mrdoob / http://mrdoob.com/
  162. */
  163. THREE.Color = function ( value ) {
  164. if ( value !== undefined ) this.set( value );
  165. return this;
  166. };
  167. THREE.Color.prototype = {
  168. constructor: THREE.Color,
  169. r: 1, g: 1, b: 1,
  170. copy: function ( color ) {
  171. this.r = color.r;
  172. this.g = color.g;
  173. this.b = color.b;
  174. return this;
  175. },
  176. copyGammaToLinear: function ( color ) {
  177. this.r = color.r * color.r;
  178. this.g = color.g * color.g;
  179. this.b = color.b * color.b;
  180. return this;
  181. },
  182. copyLinearToGamma: function ( color ) {
  183. this.r = Math.sqrt( color.r );
  184. this.g = Math.sqrt( color.g );
  185. this.b = Math.sqrt( color.b );
  186. return this;
  187. },
  188. convertGammaToLinear: function () {
  189. var r = this.r, g = this.g, b = this.b;
  190. this.r = r * r;
  191. this.g = g * g;
  192. this.b = b * b;
  193. return this;
  194. },
  195. convertLinearToGamma: function () {
  196. this.r = Math.sqrt( this.r );
  197. this.g = Math.sqrt( this.g );
  198. this.b = Math.sqrt( this.b );
  199. return this;
  200. },
  201. set: function ( value ) {
  202. switch ( typeof value ) {
  203. case "number":
  204. this.setHex( value );
  205. break;
  206. case "string":
  207. this.setStyle( value );
  208. break;
  209. }
  210. },
  211. setRGB: function ( r, g, b ) {
  212. this.r = r;
  213. this.g = g;
  214. this.b = b;
  215. return this;
  216. },
  217. setHSV: function ( h, s, v ) {
  218. // based on MochiKit implementation by Bob Ippolito
  219. // h,s,v ranges are < 0.0 - 1.0 >
  220. var i, f, p, q, t;
  221. if ( v === 0 ) {
  222. this.r = this.g = this.b = 0;
  223. } else {
  224. i = Math.floor( h * 6 );
  225. f = ( h * 6 ) - i;
  226. p = v * ( 1 - s );
  227. q = v * ( 1 - ( s * f ) );
  228. t = v * ( 1 - ( s * ( 1 - f ) ) );
  229. if ( i === 0 ) {
  230. this.r = v;
  231. this.g = t;
  232. this.b = p;
  233. } else if ( i === 1 ) {
  234. this.r = q;
  235. this.g = v;
  236. this.b = p;
  237. } else if ( i === 2 ) {
  238. this.r = p;
  239. this.g = v;
  240. this.b = t;
  241. } else if ( i === 3 ) {
  242. this.r = p;
  243. this.g = q;
  244. this.b = v;
  245. } else if ( i === 4 ) {
  246. this.r = t;
  247. this.g = p;
  248. this.b = v;
  249. } else if ( i === 5 ) {
  250. this.r = v;
  251. this.g = p;
  252. this.b = q;
  253. }
  254. }
  255. return this;
  256. },
  257. getHex: function () {
  258. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  259. },
  260. setHex: function ( hex ) {
  261. hex = Math.floor( hex );
  262. this.r = ( hex >> 16 & 255 ) / 255;
  263. this.g = ( hex >> 8 & 255 ) / 255;
  264. this.b = ( hex & 255 ) / 255;
  265. return this;
  266. },
  267. getHexString: function () {
  268. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  269. },
  270. getStyle: function () {
  271. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  272. },
  273. setStyle: function ( style ) {
  274. // rgb(255,0,0)
  275. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  276. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  277. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  278. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  279. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  280. return this;
  281. }
  282. // rgb(100%,0%,0%)
  283. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  284. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  285. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  286. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  287. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  288. return this;
  289. }
  290. // #ff0000
  291. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  292. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  293. this.setHex( parseInt( color[ 1 ], 16 ) );
  294. return this;
  295. }
  296. // #f00
  297. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  298. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  299. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  300. return this;
  301. }
  302. // red
  303. if ( /^(\w+)$/i.test( style ) ) {
  304. this.setHex( THREE.ColorKeywords[ style ] );
  305. return this;
  306. }
  307. },
  308. getHSV: function ( hsv ) {
  309. // based on MochiKit implementation by Bob Ippolito
  310. // h,s,v ranges are < 0.0 - 1.0 >
  311. var r = this.r;
  312. var g = this.g;
  313. var b = this.b;
  314. var max = Math.max( Math.max( r, g ), b );
  315. var min = Math.min( Math.min( r, g ), b );
  316. var hue;
  317. var saturation;
  318. var value = max;
  319. if ( min === max ) {
  320. hue = 0;
  321. saturation = 0;
  322. } else {
  323. var delta = ( max - min );
  324. saturation = delta / max;
  325. if ( r === max ) {
  326. hue = ( g - b ) / delta;
  327. } else if ( g === max ) {
  328. hue = 2 + ( ( b - r ) / delta );
  329. } else {
  330. hue = 4 + ( ( r - g ) / delta );
  331. }
  332. hue /= 6;
  333. if ( hue < 0 ) {
  334. hue += 1;
  335. }
  336. if ( hue > 1 ) {
  337. hue -= 1;
  338. }
  339. }
  340. if ( hsv === undefined ) {
  341. hsv = { h: 0, s: 0, v: 0 };
  342. }
  343. hsv.h = hue;
  344. hsv.s = saturation;
  345. hsv.v = value;
  346. return hsv;
  347. },
  348. lerpSelf: function ( color, alpha ) {
  349. this.r += ( color.r - this.r ) * alpha;
  350. this.g += ( color.g - this.g ) * alpha;
  351. this.b += ( color.b - this.b ) * alpha;
  352. return this;
  353. },
  354. clone: function () {
  355. return new THREE.Color().setRGB( this.r, this.g, this.b );
  356. }
  357. };
  358. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  359. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  360. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  361. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  362. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  363. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  364. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  365. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  366. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  367. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  368. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  369. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  370. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  371. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  372. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  373. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  374. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  375. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  376. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  377. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  378. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  379. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  380. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  381. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  382. /**
  383. * @author mrdoob / http://mrdoob.com/
  384. * @author philogb / http://blog.thejit.org/
  385. * @author egraether / http://egraether.com/
  386. * @author zz85 / http://www.lab4games.net/zz85/blog
  387. */
  388. THREE.Vector2 = function ( x, y ) {
  389. this.x = x || 0;
  390. this.y = y || 0;
  391. };
  392. THREE.Vector2.prototype = {
  393. constructor: THREE.Vector2,
  394. set: function ( x, y ) {
  395. this.x = x;
  396. this.y = y;
  397. return this;
  398. },
  399. setX: function ( x ) {
  400. this.x = x;
  401. return this;
  402. },
  403. setY: function ( y ) {
  404. this.y = y;
  405. return this;
  406. },
  407. setComponent: function ( index, value ) {
  408. switch ( index ) {
  409. case 0: this.x = value; break;
  410. case 1: this.y = value; break;
  411. default: throw new Error( "index is out of range: " + index );
  412. }
  413. },
  414. getComponent: function ( index ) {
  415. switch ( index ) {
  416. case 0: return this.x;
  417. case 1: return this.y;
  418. default: throw new Error( "index is out of range: " + index );
  419. }
  420. },
  421. copy: function ( v ) {
  422. this.x = v.x;
  423. this.y = v.y;
  424. return this;
  425. },
  426. addScalar: function ( s ) {
  427. this.x += s;
  428. this.y += s;
  429. return this;
  430. },
  431. add: function ( a, b ) {
  432. this.x = a.x + b.x;
  433. this.y = a.y + b.y;
  434. return this;
  435. },
  436. addSelf: function ( v ) {
  437. this.x += v.x;
  438. this.y += v.y;
  439. return this;
  440. },
  441. sub: function ( a, b ) {
  442. this.x = a.x - b.x;
  443. this.y = a.y - b.y;
  444. return this;
  445. },
  446. subSelf: function ( v ) {
  447. this.x -= v.x;
  448. this.y -= v.y;
  449. return this;
  450. },
  451. multiplyScalar: function ( s ) {
  452. this.x *= s;
  453. this.y *= s;
  454. return this;
  455. },
  456. divideScalar: function ( s ) {
  457. if ( s !== 0 ) {
  458. this.x /= s;
  459. this.y /= s;
  460. } else {
  461. this.set( 0, 0 );
  462. }
  463. return this;
  464. },
  465. minSelf: function ( v ) {
  466. if ( this.x > v.x ) {
  467. this.x = v.x;
  468. }
  469. if ( this.y > v.y ) {
  470. this.y = v.y;
  471. }
  472. return this;
  473. },
  474. maxSelf: function ( v ) {
  475. if ( this.x < v.x ) {
  476. this.x = v.x;
  477. }
  478. if ( this.y < v.y ) {
  479. this.y = v.y;
  480. }
  481. return this;
  482. },
  483. clampSelf: function ( min, max ) {
  484. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  485. if ( this.x < min.x ) {
  486. this.x = min.x;
  487. } else if ( this.x > max.x ) {
  488. this.x = max.x;
  489. }
  490. if ( this.y < min.y ) {
  491. this.y = min.y;
  492. } else if ( this.y > max.y ) {
  493. this.y = max.y;
  494. }
  495. return this;
  496. },
  497. negate: function() {
  498. return this.multiplyScalar( - 1 );
  499. },
  500. dot: function ( v ) {
  501. return this.x * v.x + this.y * v.y;
  502. },
  503. lengthSq: function () {
  504. return this.x * this.x + this.y * this.y;
  505. },
  506. length: function () {
  507. return Math.sqrt( this.x * this.x + this.y * this.y );
  508. },
  509. normalize: function () {
  510. return this.divideScalar( this.length() );
  511. },
  512. distanceTo: function ( v ) {
  513. return Math.sqrt( this.distanceToSquared( v ) );
  514. },
  515. distanceToSquared: function ( v ) {
  516. var dx = this.x - v.x, dy = this.y - v.y;
  517. return dx * dx + dy * dy;
  518. },
  519. setLength: function ( l ) {
  520. var oldLength = this.length();
  521. if ( oldLength !== 0 && l !== oldLength ) {
  522. this.multiplyScalar( l / oldLength );
  523. }
  524. return this;
  525. },
  526. lerpSelf: function ( v, alpha ) {
  527. this.x += ( v.x - this.x ) * alpha;
  528. this.y += ( v.y - this.y ) * alpha;
  529. return this;
  530. },
  531. equals: function( v ) {
  532. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  533. },
  534. clone: function () {
  535. return new THREE.Vector2( this.x, this.y );
  536. }
  537. };
  538. /**
  539. * @author mrdoob / http://mrdoob.com/
  540. * @author *kile / http://kile.stravaganza.org/
  541. * @author philogb / http://blog.thejit.org/
  542. * @author mikael emtinger / http://gomo.se/
  543. * @author egraether / http://egraether.com/
  544. * @author WestLangley / http://github.com/WestLangley
  545. */
  546. THREE.Vector3 = function ( x, y, z ) {
  547. this.x = x || 0;
  548. this.y = y || 0;
  549. this.z = z || 0;
  550. };
  551. THREE.Vector3.prototype = {
  552. constructor: THREE.Vector3,
  553. set: function ( x, y, z ) {
  554. this.x = x;
  555. this.y = y;
  556. this.z = z;
  557. return this;
  558. },
  559. setX: function ( x ) {
  560. this.x = x;
  561. return this;
  562. },
  563. setY: function ( y ) {
  564. this.y = y;
  565. return this;
  566. },
  567. setZ: function ( z ) {
  568. this.z = z;
  569. return this;
  570. },
  571. setComponent: function ( index, value ) {
  572. switch ( index ) {
  573. case 0: this.x = value; break;
  574. case 1: this.y = value; break;
  575. case 2: this.z = value; break;
  576. default: throw new Error( "index is out of range: " + index );
  577. }
  578. },
  579. getComponent: function ( index ) {
  580. switch ( index ) {
  581. case 0: return this.x;
  582. case 1: return this.y;
  583. case 2: return this.z;
  584. default: throw new Error( "index is out of range: " + index );
  585. }
  586. },
  587. copy: function ( v ) {
  588. this.x = v.x;
  589. this.y = v.y;
  590. this.z = v.z;
  591. return this;
  592. },
  593. add: function ( a, b ) {
  594. this.x = a.x + b.x;
  595. this.y = a.y + b.y;
  596. this.z = a.z + b.z;
  597. return this;
  598. },
  599. addSelf: function ( v ) {
  600. this.x += v.x;
  601. this.y += v.y;
  602. this.z += v.z;
  603. return this;
  604. },
  605. addScalar: function ( s ) {
  606. this.x += s;
  607. this.y += s;
  608. this.z += s;
  609. return this;
  610. },
  611. sub: function ( a, b ) {
  612. this.x = a.x - b.x;
  613. this.y = a.y - b.y;
  614. this.z = a.z - b.z;
  615. return this;
  616. },
  617. subSelf: function ( v ) {
  618. this.x -= v.x;
  619. this.y -= v.y;
  620. this.z -= v.z;
  621. return this;
  622. },
  623. multiply: function ( a, b ) {
  624. this.x = a.x * b.x;
  625. this.y = a.y * b.y;
  626. this.z = a.z * b.z;
  627. return this;
  628. },
  629. multiplySelf: function ( v ) {
  630. this.x *= v.x;
  631. this.y *= v.y;
  632. this.z *= v.z;
  633. return this;
  634. },
  635. multiplyScalar: function ( s ) {
  636. this.x *= s;
  637. this.y *= s;
  638. this.z *= s;
  639. return this;
  640. },
  641. applyMatrix3: function ( m ) {
  642. var x = this.x;
  643. var y = this.y;
  644. var z = this.z;
  645. var e = m.elements;
  646. this.x = e[0] * x + e[3] * y + e[6] * z;
  647. this.y = e[1] * x + e[4] * y + e[7] * z;
  648. this.z = e[2] * x + e[5] * y + e[8] * z;
  649. return this;
  650. },
  651. applyMatrix4: function ( m ) {
  652. var x = this.x;
  653. var y = this.y;
  654. var z = this.z;
  655. var e = m.elements;
  656. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] );
  657. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  658. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  659. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  660. return this;
  661. },
  662. applyQuaternion: function ( q ) {
  663. var x = this.x;
  664. var y = this.y;
  665. var z = this.z;
  666. var qx = q.x;
  667. var qy = q.y;
  668. var qz = q.z;
  669. var qw = q.w;
  670. // calculate quat * vector
  671. var ix = qw * x + qy * z - qz * y;
  672. var iy = qw * y + qz * x - qx * z;
  673. var iz = qw * z + qx * y - qy * x;
  674. var iw = -qx * x - qy * y - qz * z;
  675. // calculate result * inverse quat
  676. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  677. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  678. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  679. return this;
  680. },
  681. divideSelf: function ( v ) {
  682. this.x /= v.x;
  683. this.y /= v.y;
  684. this.z /= v.z;
  685. return this;
  686. },
  687. divideScalar: function ( s ) {
  688. if ( s !== 0 ) {
  689. this.x /= s;
  690. this.y /= s;
  691. this.z /= s;
  692. } else {
  693. this.x = 0;
  694. this.y = 0;
  695. this.z = 0;
  696. }
  697. return this;
  698. },
  699. minSelf: function ( v ) {
  700. if ( this.x > v.x ) {
  701. this.x = v.x;
  702. }
  703. if ( this.y > v.y ) {
  704. this.y = v.y;
  705. }
  706. if ( this.z > v.z ) {
  707. this.z = v.z;
  708. }
  709. return this;
  710. },
  711. maxSelf: function ( v ) {
  712. if ( this.x < v.x ) {
  713. this.x = v.x;
  714. }
  715. if ( this.y < v.y ) {
  716. this.y = v.y;
  717. }
  718. if ( this.z < v.z ) {
  719. this.z = v.z;
  720. }
  721. return this;
  722. },
  723. clampSelf: function ( min, max ) {
  724. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  725. if ( this.x < min.x ) {
  726. this.x = min.x;
  727. } else if ( this.x > max.x ) {
  728. this.x = max.x;
  729. }
  730. if ( this.y < min.y ) {
  731. this.y = min.y;
  732. } else if ( this.y > max.y ) {
  733. this.y = max.y;
  734. }
  735. if ( this.z < min.z ) {
  736. this.z = min.z;
  737. } else if ( this.z > max.z ) {
  738. this.z = max.z;
  739. }
  740. return this;
  741. },
  742. negate: function() {
  743. return this.multiplyScalar( - 1 );
  744. },
  745. dot: function ( v ) {
  746. return this.x * v.x + this.y * v.y + this.z * v.z;
  747. },
  748. lengthSq: function () {
  749. return this.x * this.x + this.y * this.y + this.z * this.z;
  750. },
  751. length: function () {
  752. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  753. },
  754. lengthManhattan: function () {
  755. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  756. },
  757. normalize: function () {
  758. return this.divideScalar( this.length() );
  759. },
  760. setLength: function ( l ) {
  761. var oldLength = this.length();
  762. if ( oldLength !== 0 && l !== oldLength ) {
  763. this.multiplyScalar( l / oldLength );
  764. }
  765. return this;
  766. },
  767. lerpSelf: function ( v, alpha ) {
  768. this.x += ( v.x - this.x ) * alpha;
  769. this.y += ( v.y - this.y ) * alpha;
  770. this.z += ( v.z - this.z ) * alpha;
  771. return this;
  772. },
  773. cross: function ( a, b ) {
  774. this.x = a.y * b.z - a.z * b.y;
  775. this.y = a.z * b.x - a.x * b.z;
  776. this.z = a.x * b.y - a.y * b.x;
  777. return this;
  778. },
  779. crossSelf: function ( v ) {
  780. var x = this.x, y = this.y, z = this.z;
  781. this.x = y * v.z - z * v.y;
  782. this.y = z * v.x - x * v.z;
  783. this.z = x * v.y - y * v.x;
  784. return this;
  785. },
  786. angleTo: function ( v ) {
  787. return Math.acos( this.dot( v ) / this.length() / v.length() );
  788. },
  789. distanceTo: function ( v ) {
  790. return Math.sqrt( this.distanceToSquared( v ) );
  791. },
  792. distanceToSquared: function ( v ) {
  793. var dx = this.x - v.x;
  794. var dy = this.y - v.y;
  795. var dz = this.z - v.z;
  796. return dx * dx + dy * dy + dz * dz;
  797. },
  798. getPositionFromMatrix: function ( m ) {
  799. this.x = m.elements[12];
  800. this.y = m.elements[13];
  801. this.z = m.elements[14];
  802. return this;
  803. },
  804. setEulerFromRotationMatrix: function ( m, order ) {
  805. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  806. // clamp, to handle numerical problems
  807. function clamp( x ) {
  808. return Math.min( Math.max( x, -1 ), 1 );
  809. }
  810. var te = m.elements;
  811. var m11 = te[0], m12 = te[4], m13 = te[8];
  812. var m21 = te[1], m22 = te[5], m23 = te[9];
  813. var m31 = te[2], m32 = te[6], m33 = te[10];
  814. if ( order === undefined || order === 'XYZ' ) {
  815. this.y = Math.asin( clamp( m13 ) );
  816. if ( Math.abs( m13 ) < 0.99999 ) {
  817. this.x = Math.atan2( - m23, m33 );
  818. this.z = Math.atan2( - m12, m11 );
  819. } else {
  820. this.x = Math.atan2( m32, m22 );
  821. this.z = 0;
  822. }
  823. } else if ( order === 'YXZ' ) {
  824. this.x = Math.asin( - clamp( m23 ) );
  825. if ( Math.abs( m23 ) < 0.99999 ) {
  826. this.y = Math.atan2( m13, m33 );
  827. this.z = Math.atan2( m21, m22 );
  828. } else {
  829. this.y = Math.atan2( - m31, m11 );
  830. this.z = 0;
  831. }
  832. } else if ( order === 'ZXY' ) {
  833. this.x = Math.asin( clamp( m32 ) );
  834. if ( Math.abs( m32 ) < 0.99999 ) {
  835. this.y = Math.atan2( - m31, m33 );
  836. this.z = Math.atan2( - m12, m22 );
  837. } else {
  838. this.y = 0;
  839. this.z = Math.atan2( m21, m11 );
  840. }
  841. } else if ( order === 'ZYX' ) {
  842. this.y = Math.asin( - clamp( m31 ) );
  843. if ( Math.abs( m31 ) < 0.99999 ) {
  844. this.x = Math.atan2( m32, m33 );
  845. this.z = Math.atan2( m21, m11 );
  846. } else {
  847. this.x = 0;
  848. this.z = Math.atan2( - m12, m22 );
  849. }
  850. } else if ( order === 'YZX' ) {
  851. this.z = Math.asin( clamp( m21 ) );
  852. if ( Math.abs( m21 ) < 0.99999 ) {
  853. this.x = Math.atan2( - m23, m22 );
  854. this.y = Math.atan2( - m31, m11 );
  855. } else {
  856. this.x = 0;
  857. this.y = Math.atan2( m13, m33 );
  858. }
  859. } else if ( order === 'XZY' ) {
  860. this.z = Math.asin( - clamp( m12 ) );
  861. if ( Math.abs( m12 ) < 0.99999 ) {
  862. this.x = Math.atan2( m32, m22 );
  863. this.y = Math.atan2( m13, m11 );
  864. } else {
  865. this.x = Math.atan2( - m23, m33 );
  866. this.y = 0;
  867. }
  868. }
  869. return this;
  870. },
  871. setEulerFromQuaternion: function ( q, order ) {
  872. // q is assumed to be normalized
  873. // clamp, to handle numerical problems
  874. function clamp( x ) {
  875. return Math.min( Math.max( x, -1 ), 1 );
  876. }
  877. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  878. var sqx = q.x * q.x;
  879. var sqy = q.y * q.y;
  880. var sqz = q.z * q.z;
  881. var sqw = q.w * q.w;
  882. if ( order === undefined || order === 'XYZ' ) {
  883. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  884. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  885. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  886. } else if ( order === 'YXZ' ) {
  887. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  888. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  889. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  890. } else if ( order === 'ZXY' ) {
  891. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  892. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  893. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  894. } else if ( order === 'ZYX' ) {
  895. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  896. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  897. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  898. } else if ( order === 'YZX' ) {
  899. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  900. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  901. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  902. } else if ( order === 'XZY' ) {
  903. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  904. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  905. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  906. }
  907. return this;
  908. },
  909. getScaleFromMatrix: function ( m ) {
  910. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  911. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  912. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  913. this.x = sx;
  914. this.y = sy;
  915. this.z = sz;
  916. return this;
  917. },
  918. equals: function ( v ) {
  919. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  920. },
  921. clone: function () {
  922. return new THREE.Vector3( this.x, this.y, this.z );
  923. }
  924. };
  925. /**
  926. * @author supereggbert / http://www.paulbrunt.co.uk/
  927. * @author philogb / http://blog.thejit.org/
  928. * @author mikael emtinger / http://gomo.se/
  929. * @author egraether / http://egraether.com/
  930. * @author WestLangley / http://github.com/WestLangley
  931. */
  932. THREE.Vector4 = function ( x, y, z, w ) {
  933. this.x = x || 0;
  934. this.y = y || 0;
  935. this.z = z || 0;
  936. this.w = ( w !== undefined ) ? w : 1;
  937. };
  938. THREE.Vector4.prototype = {
  939. constructor: THREE.Vector4,
  940. set: function ( x, y, z, w ) {
  941. this.x = x;
  942. this.y = y;
  943. this.z = z;
  944. this.w = w;
  945. return this;
  946. },
  947. setX: function ( x ) {
  948. this.x = x;
  949. return this;
  950. },
  951. setY: function ( y ) {
  952. this.y = y;
  953. return this;
  954. },
  955. setZ: function ( z ) {
  956. this.z = z;
  957. return this;
  958. },
  959. setW: function ( w ) {
  960. this.w = w;
  961. return this;
  962. },
  963. setComponent: function ( index, value ) {
  964. switch ( index ) {
  965. case 0: this.x = value; break;
  966. case 1: this.y = value; break;
  967. case 2: this.z = value; break;
  968. case 3: this.w = value; break;
  969. default: throw new Error( "index is out of range: " + index );
  970. }
  971. },
  972. getComponent: function ( index ) {
  973. switch ( index ) {
  974. case 0: return this.x;
  975. case 1: return this.y;
  976. case 2: return this.z;
  977. case 3: return this.w;
  978. default: throw new Error( "index is out of range: " + index );
  979. }
  980. },
  981. copy: function ( v ) {
  982. this.x = v.x;
  983. this.y = v.y;
  984. this.z = v.z;
  985. this.w = ( v.w !== undefined ) ? v.w : 1;
  986. return this;
  987. },
  988. addScalar: function ( s ) {
  989. this.x += s;
  990. this.y += s;
  991. this.z += s;
  992. this.w += s;
  993. return this;
  994. },
  995. add: function ( a, b ) {
  996. this.x = a.x + b.x;
  997. this.y = a.y + b.y;
  998. this.z = a.z + b.z;
  999. this.w = a.w + b.w;
  1000. return this;
  1001. },
  1002. addSelf: function ( v ) {
  1003. this.x += v.x;
  1004. this.y += v.y;
  1005. this.z += v.z;
  1006. this.w += v.w;
  1007. return this;
  1008. },
  1009. sub: function ( a, b ) {
  1010. this.x = a.x - b.x;
  1011. this.y = a.y - b.y;
  1012. this.z = a.z - b.z;
  1013. this.w = a.w - b.w;
  1014. return this;
  1015. },
  1016. subSelf: function ( v ) {
  1017. this.x -= v.x;
  1018. this.y -= v.y;
  1019. this.z -= v.z;
  1020. this.w -= v.w;
  1021. return this;
  1022. },
  1023. multiplyScalar: function ( s ) {
  1024. this.x *= s;
  1025. this.y *= s;
  1026. this.z *= s;
  1027. this.w *= s;
  1028. return this;
  1029. },
  1030. applyMatrix4: function ( m ) {
  1031. var x = this.x;
  1032. var y = this.y;
  1033. var z = this.z;
  1034. var w = this.w;
  1035. var e = m.elements;
  1036. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1037. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1038. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1039. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1040. return this;
  1041. },
  1042. divideScalar: function ( s ) {
  1043. if ( s !== 0 ) {
  1044. this.x /= s;
  1045. this.y /= s;
  1046. this.z /= s;
  1047. this.w /= s;
  1048. } else {
  1049. this.x = 0;
  1050. this.y = 0;
  1051. this.z = 0;
  1052. this.w = 1;
  1053. }
  1054. return this;
  1055. },
  1056. minSelf: function ( v ) {
  1057. if ( this.x > v.x ) {
  1058. this.x = v.x;
  1059. }
  1060. if ( this.y > v.y ) {
  1061. this.y = v.y;
  1062. }
  1063. if ( this.z > v.z ) {
  1064. this.z = v.z;
  1065. }
  1066. if ( this.w > v.w ) {
  1067. this.w = v.w;
  1068. }
  1069. return this;
  1070. },
  1071. maxSelf: function ( v ) {
  1072. if ( this.x < v.x ) {
  1073. this.x = v.x;
  1074. }
  1075. if ( this.y < v.y ) {
  1076. this.y = v.y;
  1077. }
  1078. if ( this.z < v.z ) {
  1079. this.z = v.z;
  1080. }
  1081. if ( this.w < v.w ) {
  1082. this.w = v.w;
  1083. }
  1084. return this;
  1085. },
  1086. clampSelf: function ( min, max ) {
  1087. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1088. if ( this.x < min.x ) {
  1089. this.x = min.x;
  1090. } else if ( this.x > max.x ) {
  1091. this.x = max.x;
  1092. }
  1093. if ( this.y < min.y ) {
  1094. this.y = min.y;
  1095. } else if ( this.y > max.y ) {
  1096. this.y = max.y;
  1097. }
  1098. if ( this.z < min.z ) {
  1099. this.z = min.z;
  1100. } else if ( this.z > max.z ) {
  1101. this.z = max.z;
  1102. }
  1103. if ( this.w < min.w ) {
  1104. this.w = min.w;
  1105. } else if ( this.w > max.w ) {
  1106. this.w = max.w;
  1107. }
  1108. return this;
  1109. },
  1110. negate: function() {
  1111. return this.multiplyScalar( -1 );
  1112. },
  1113. dot: function ( v ) {
  1114. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1115. },
  1116. lengthSq: function () {
  1117. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1118. },
  1119. length: function () {
  1120. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1121. },
  1122. lengthManhattan: function () {
  1123. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1124. },
  1125. normalize: function () {
  1126. return this.divideScalar( this.length() );
  1127. },
  1128. setLength: function ( l ) {
  1129. var oldLength = this.length();
  1130. if ( oldLength !== 0 && l !== oldLength ) {
  1131. this.multiplyScalar( l / oldLength );
  1132. }
  1133. return this;
  1134. },
  1135. lerpSelf: function ( v, alpha ) {
  1136. this.x += ( v.x - this.x ) * alpha;
  1137. this.y += ( v.y - this.y ) * alpha;
  1138. this.z += ( v.z - this.z ) * alpha;
  1139. this.w += ( v.w - this.w ) * alpha;
  1140. return this;
  1141. },
  1142. equals: function ( v ) {
  1143. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1144. },
  1145. clone: function () {
  1146. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1147. },
  1148. setAxisAngleFromQuaternion: function ( q ) {
  1149. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1150. // q is assumed to be normalized
  1151. this.w = 2 * Math.acos( q.w );
  1152. var s = Math.sqrt( 1 - q.w * q.w );
  1153. if ( s < 0.0001 ) {
  1154. this.x = 1;
  1155. this.y = 0;
  1156. this.z = 0;
  1157. } else {
  1158. this.x = q.x / s;
  1159. this.y = q.y / s;
  1160. this.z = q.z / s;
  1161. }
  1162. return this;
  1163. },
  1164. setAxisAngleFromRotationMatrix: function ( m ) {
  1165. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1166. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1167. var angle, x, y, z, // variables for result
  1168. epsilon = 0.01, // margin to allow for rounding errors
  1169. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1170. te = m.elements,
  1171. m11 = te[0], m12 = te[4], m13 = te[8],
  1172. m21 = te[1], m22 = te[5], m23 = te[9],
  1173. m31 = te[2], m32 = te[6], m33 = te[10];
  1174. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1175. && ( Math.abs( m13 - m31 ) < epsilon )
  1176. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1177. // singularity found
  1178. // first check for identity matrix which must have +1 for all terms
  1179. // in leading diagonal and zero in other terms
  1180. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1181. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1182. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1183. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1184. // this singularity is identity matrix so angle = 0
  1185. this.set( 1, 0, 0, 0 );
  1186. return this; // zero angle, arbitrary axis
  1187. }
  1188. // otherwise this singularity is angle = 180
  1189. angle = Math.PI;
  1190. var xx = ( m11 + 1 ) / 2;
  1191. var yy = ( m22 + 1 ) / 2;
  1192. var zz = ( m33 + 1 ) / 2;
  1193. var xy = ( m12 + m21 ) / 4;
  1194. var xz = ( m13 + m31 ) / 4;
  1195. var yz = ( m23 + m32 ) / 4;
  1196. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1197. if ( xx < epsilon ) {
  1198. x = 0;
  1199. y = 0.707106781;
  1200. z = 0.707106781;
  1201. } else {
  1202. x = Math.sqrt( xx );
  1203. y = xy / x;
  1204. z = xz / x;
  1205. }
  1206. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1207. if ( yy < epsilon ) {
  1208. x = 0.707106781;
  1209. y = 0;
  1210. z = 0.707106781;
  1211. } else {
  1212. y = Math.sqrt( yy );
  1213. x = xy / y;
  1214. z = yz / y;
  1215. }
  1216. } else { // m33 is the largest diagonal term so base result on this
  1217. if ( zz < epsilon ) {
  1218. x = 0.707106781;
  1219. y = 0.707106781;
  1220. z = 0;
  1221. } else {
  1222. z = Math.sqrt( zz );
  1223. x = xz / z;
  1224. y = yz / z;
  1225. }
  1226. }
  1227. this.set( x, y, z, angle );
  1228. return this; // return 180 deg rotation
  1229. }
  1230. // as we have reached here there are no singularities so we can handle normally
  1231. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1232. + ( m13 - m31 ) * ( m13 - m31 )
  1233. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1234. if ( Math.abs( s ) < 0.001 ) s = 1;
  1235. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1236. // caught by singularity test above, but I've left it in just in case
  1237. this.x = ( m32 - m23 ) / s;
  1238. this.y = ( m13 - m31 ) / s;
  1239. this.z = ( m21 - m12 ) / s;
  1240. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1241. return this;
  1242. }
  1243. };
  1244. /**
  1245. * @author bhouston / http://exocortex.com
  1246. */
  1247. THREE.Box2 = function ( min, max ) {
  1248. this.min = min !== undefined ? min.clone() : new THREE.Vector2( Infinity, Infinity );
  1249. this.max = max !== undefined ? max.clone() : new THREE.Vector2( -Infinity, -Infinity );
  1250. };
  1251. THREE.Box2.prototype = {
  1252. constructor: THREE.Box2,
  1253. set: function ( min, max ) {
  1254. this.min.copy( min );
  1255. this.max.copy( max );
  1256. return this;
  1257. },
  1258. setFromPoints: function ( points ) {
  1259. if ( points.length > 0 ) {
  1260. var point = points[ 0 ];
  1261. this.min.copy( point );
  1262. this.max.copy( point );
  1263. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1264. point = points[ i ];
  1265. if ( point.x < this.min.x ) {
  1266. this.min.x = point.x;
  1267. } else if ( point.x > this.max.x ) {
  1268. this.max.x = point.x;
  1269. }
  1270. if ( point.y < this.min.y ) {
  1271. this.min.y = point.y;
  1272. } else if ( point.y > this.max.y ) {
  1273. this.max.y = point.y;
  1274. }
  1275. }
  1276. } else {
  1277. this.makeEmpty();
  1278. }
  1279. return this;
  1280. },
  1281. setFromCenterAndSize: function ( center, size ) {
  1282. var halfSize = THREE.Box2.__v1.copy( size ).multiplyScalar( 0.5 );
  1283. this.min.copy( center ).subSelf( halfSize );
  1284. this.max.copy( center ).addSelf( halfSize );
  1285. return this;
  1286. },
  1287. copy: function ( box ) {
  1288. this.min.copy( box.min );
  1289. this.max.copy( box.max );
  1290. return this;
  1291. },
  1292. makeEmpty: function () {
  1293. this.min.x = this.min.y = Infinity;
  1294. this.max.x = this.max.y = -Infinity;
  1295. return this;
  1296. },
  1297. empty: function () {
  1298. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1299. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1300. },
  1301. center: function ( optionalTarget ) {
  1302. var result = optionalTarget || new THREE.Vector2();
  1303. return result.add( this.min, this.max ).multiplyScalar( 0.5 );
  1304. },
  1305. size: function ( optionalTarget ) {
  1306. var result = optionalTarget || new THREE.Vector2();
  1307. return result.sub( this.max, this.min );
  1308. },
  1309. expandByPoint: function ( point ) {
  1310. this.min.minSelf( point );
  1311. this.max.maxSelf( point );
  1312. return this;
  1313. },
  1314. expandByVector: function ( vector ) {
  1315. this.min.subSelf( vector );
  1316. this.max.addSelf( vector );
  1317. return this;
  1318. },
  1319. expandByScalar: function ( scalar ) {
  1320. this.min.addScalar( -scalar );
  1321. this.max.addScalar( scalar );
  1322. return this;
  1323. },
  1324. containsPoint: function ( point ) {
  1325. if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
  1326. ( this.min.y <= point.y ) && ( point.y <= this.max.y ) ) {
  1327. return true;
  1328. }
  1329. return false;
  1330. },
  1331. containsBox: function ( box ) {
  1332. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1333. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1334. return true;
  1335. }
  1336. return false;
  1337. },
  1338. getParameter: function ( point ) {
  1339. // This can potentially have a divide by zero if the box
  1340. // has a size dimension of 0.
  1341. return new THREE.Vector2(
  1342. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1343. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1344. );
  1345. },
  1346. isIntersectionBox: function ( box ) {
  1347. // using 6 splitting planes to rule out intersections.
  1348. if ( ( box.max.x < this.min.x ) ||
  1349. ( box.min.x > this.max.x ) ||
  1350. ( box.max.y < this.min.y ) ||
  1351. ( box.min.y > this.max.y ) ) {
  1352. return false;
  1353. }
  1354. return true;
  1355. },
  1356. clampPoint: function ( point, optionalTarget ) {
  1357. var result = optionalTarget || new THREE.Vector2();
  1358. return result.copy( point ).clampSelf( this.min, this.max );
  1359. },
  1360. distanceToPoint: function ( point ) {
  1361. var clampedPoint = THREE.Box2.__v1.copy( point ).clampSelf( this.min, this.max );
  1362. return clampedPoint.subSelf( point ).length();
  1363. },
  1364. intersect: function ( box ) {
  1365. this.min.maxSelf( box.min );
  1366. this.max.minSelf( box.max );
  1367. return this;
  1368. },
  1369. union: function ( box ) {
  1370. this.min.minSelf( box.min );
  1371. this.max.maxSelf( box.max );
  1372. return this;
  1373. },
  1374. translate: function ( offset ) {
  1375. this.min.addSelf( offset );
  1376. this.max.addSelf( offset );
  1377. return this;
  1378. },
  1379. equals: function ( box ) {
  1380. return box.min.equals( this.min ) && box.max.equals( this.max );
  1381. },
  1382. clone: function () {
  1383. return new THREE.Box2().copy( this );
  1384. }
  1385. };
  1386. THREE.Box2.__v1 = new THREE.Vector2();
  1387. /**
  1388. * @author bhouston / http://exocortex.com
  1389. */
  1390. THREE.Box3 = function ( min, max ) {
  1391. this.min = min !== undefined ? min.clone() : new THREE.Vector3( Infinity, Infinity, Infinity );
  1392. this.max = max !== undefined ? max.clone() : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1393. };
  1394. THREE.Box3.prototype = {
  1395. constructor: THREE.Box3,
  1396. set: function ( min, max ) {
  1397. this.min.copy( min );
  1398. this.max.copy( max );
  1399. return this;
  1400. },
  1401. setFromPoints: function ( points ) {
  1402. if ( points.length > 0 ) {
  1403. var p = points[ 0 ];
  1404. this.min.copy( p );
  1405. this.max.copy( p );
  1406. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1407. p = points[ i ];
  1408. if ( p.x < this.min.x ) {
  1409. this.min.x = p.x;
  1410. } else if ( p.x > this.max.x ) {
  1411. this.max.x = p.x;
  1412. }
  1413. if ( p.y < this.min.y ) {
  1414. this.min.y = p.y;
  1415. } else if ( p.y > this.max.y ) {
  1416. this.max.y = p.y;
  1417. }
  1418. if ( p.z < this.min.z ) {
  1419. this.min.z = p.z;
  1420. } else if ( p.z > this.max.z ) {
  1421. this.max.z = p.z;
  1422. }
  1423. }
  1424. } else {
  1425. this.makeEmpty();
  1426. }
  1427. return this;
  1428. },
  1429. setFromCenterAndSize: function ( center, size ) {
  1430. var halfSize = THREE.Box3.__v1.copy( size ).multiplyScalar( 0.5 );
  1431. this.min.copy( center ).subSelf( halfSize );
  1432. this.max.copy( center ).addSelf( halfSize );
  1433. return this;
  1434. },
  1435. copy: function ( box ) {
  1436. this.min.copy( box.min );
  1437. this.max.copy( box.max );
  1438. return this;
  1439. },
  1440. makeEmpty: function () {
  1441. this.min.x = this.min.y = this.min.z = Infinity;
  1442. this.max.x = this.max.y = this.max.z = -Infinity;
  1443. return this;
  1444. },
  1445. empty: function () {
  1446. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1447. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1448. },
  1449. center: function ( optionalTarget ) {
  1450. var result = optionalTarget || new THREE.Vector3();
  1451. return result.add( this.min, this.max ).multiplyScalar( 0.5 );
  1452. },
  1453. size: function ( optionalTarget ) {
  1454. var result = optionalTarget || new THREE.Vector3();
  1455. return result.sub( this.max, this.min );
  1456. },
  1457. expandByPoint: function ( point ) {
  1458. this.min.minSelf( point );
  1459. this.max.maxSelf( point );
  1460. return this;
  1461. },
  1462. expandByVector: function ( vector ) {
  1463. this.min.subSelf( vector );
  1464. this.max.addSelf( vector );
  1465. return this;
  1466. },
  1467. expandByScalar: function ( scalar ) {
  1468. this.min.addScalar( -scalar );
  1469. this.max.addScalar( scalar );
  1470. return this;
  1471. },
  1472. containsPoint: function ( point ) {
  1473. if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
  1474. ( this.min.y <= point.y ) && ( point.y <= this.max.y ) &&
  1475. ( this.min.z <= point.z ) && ( point.z <= this.max.z ) ) {
  1476. return true;
  1477. }
  1478. return false;
  1479. },
  1480. containsBox: function ( box ) {
  1481. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1482. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1483. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1484. return true;
  1485. }
  1486. return false;
  1487. },
  1488. getParameter: function ( point ) {
  1489. // This can potentially have a divide by zero if the box
  1490. // has a size dimension of 0.
  1491. return new THREE.Vector3(
  1492. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1493. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1494. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1495. );
  1496. },
  1497. isIntersectionBox: function ( box ) {
  1498. // using 6 splitting planes to rule out intersections.
  1499. if ( ( box.max.x < this.min.x ) || ( box.min.x > this.max.x ) ||
  1500. ( box.max.y < this.min.y ) || ( box.min.y > this.max.y ) ||
  1501. ( box.max.z < this.min.z ) || ( box.min.z > this.max.z ) ) {
  1502. return false;
  1503. }
  1504. return true;
  1505. },
  1506. clampPoint: function ( point, optionalTarget ) {
  1507. var result = optionalTarget || new THREE.Vector3();
  1508. return new THREE.Vector3().copy( point ).clampSelf( this.min, this.max );
  1509. },
  1510. distanceToPoint: function ( point ) {
  1511. var clampedPoint = THREE.Box3.__v1.copy( point ).clampSelf( this.min, this.max );
  1512. return clampedPoint.subSelf( point ).length();
  1513. },
  1514. getBoundingSphere: function ( optionalTarget ) {
  1515. var result = optionalTarget || new THREE.Sphere();
  1516. result.center = this.center();
  1517. result.radius = this.size( THREE.Box3.__v0 ).length() * 0.5;;
  1518. return result;
  1519. },
  1520. intersect: function ( box ) {
  1521. this.min.maxSelf( box.min );
  1522. this.max.minSelf( box.max );
  1523. return this;
  1524. },
  1525. union: function ( box ) {
  1526. this.min.minSelf( box.min );
  1527. this.max.maxSelf( box.max );
  1528. return this;
  1529. },
  1530. transform: function ( matrix ) {
  1531. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  1532. var newPoints = [
  1533. THREE.Box3.__v0.set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ),
  1534. THREE.Box3.__v0.set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ), // 000
  1535. THREE.Box3.__v1.set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ), // 001
  1536. THREE.Box3.__v2.set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ), // 010
  1537. THREE.Box3.__v3.set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ), // 011
  1538. THREE.Box3.__v4.set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ), // 100
  1539. THREE.Box3.__v5.set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ), // 101
  1540. THREE.Box3.__v6.set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ), // 110
  1541. THREE.Box3.__v7.set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ) // 111
  1542. ];
  1543. this.makeEmpty();
  1544. this.setFromPoints( newPoints );
  1545. return this;
  1546. },
  1547. translate: function ( offset ) {
  1548. this.min.addSelf( offset );
  1549. this.max.addSelf( offset );
  1550. return this;
  1551. },
  1552. equals: function ( box ) {
  1553. return box.min.equals( this.min ) && box.max.equals( this.max );
  1554. },
  1555. clone: function () {
  1556. return new THREE.Box3().copy( this );
  1557. }
  1558. };
  1559. THREE.Box3.__v0 = new THREE.Vector3();
  1560. THREE.Box3.__v1 = new THREE.Vector3();
  1561. THREE.Box3.__v2 = new THREE.Vector3();
  1562. THREE.Box3.__v3 = new THREE.Vector3();
  1563. THREE.Box3.__v4 = new THREE.Vector3();
  1564. THREE.Box3.__v5 = new THREE.Vector3();
  1565. THREE.Box3.__v6 = new THREE.Vector3();
  1566. THREE.Box3.__v7 = new THREE.Vector3();
  1567. /**
  1568. * @author alteredq / http://alteredqualia.com/
  1569. * @author WestLangley / http://github.com/WestLangley
  1570. * @author bhouston / http://exocortex.com
  1571. */
  1572. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1573. this.elements = new Float32Array(9);
  1574. this.set(
  1575. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  1576. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  1577. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  1578. );
  1579. };
  1580. THREE.Matrix3.prototype = {
  1581. constructor: THREE.Matrix3,
  1582. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1583. var te = this.elements;
  1584. te[0] = n11; te[3] = n12; te[6] = n13;
  1585. te[1] = n21; te[4] = n22; te[7] = n23;
  1586. te[2] = n31; te[5] = n32; te[8] = n33;
  1587. return this;
  1588. },
  1589. identity: function () {
  1590. this.set(
  1591. 1, 0, 0,
  1592. 0, 1, 0,
  1593. 0, 0, 1
  1594. );
  1595. return this;
  1596. },
  1597. copy: function ( m ) {
  1598. var me = m.elements;
  1599. this.set(
  1600. me[0], me[3], me[6],
  1601. me[1], me[4], me[7],
  1602. me[2], me[5], me[8]
  1603. );
  1604. return this;
  1605. },
  1606. multiplyVector3Array: function ( a ) {
  1607. var tmp = THREE.Matrix3.__v1;
  1608. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1609. tmp.x = a[ i ];
  1610. tmp.y = a[ i + 1 ];
  1611. tmp.z = a[ i + 2 ];
  1612. this.multiplyVector3( tmp );
  1613. a[ i ] = tmp.x;
  1614. a[ i + 1 ] = tmp.y;
  1615. a[ i + 2 ] = tmp.z;
  1616. }
  1617. return a;
  1618. },
  1619. multiplyScalar: function ( s ) {
  1620. var te = this.elements;
  1621. te[0] *= s; te[3] *= s; te[6] *= s;
  1622. te[1] *= s; te[4] *= s; te[7] *= s;
  1623. te[2] *= s; te[5] *= s; te[8] *= s;
  1624. return this;
  1625. },
  1626. determinant: function () {
  1627. var te = this.elements;
  1628. var a = te[0], b = te[1], c = te[2],
  1629. d = te[3], e = te[4], f = te[5],
  1630. g = te[6], h = te[7], i = te[8];
  1631. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  1632. },
  1633. getInverse: function ( matrix, throwOnInvertible ) {
  1634. // input: THREE.Matrix4
  1635. // ( based on http://code.google.com/p/webgl-mjs/ )
  1636. var me = matrix.elements;
  1637. var te = this.elements;
  1638. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  1639. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  1640. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  1641. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  1642. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  1643. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  1644. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  1645. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  1646. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  1647. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  1648. // no inverse
  1649. if ( det === 0 ) {
  1650. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  1651. if ( throwOnInvertible || false ) {
  1652. throw new Error( msg );
  1653. } else {
  1654. console.warn( msg );
  1655. }
  1656. this.identity();
  1657. return this;
  1658. }
  1659. this.multiplyScalar( 1.0 / det );
  1660. return this;
  1661. },
  1662. transpose: function () {
  1663. var tmp, m = this.elements;
  1664. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  1665. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  1666. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  1667. return this;
  1668. },
  1669. transposeIntoArray: function ( r ) {
  1670. var m = this.elements;
  1671. r[ 0 ] = m[ 0 ];
  1672. r[ 1 ] = m[ 3 ];
  1673. r[ 2 ] = m[ 6 ];
  1674. r[ 3 ] = m[ 1 ];
  1675. r[ 4 ] = m[ 4 ];
  1676. r[ 5 ] = m[ 7 ];
  1677. r[ 6 ] = m[ 2 ];
  1678. r[ 7 ] = m[ 5 ];
  1679. r[ 8 ] = m[ 8 ];
  1680. return this;
  1681. },
  1682. clone: function () {
  1683. var te = this.elements;
  1684. return new THREE.Matrix3(
  1685. te[0], te[3], te[6],
  1686. te[1], te[4], te[7],
  1687. te[2], te[5], te[8]
  1688. );
  1689. }
  1690. };
  1691. THREE.Matrix3.__v1 = new THREE.Vector3();
  1692. /**
  1693. * @author mrdoob / http://mrdoob.com/
  1694. * @author supereggbert / http://www.paulbrunt.co.uk/
  1695. * @author philogb / http://blog.thejit.org/
  1696. * @author jordi_ros / http://plattsoft.com
  1697. * @author D1plo1d / http://github.com/D1plo1d
  1698. * @author alteredq / http://alteredqualia.com/
  1699. * @author mikael emtinger / http://gomo.se/
  1700. * @author timknip / http://www.floorplanner.com/
  1701. * @author bhouston / http://exocortex.com
  1702. */
  1703. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1704. this.elements = new Float32Array( 16 );
  1705. this.set(
  1706. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  1707. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  1708. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  1709. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  1710. );
  1711. };
  1712. THREE.Matrix4.prototype = {
  1713. constructor: THREE.Matrix4,
  1714. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1715. var te = this.elements;
  1716. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  1717. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1718. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1719. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1720. return this;
  1721. },
  1722. identity: function () {
  1723. this.set(
  1724. 1, 0, 0, 0,
  1725. 0, 1, 0, 0,
  1726. 0, 0, 1, 0,
  1727. 0, 0, 0, 1
  1728. );
  1729. return this;
  1730. },
  1731. copy: function ( m ) {
  1732. var me = m.elements;
  1733. this.set(
  1734. me[0], me[4], me[8], me[12],
  1735. me[1], me[5], me[9], me[13],
  1736. me[2], me[6], me[10], me[14],
  1737. me[3], me[7], me[11], me[15]
  1738. );
  1739. return this;
  1740. },
  1741. setRotationFromEuler: function ( v, order ) {
  1742. var te = this.elements;
  1743. var x = v.x, y = v.y, z = v.z;
  1744. var a = Math.cos( x ), b = Math.sin( x );
  1745. var c = Math.cos( y ), d = Math.sin( y );
  1746. var e = Math.cos( z ), f = Math.sin( z );
  1747. if ( order === undefined || order === 'XYZ' ) {
  1748. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1749. te[0] = c * e;
  1750. te[4] = - c * f;
  1751. te[8] = d;
  1752. te[1] = af + be * d;
  1753. te[5] = ae - bf * d;
  1754. te[9] = - b * c;
  1755. te[2] = bf - ae * d;
  1756. te[6] = be + af * d;
  1757. te[10] = a * c;
  1758. } else if ( order === 'YXZ' ) {
  1759. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1760. te[0] = ce + df * b;
  1761. te[4] = de * b - cf;
  1762. te[8] = a * d;
  1763. te[1] = a * f;
  1764. te[5] = a * e;
  1765. te[9] = - b;
  1766. te[2] = cf * b - de;
  1767. te[6] = df + ce * b;
  1768. te[10] = a * c;
  1769. } else if ( order === 'ZXY' ) {
  1770. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1771. te[0] = ce - df * b;
  1772. te[4] = - a * f;
  1773. te[8] = de + cf * b;
  1774. te[1] = cf + de * b;
  1775. te[5] = a * e;
  1776. te[9] = df - ce * b;
  1777. te[2] = - a * d;
  1778. te[6] = b;
  1779. te[10] = a * c;
  1780. } else if ( order === 'ZYX' ) {
  1781. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1782. te[0] = c * e;
  1783. te[4] = be * d - af;
  1784. te[8] = ae * d + bf;
  1785. te[1] = c * f;
  1786. te[5] = bf * d + ae;
  1787. te[9] = af * d - be;
  1788. te[2] = - d;
  1789. te[6] = b * c;
  1790. te[10] = a * c;
  1791. } else if ( order === 'YZX' ) {
  1792. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1793. te[0] = c * e;
  1794. te[4] = bd - ac * f;
  1795. te[8] = bc * f + ad;
  1796. te[1] = f;
  1797. te[5] = a * e;
  1798. te[9] = - b * e;
  1799. te[2] = - d * e;
  1800. te[6] = ad * f + bc;
  1801. te[10] = ac - bd * f;
  1802. } else if ( order === 'XZY' ) {
  1803. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1804. te[0] = c * e;
  1805. te[4] = - f;
  1806. te[8] = d * e;
  1807. te[1] = ac * f + bd;
  1808. te[5] = a * e;
  1809. te[9] = ad * f - bc;
  1810. te[2] = bc * f - ad;
  1811. te[6] = b * e;
  1812. te[10] = bd * f + ac;
  1813. }
  1814. return this;
  1815. },
  1816. setRotationFromQuaternion: function ( q ) {
  1817. var te = this.elements;
  1818. var x = q.x, y = q.y, z = q.z, w = q.w;
  1819. var x2 = x + x, y2 = y + y, z2 = z + z;
  1820. var xx = x * x2, xy = x * y2, xz = x * z2;
  1821. var yy = y * y2, yz = y * z2, zz = z * z2;
  1822. var wx = w * x2, wy = w * y2, wz = w * z2;
  1823. te[0] = 1 - ( yy + zz );
  1824. te[4] = xy - wz;
  1825. te[8] = xz + wy;
  1826. te[1] = xy + wz;
  1827. te[5] = 1 - ( xx + zz );
  1828. te[9] = yz - wx;
  1829. te[2] = xz - wy;
  1830. te[6] = yz + wx;
  1831. te[10] = 1 - ( xx + yy );
  1832. return this;
  1833. },
  1834. lookAt: function ( eye, target, up ) {
  1835. var te = this.elements;
  1836. var x = THREE.Matrix4.__v1;
  1837. var y = THREE.Matrix4.__v2;
  1838. var z = THREE.Matrix4.__v3;
  1839. z.sub( eye, target ).normalize();
  1840. if ( z.length() === 0 ) {
  1841. z.z = 1;
  1842. }
  1843. x.cross( up, z ).normalize();
  1844. if ( x.length() === 0 ) {
  1845. z.x += 0.0001;
  1846. x.cross( up, z ).normalize();
  1847. }
  1848. y.cross( z, x );
  1849. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1850. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1851. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1852. return this;
  1853. },
  1854. multiply: function ( a, b ) {
  1855. var ae = a.elements;
  1856. var be = b.elements;
  1857. var te = this.elements;
  1858. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1859. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1860. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1861. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1862. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1863. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1864. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1865. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1866. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1867. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1868. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1869. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1870. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1871. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1872. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1873. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1874. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1875. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1876. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1877. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1878. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1879. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1880. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1881. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1882. return this;
  1883. },
  1884. multiplySelf: function ( m ) {
  1885. return this.multiply( this, m );
  1886. },
  1887. multiplyToArray: function ( a, b, r ) {
  1888. var te = this.elements;
  1889. this.multiply( a, b );
  1890. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1891. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1892. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1893. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1894. return this;
  1895. },
  1896. multiplyScalar: function ( s ) {
  1897. var te = this.elements;
  1898. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1899. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1900. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1901. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1902. return this;
  1903. },
  1904. multiplyVector3Array: function ( a ) {
  1905. var tmp = THREE.Matrix4.__v1;
  1906. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1907. tmp.x = a[ i ];
  1908. tmp.y = a[ i + 1 ];
  1909. tmp.z = a[ i + 2 ];
  1910. this.multiplyVector3( tmp );
  1911. a[ i ] = tmp.x;
  1912. a[ i + 1 ] = tmp.y;
  1913. a[ i + 2 ] = tmp.z;
  1914. }
  1915. return a;
  1916. },
  1917. rotateAxis: function ( v ) {
  1918. var te = this.elements;
  1919. var vx = v.x, vy = v.y, vz = v.z;
  1920. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1921. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1922. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1923. v.normalize();
  1924. return v;
  1925. },
  1926. crossVector: function ( a ) {
  1927. var te = this.elements;
  1928. var v = new THREE.Vector4();
  1929. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1930. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1931. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1932. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1933. return v;
  1934. },
  1935. determinant: function () {
  1936. var te = this.elements;
  1937. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1938. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1939. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1940. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1941. //TODO: make this more efficient
  1942. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1943. return (
  1944. n41 * (
  1945. +n14 * n23 * n32
  1946. -n13 * n24 * n32
  1947. -n14 * n22 * n33
  1948. +n12 * n24 * n33
  1949. +n13 * n22 * n34
  1950. -n12 * n23 * n34
  1951. ) +
  1952. n42 * (
  1953. +n11 * n23 * n34
  1954. -n11 * n24 * n33
  1955. +n14 * n21 * n33
  1956. -n13 * n21 * n34
  1957. +n13 * n24 * n31
  1958. -n14 * n23 * n31
  1959. ) +
  1960. n43 * (
  1961. +n11 * n24 * n32
  1962. -n11 * n22 * n34
  1963. -n14 * n21 * n32
  1964. +n12 * n21 * n34
  1965. +n14 * n22 * n31
  1966. -n12 * n24 * n31
  1967. ) +
  1968. n44 * (
  1969. -n13 * n22 * n31
  1970. -n11 * n23 * n32
  1971. +n11 * n22 * n33
  1972. +n13 * n21 * n32
  1973. -n12 * n21 * n33
  1974. +n12 * n23 * n31
  1975. )
  1976. );
  1977. },
  1978. transpose: function () {
  1979. var te = this.elements;
  1980. var tmp;
  1981. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1982. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1983. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1984. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1985. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1986. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1987. return this;
  1988. },
  1989. flattenToArray: function ( flat ) {
  1990. var te = this.elements;
  1991. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1992. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1993. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1994. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1995. return flat;
  1996. },
  1997. flattenToArrayOffset: function( flat, offset ) {
  1998. var te = this.elements;
  1999. flat[ offset ] = te[0];
  2000. flat[ offset + 1 ] = te[1];
  2001. flat[ offset + 2 ] = te[2];
  2002. flat[ offset + 3 ] = te[3];
  2003. flat[ offset + 4 ] = te[4];
  2004. flat[ offset + 5 ] = te[5];
  2005. flat[ offset + 6 ] = te[6];
  2006. flat[ offset + 7 ] = te[7];
  2007. flat[ offset + 8 ] = te[8];
  2008. flat[ offset + 9 ] = te[9];
  2009. flat[ offset + 10 ] = te[10];
  2010. flat[ offset + 11 ] = te[11];
  2011. flat[ offset + 12 ] = te[12];
  2012. flat[ offset + 13 ] = te[13];
  2013. flat[ offset + 14 ] = te[14];
  2014. flat[ offset + 15 ] = te[15];
  2015. return flat;
  2016. },
  2017. getPosition: function () {
  2018. var te = this.elements;
  2019. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  2020. },
  2021. setPosition: function ( v ) {
  2022. var te = this.elements;
  2023. te[12] = v.x;
  2024. te[13] = v.y;
  2025. te[14] = v.z;
  2026. return this;
  2027. },
  2028. getColumnX: function () {
  2029. var te = this.elements;
  2030. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  2031. },
  2032. getColumnY: function () {
  2033. var te = this.elements;
  2034. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  2035. },
  2036. getColumnZ: function() {
  2037. var te = this.elements;
  2038. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  2039. },
  2040. getInverse: function ( m, throwOnInvertible ) {
  2041. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2042. var te = this.elements;
  2043. var me = m.elements;
  2044. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2045. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2046. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2047. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2048. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2049. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2050. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2051. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2052. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2053. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2054. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2055. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2056. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2057. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2058. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2059. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2060. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2061. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2062. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2063. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2064. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 4 ] + me[ 2 ] * te[ 8 ] + me[ 3 ] * te[ 12 ];
  2065. if ( det == 0 ) {
  2066. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2067. if ( throwOnInvertible || false ) {
  2068. throw new Error( msg );
  2069. } else {
  2070. console.warn( msg );
  2071. }
  2072. this.identity();
  2073. return this;
  2074. }
  2075. this.multiplyScalar( 1 / det );
  2076. return this;
  2077. },
  2078. compose: function ( translation, rotation, scale ) {
  2079. var te = this.elements;
  2080. var mRotation = THREE.Matrix4.__m1;
  2081. var mScale = THREE.Matrix4.__m2;
  2082. mRotation.identity();
  2083. mRotation.setRotationFromQuaternion( rotation );
  2084. mScale.makeScale( scale );
  2085. this.multiply( mRotation, mScale );
  2086. te[12] = translation.x;
  2087. te[13] = translation.y;
  2088. te[14] = translation.z;
  2089. return this;
  2090. },
  2091. decompose: function ( translation, rotation, scale ) {
  2092. var te = this.elements;
  2093. // grab the axis vectors
  2094. var x = THREE.Matrix4.__v1;
  2095. var y = THREE.Matrix4.__v2;
  2096. var z = THREE.Matrix4.__v3;
  2097. x.set( te[0], te[1], te[2] );
  2098. y.set( te[4], te[5], te[6] );
  2099. z.set( te[8], te[9], te[10] );
  2100. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  2101. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  2102. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2103. scale.x = x.length();
  2104. scale.y = y.length();
  2105. scale.z = z.length();
  2106. translation.x = te[12];
  2107. translation.y = te[13];
  2108. translation.z = te[14];
  2109. // scale the rotation part
  2110. var matrix = THREE.Matrix4.__m1;
  2111. matrix.copy( this );
  2112. matrix.elements[0] /= scale.x;
  2113. matrix.elements[1] /= scale.x;
  2114. matrix.elements[2] /= scale.x;
  2115. matrix.elements[4] /= scale.y;
  2116. matrix.elements[5] /= scale.y;
  2117. matrix.elements[6] /= scale.y;
  2118. matrix.elements[8] /= scale.z;
  2119. matrix.elements[9] /= scale.z;
  2120. matrix.elements[10] /= scale.z;
  2121. rotation.setFromRotationMatrix( matrix );
  2122. return [ translation, rotation, scale ];
  2123. },
  2124. extractPosition: function ( m ) {
  2125. var te = this.elements;
  2126. var me = m.elements;
  2127. te[12] = me[12];
  2128. te[13] = me[13];
  2129. te[14] = me[14];
  2130. return this;
  2131. },
  2132. extractRotation: function ( m ) {
  2133. var te = this.elements;
  2134. var me = m.elements;
  2135. var vector = THREE.Matrix4.__v1;
  2136. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  2137. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  2138. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  2139. te[0] = me[0] * scaleX;
  2140. te[1] = me[1] * scaleX;
  2141. te[2] = me[2] * scaleX;
  2142. te[4] = me[4] * scaleY;
  2143. te[5] = me[5] * scaleY;
  2144. te[6] = me[6] * scaleY;
  2145. te[8] = me[8] * scaleZ;
  2146. te[9] = me[9] * scaleZ;
  2147. te[10] = me[10] * scaleZ;
  2148. return this;
  2149. },
  2150. //
  2151. translate: function ( v ) {
  2152. var te = this.elements;
  2153. var x = v.x, y = v.y, z = v.z;
  2154. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  2155. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  2156. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  2157. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  2158. return this;
  2159. },
  2160. rotateX: function ( angle ) {
  2161. var te = this.elements;
  2162. var m12 = te[4];
  2163. var m22 = te[5];
  2164. var m32 = te[6];
  2165. var m42 = te[7];
  2166. var m13 = te[8];
  2167. var m23 = te[9];
  2168. var m33 = te[10];
  2169. var m43 = te[11];
  2170. var c = Math.cos( angle );
  2171. var s = Math.sin( angle );
  2172. te[4] = c * m12 + s * m13;
  2173. te[5] = c * m22 + s * m23;
  2174. te[6] = c * m32 + s * m33;
  2175. te[7] = c * m42 + s * m43;
  2176. te[8] = c * m13 - s * m12;
  2177. te[9] = c * m23 - s * m22;
  2178. te[10] = c * m33 - s * m32;
  2179. te[11] = c * m43 - s * m42;
  2180. return this;
  2181. },
  2182. rotateY: function ( angle ) {
  2183. var te = this.elements;
  2184. var m11 = te[0];
  2185. var m21 = te[1];
  2186. var m31 = te[2];
  2187. var m41 = te[3];
  2188. var m13 = te[8];
  2189. var m23 = te[9];
  2190. var m33 = te[10];
  2191. var m43 = te[11];
  2192. var c = Math.cos( angle );
  2193. var s = Math.sin( angle );
  2194. te[0] = c * m11 - s * m13;
  2195. te[1] = c * m21 - s * m23;
  2196. te[2] = c * m31 - s * m33;
  2197. te[3] = c * m41 - s * m43;
  2198. te[8] = c * m13 + s * m11;
  2199. te[9] = c * m23 + s * m21;
  2200. te[10] = c * m33 + s * m31;
  2201. te[11] = c * m43 + s * m41;
  2202. return this;
  2203. },
  2204. rotateZ: function ( angle ) {
  2205. var te = this.elements;
  2206. var m11 = te[0];
  2207. var m21 = te[1];
  2208. var m31 = te[2];
  2209. var m41 = te[3];
  2210. var m12 = te[4];
  2211. var m22 = te[5];
  2212. var m32 = te[6];
  2213. var m42 = te[7];
  2214. var c = Math.cos( angle );
  2215. var s = Math.sin( angle );
  2216. te[0] = c * m11 + s * m12;
  2217. te[1] = c * m21 + s * m22;
  2218. te[2] = c * m31 + s * m32;
  2219. te[3] = c * m41 + s * m42;
  2220. te[4] = c * m12 - s * m11;
  2221. te[5] = c * m22 - s * m21;
  2222. te[6] = c * m32 - s * m31;
  2223. te[7] = c * m42 - s * m41;
  2224. return this;
  2225. },
  2226. rotateByAxis: function ( axis, angle ) {
  2227. var te = this.elements;
  2228. // optimize by checking axis
  2229. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  2230. return this.rotateX( angle );
  2231. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  2232. return this.rotateY( angle );
  2233. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  2234. return this.rotateZ( angle );
  2235. }
  2236. var x = axis.x, y = axis.y, z = axis.z;
  2237. var n = Math.sqrt(x * x + y * y + z * z);
  2238. x /= n;
  2239. y /= n;
  2240. z /= n;
  2241. var xx = x * x, yy = y * y, zz = z * z;
  2242. var c = Math.cos( angle );
  2243. var s = Math.sin( angle );
  2244. var oneMinusCosine = 1 - c;
  2245. var xy = x * y * oneMinusCosine;
  2246. var xz = x * z * oneMinusCosine;
  2247. var yz = y * z * oneMinusCosine;
  2248. var xs = x * s;
  2249. var ys = y * s;
  2250. var zs = z * s;
  2251. var r11 = xx + (1 - xx) * c;
  2252. var r21 = xy + zs;
  2253. var r31 = xz - ys;
  2254. var r12 = xy - zs;
  2255. var r22 = yy + (1 - yy) * c;
  2256. var r32 = yz + xs;
  2257. var r13 = xz + ys;
  2258. var r23 = yz - xs;
  2259. var r33 = zz + (1 - zz) * c;
  2260. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  2261. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  2262. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  2263. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  2264. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  2265. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  2266. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  2267. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  2268. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  2269. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  2270. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  2271. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  2272. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  2273. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  2274. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  2275. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  2276. return this;
  2277. },
  2278. scale: function ( v ) {
  2279. var te = this.elements;
  2280. var x = v.x, y = v.y, z = v.z;
  2281. te[0] *= x; te[4] *= y; te[8] *= z;
  2282. te[1] *= x; te[5] *= y; te[9] *= z;
  2283. te[2] *= x; te[6] *= y; te[10] *= z;
  2284. te[3] *= x; te[7] *= y; te[11] *= z;
  2285. return this;
  2286. },
  2287. getMaxScaleOnAxis: function () {
  2288. var te = this.elements;
  2289. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2290. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2291. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2292. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2293. },
  2294. //
  2295. makeTranslation: function ( offset ) {
  2296. this.set(
  2297. 1, 0, 0, offset.x,
  2298. 0, 1, 0, offset.y,
  2299. 0, 0, 1, offset.z,
  2300. 0, 0, 0, 1
  2301. );
  2302. return this;
  2303. },
  2304. makeRotationX: function ( theta ) {
  2305. var c = Math.cos( theta ), s = Math.sin( theta );
  2306. this.set(
  2307. 1, 0, 0, 0,
  2308. 0, c, -s, 0,
  2309. 0, s, c, 0,
  2310. 0, 0, 0, 1
  2311. );
  2312. return this;
  2313. },
  2314. makeRotationY: function ( theta ) {
  2315. var c = Math.cos( theta ), s = Math.sin( theta );
  2316. this.set(
  2317. c, 0, s, 0,
  2318. 0, 1, 0, 0,
  2319. -s, 0, c, 0,
  2320. 0, 0, 0, 1
  2321. );
  2322. return this;
  2323. },
  2324. makeRotationZ: function ( theta ) {
  2325. var c = Math.cos( theta ), s = Math.sin( theta );
  2326. this.set(
  2327. c, -s, 0, 0,
  2328. s, c, 0, 0,
  2329. 0, 0, 1, 0,
  2330. 0, 0, 0, 1
  2331. );
  2332. return this;
  2333. },
  2334. makeRotationAxis: function ( axis, angle ) {
  2335. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2336. var c = Math.cos( angle );
  2337. var s = Math.sin( angle );
  2338. var t = 1 - c;
  2339. var x = axis.x, y = axis.y, z = axis.z;
  2340. var tx = t * x, ty = t * y;
  2341. this.set(
  2342. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2343. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2344. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2345. 0, 0, 0, 1
  2346. );
  2347. return this;
  2348. },
  2349. makeScale: function ( factor ) {
  2350. this.set(
  2351. factor.x, 0, 0, 0,
  2352. 0, factor.y, 0, 0,
  2353. 0, 0, factor.z, 0,
  2354. 0, 0, 0, 1
  2355. );
  2356. return this;
  2357. },
  2358. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2359. var te = this.elements;
  2360. var x = 2 * near / ( right - left );
  2361. var y = 2 * near / ( top - bottom );
  2362. var a = ( right + left ) / ( right - left );
  2363. var b = ( top + bottom ) / ( top - bottom );
  2364. var c = - ( far + near ) / ( far - near );
  2365. var d = - 2 * far * near / ( far - near );
  2366. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2367. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2368. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2369. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2370. return this;
  2371. },
  2372. makePerspective: function ( fov, aspect, near, far ) {
  2373. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2374. var ymin = - ymax;
  2375. var xmin = ymin * aspect;
  2376. var xmax = ymax * aspect;
  2377. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2378. },
  2379. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2380. var te = this.elements;
  2381. var w = right - left;
  2382. var h = top - bottom;
  2383. var p = far - near;
  2384. var x = ( right + left ) / w;
  2385. var y = ( top + bottom ) / h;
  2386. var z = ( far + near ) / p;
  2387. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2388. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2389. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2390. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2391. return this;
  2392. },
  2393. clone: function () {
  2394. var te = this.elements;
  2395. return new THREE.Matrix4(
  2396. te[0], te[4], te[8], te[12],
  2397. te[1], te[5], te[9], te[13],
  2398. te[2], te[6], te[10], te[14],
  2399. te[3], te[7], te[11], te[15]
  2400. );
  2401. }
  2402. };
  2403. THREE.Matrix4.__v1 = new THREE.Vector3();
  2404. THREE.Matrix4.__v2 = new THREE.Vector3();
  2405. THREE.Matrix4.__v3 = new THREE.Vector3();
  2406. THREE.Matrix4.__m1 = new THREE.Matrix4();
  2407. THREE.Matrix4.__m2 = new THREE.Matrix4();
  2408. /**
  2409. * @author bhouston / http://exocortex.com
  2410. */
  2411. THREE.Ray = function ( origin, direction ) {
  2412. this.origin = origin !== undefined ? origin.clone() : new THREE.Vector3();
  2413. this.direction = direction !== undefined ? direction.clone() : new THREE.Vector3();
  2414. };
  2415. THREE.Ray.prototype = {
  2416. constructor: THREE.Ray,
  2417. set: function ( origin, direction ) {
  2418. this.origin.copy( origin );
  2419. this.direction.copy( direction );
  2420. return this;
  2421. },
  2422. copy: function ( ray ) {
  2423. this.origin.copy( ray.origin );
  2424. this.direction.copy( ray.direction );
  2425. return this;
  2426. },
  2427. at: function( t, optionalTarget ) {
  2428. var result = optionalTarget || new THREE.Vector3();
  2429. return result.copy( this.direction ).multiplyScalar( t ).addSelf( this.origin );
  2430. },
  2431. recastSelf: function ( t ) {
  2432. this.origin.copy( this.at( t, THREE.Ray.__v1 ) );
  2433. return this;
  2434. },
  2435. closestPointToPoint: function ( point, optionalTarget ) {
  2436. var result = optionalTarget || new THREE.Vector3();
  2437. result.sub( point, this.origin );
  2438. var directionDistance = result.dot( this.direction );
  2439. return result.copy( this.direction ).multiplyScalar( directionDistance ).addSelf( this.origin );
  2440. },
  2441. distanceToPoint: function ( point ) {
  2442. var directionDistance = THREE.Ray.__v1.sub( point, this.origin ).dot( this.direction );
  2443. THREE.Ray.__v1.copy( this.direction ).multiplyScalar( directionDistance ).addSelf( this.origin );
  2444. return THREE.Ray.__v1.distanceTo( point );
  2445. },
  2446. isIntersectionSphere: function( sphere ) {
  2447. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  2448. },
  2449. isIntersectionPlane: function ( plane ) {
  2450. // check if the line and plane are non-perpendicular, if they
  2451. // eventually they will intersect.
  2452. var denominator = plane.normal.dot( this.direction );
  2453. if ( denominator != 0 ) {
  2454. return true;
  2455. }
  2456. // line is coplanar, return origin
  2457. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2458. return true;
  2459. }
  2460. return false;
  2461. },
  2462. distanceToPlane: function ( plane ) {
  2463. var denominator = plane.normal.dot( this.direction );
  2464. if ( denominator == 0 ) {
  2465. // line is coplanar, return origin
  2466. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2467. return 0;
  2468. }
  2469. // Unsure if this is the correct method to handle this case.
  2470. return undefined;
  2471. }
  2472. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2473. return t;
  2474. },
  2475. intersectPlane: function ( plane, optionalTarget ) {
  2476. var t = this.distanceToPlane( plane );
  2477. if( t === undefined ) {
  2478. return undefined;
  2479. }
  2480. return this.at( t, optionalTarget );
  2481. },
  2482. transform: function ( matrix4 ) {
  2483. this.direction.addSelf( this.origin ).applyMatrix4( matrix4 );
  2484. this.origin.applyMatrix4( matrix4 );
  2485. this.direction.subSelf( this.origin );
  2486. return this;
  2487. },
  2488. equals: function ( ray ) {
  2489. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  2490. },
  2491. clone: function () {
  2492. return new THREE.Ray().copy( this );
  2493. }
  2494. };
  2495. THREE.Ray.__v1 = new THREE.Vector3();
  2496. THREE.Ray.__v2 = new THREE.Vector3();
  2497. /**
  2498. * @author mrdoob / http://mrdoob.com/
  2499. * @author alteredq / http://alteredqualia.com/
  2500. * @author bhouston / http://exocortex.com
  2501. */
  2502. THREE.Frustum = function ( ) {
  2503. this.planes = [
  2504. new THREE.Plane(),
  2505. new THREE.Plane(),
  2506. new THREE.Plane(),
  2507. new THREE.Plane(),
  2508. new THREE.Plane(),
  2509. new THREE.Plane()
  2510. ];
  2511. };
  2512. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  2513. var planes = this.planes;
  2514. var me = m.elements;
  2515. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  2516. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  2517. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  2518. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  2519. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  2520. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  2521. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  2522. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  2523. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  2524. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  2525. for ( var i = 0; i < 6; i ++ ) {
  2526. planes[ i ].normalize();
  2527. }
  2528. };
  2529. THREE.Frustum.prototype.contains = function ( object ) {
  2530. var planes = this.planes;
  2531. var matrix = object.matrixWorld;
  2532. var matrixPosition = matrix.getPosition();
  2533. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  2534. var distance = 0.0;
  2535. for ( var i = 0; i < 6; i ++ ) {
  2536. distance = planes[ i ].distanceToPoint( matrixPosition );
  2537. if ( distance <= radius ) return false;
  2538. }
  2539. return true;
  2540. };
  2541. THREE.Frustum.__v1 = new THREE.Vector3();
  2542. /**
  2543. * @author bhouston / http://exocortex.com
  2544. */
  2545. THREE.Plane = function ( normal, constant ) {
  2546. this.normal = normal !== undefined ? normal.clone() : new THREE.Vector3( 1, 0, 0 );
  2547. this.constant = constant !== undefined ? constant : 0;
  2548. };
  2549. THREE.Plane.prototype = {
  2550. constructor: THREE.Plane,
  2551. set: function ( normal, constant ) {
  2552. this.normal.copy( normal );
  2553. this.constant = constant;
  2554. return this;
  2555. },
  2556. setComponents: function ( x, y, z, w ) {
  2557. this.normal.set( x, y, z );
  2558. this.constant = w;
  2559. return this;
  2560. },
  2561. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  2562. this.normal.copy( normal ).normalize();
  2563. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  2564. return this;
  2565. },
  2566. setFromCoplanarPoints: function ( a, b, c ) {
  2567. var normal = THREE.Plane.__v1.sub( c, b ).crossSelf(
  2568. THREE.Plane.__v2.sub( a, b ) ).normalize();
  2569. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  2570. this.setFromNormalAndCoplanarPoint( normal, a );
  2571. return this;
  2572. },
  2573. copy: function ( plane ) {
  2574. this.normal.copy( plane.normal );
  2575. this.constant = plane.constant;
  2576. return this;
  2577. },
  2578. normalize: function () {
  2579. // Note: will lead to a divide by zero if the plane is invalid.
  2580. var inverseNormalLength = 1.0 / this.normal.length();
  2581. this.normal.multiplyScalar( inverseNormalLength );
  2582. this.constant *= inverseNormalLength;
  2583. return this;
  2584. },
  2585. distanceToPoint: function ( point ) {
  2586. return this.normal.dot( point ) + this.constant;
  2587. },
  2588. distanceToSphere: function ( sphere ) {
  2589. return this.distanceToPoint( sphere.center ) - sphere.radius;
  2590. },
  2591. projectPoint: function ( point, optionalTarget ) {
  2592. return this.orthoPoint( point, optionalTarget ).subSelf( point ).negate();
  2593. },
  2594. orthoPoint: function ( point, optionalTarget ) {
  2595. var perpendicularMagnitude = this.distanceToPoint( point );
  2596. var result = optionalTarget || new THREE.Vector3();
  2597. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  2598. },
  2599. isIntersectionLine: function ( startPoint, endPoint ) {
  2600. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  2601. var startSign = this.distanceToPoint( startPoint );
  2602. var endSign = this.distanceToPoint( endPoint );
  2603. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  2604. },
  2605. intersectLine: function ( startPoint, endPoint, optionalTarget ) {
  2606. var result = optionalTarget || new THREE.Vector3();
  2607. var direction = THREE.Plane.__v1.sub( endPoint, startPoint );
  2608. var denominator = this.normal.dot( direction );
  2609. if ( denominator == 0 ) {
  2610. // line is coplanar, return origin
  2611. if( this.distanceToPoint( startPoint ) == 0 ) {
  2612. return result.copy( startPoint );
  2613. }
  2614. // Unsure if this is the correct method to handle this case.
  2615. return undefined;
  2616. }
  2617. var t = - ( startPoint.dot( this.normal ) + this.constant ) / denominator;
  2618. if( t < 0 || t > 1 ) {
  2619. return undefined;
  2620. }
  2621. return result.copy( direction ).multiplyScalar( t ).addSelf( startPoint );
  2622. },
  2623. coplanarPoint: function ( optionalTarget ) {
  2624. var result = optionalTarget || new THREE.Vector3();
  2625. return result.copy( this.normal ).multiplyScalar( - this.constant );
  2626. },
  2627. transform: function ( matrix, optionalNormalMatrix ) {
  2628. var newNormal = THREE.Plane.__v1, newCoplanarPoint = THREE.Plane.__v2;
  2629. // compute new normal based on theory here:
  2630. // http://www.songho.ca/opengl/gl_normaltransform.html
  2631. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getInverse( matrix ).transpose();
  2632. newNormal.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  2633. newCoplanarPoint = this.coplanarPoint( newCoplanarPoint );
  2634. newCoplanarPoint.applyMatrix4( matrix );
  2635. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  2636. return this;
  2637. },
  2638. translate: function ( offset ) {
  2639. this.constant = this.constant - offset.dot( this.normal );
  2640. return this;
  2641. },
  2642. equals: function ( plane ) {
  2643. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  2644. },
  2645. clone: function () {
  2646. return new THREE.Plane().copy( this );
  2647. }
  2648. };
  2649. THREE.Plane.__vZero = new THREE.Vector3( 0, 0, 0 );
  2650. THREE.Plane.__v1 = new THREE.Vector3();
  2651. THREE.Plane.__v2 = new THREE.Vector3();
  2652. /**
  2653. * @author bhouston / http://exocortex.com
  2654. * @author mrdoob / http://mrdoob.com/
  2655. */
  2656. THREE.Sphere = function ( center, radius ) {
  2657. this.center = center === undefined ? new THREE.Vector3() : center.clone();
  2658. this.radius = radius === undefined ? 0 : radius;
  2659. };
  2660. THREE.Sphere.prototype = {
  2661. constructor: THREE.Sphere,
  2662. set: function ( center, radius ) {
  2663. this.center.copy( center );
  2664. this.radius = radius;
  2665. return this;
  2666. },
  2667. setFromCenterAndPoints: function ( center, points ) {
  2668. var maxRadiusSq = 0;
  2669. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2670. var radiusSq = center.distanceToSquared( points[ i ] );
  2671. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2672. }
  2673. this.center = center;
  2674. this.radius = Math.sqrt( maxRadiusSq );
  2675. return this;
  2676. },
  2677. copy: function ( sphere ) {
  2678. this.center.copy( sphere.center );
  2679. this.radius = sphere.radius;
  2680. return this;
  2681. },
  2682. empty: function () {
  2683. return ( this.radius <= 0 );
  2684. },
  2685. containsPoint: function ( point ) {
  2686. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2687. },
  2688. distanceToPoint: function ( point ) {
  2689. return ( point.distanceTo( this.center ) - this.radius );
  2690. },
  2691. clampPoint: function ( point, optionalTarget ) {
  2692. var deltaLengthSq = this.center.distanceToSquared( point );
  2693. var result = optionalTarget || new THREE.Vector3();
  2694. result.copy( point );
  2695. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2696. result.subSelf( this.center ).normalize();
  2697. result.multiplyScalar( this.radius ).addSelf( this.center );
  2698. }
  2699. return result;
  2700. },
  2701. getBoundingBox: function ( optionalTarget ) {
  2702. var box = optionalTarget || new THREE.Box3();
  2703. box.set( this.center, this.center );
  2704. box.expandByScalar( this.radius );
  2705. return box;
  2706. },
  2707. transform: function ( matrix ) {
  2708. this.center.applyMatrix4( matrix );
  2709. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2710. return this;
  2711. },
  2712. translate: function ( offset ) {
  2713. this.center.addSelf( offset );
  2714. return this;
  2715. },
  2716. equals: function ( sphere ) {
  2717. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2718. },
  2719. clone: function () {
  2720. return new THREE.Sphere().copy( this );
  2721. }
  2722. };
  2723. /**
  2724. * @author alteredq / http://alteredqualia.com/
  2725. */
  2726. THREE.Math = {
  2727. // Clamp value to range <a, b>
  2728. clamp: function ( x, a, b ) {
  2729. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2730. },
  2731. // Clamp value to range <a, inf)
  2732. clampBottom: function ( x, a ) {
  2733. return x < a ? a : x;
  2734. },
  2735. // Linear mapping from range <a1, a2> to range <b1, b2>
  2736. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2737. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2738. },
  2739. // Random float from <0, 1> with 16 bits of randomness
  2740. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2741. random16: function () {
  2742. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2743. },
  2744. // Random integer from <low, high> interval
  2745. randInt: function ( low, high ) {
  2746. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2747. },
  2748. // Random float from <low, high> interval
  2749. randFloat: function ( low, high ) {
  2750. return low + Math.random() * ( high - low );
  2751. },
  2752. // Random float from <-range/2, range/2> interval
  2753. randFloatSpread: function ( range ) {
  2754. return range * ( 0.5 - Math.random() );
  2755. },
  2756. sign: function ( x ) {
  2757. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2758. },
  2759. degToRad: function ( degrees ) {
  2760. return degrees * THREE.Math.__d2r;
  2761. },
  2762. radToDeg: function ( radians ) {
  2763. return radians * THREE.Math.__r2d;
  2764. }
  2765. };
  2766. THREE.Math.__d2r = Math.PI / 180;
  2767. THREE.Math.__r2d = 180 / Math.PI;
  2768. /**
  2769. * @author mikael emtinger / http://gomo.se/
  2770. * @author alteredq / http://alteredqualia.com/
  2771. * @author WestLangley / http://github.com/WestLangley
  2772. * @author bhouston / http://exocortex.com
  2773. */
  2774. THREE.Quaternion = function( x, y, z, w ) {
  2775. this.x = x || 0;
  2776. this.y = y || 0;
  2777. this.z = z || 0;
  2778. this.w = ( w !== undefined ) ? w : 1;
  2779. };
  2780. THREE.Quaternion.prototype = {
  2781. constructor: THREE.Quaternion,
  2782. set: function ( x, y, z, w ) {
  2783. this.x = x;
  2784. this.y = y;
  2785. this.z = z;
  2786. this.w = w;
  2787. return this;
  2788. },
  2789. copy: function ( q ) {
  2790. this.x = q.x;
  2791. this.y = q.y;
  2792. this.z = q.z;
  2793. this.w = q.w;
  2794. return this;
  2795. },
  2796. setFromEuler: function ( v, order ) {
  2797. // http://www.mathworks.com/matlabcentral/fileexchange/
  2798. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2799. // content/SpinCalc.m
  2800. var c1 = Math.cos( v.x / 2 );
  2801. var c2 = Math.cos( v.y / 2 );
  2802. var c3 = Math.cos( v.z / 2 );
  2803. var s1 = Math.sin( v.x / 2 );
  2804. var s2 = Math.sin( v.y / 2 );
  2805. var s3 = Math.sin( v.z / 2 );
  2806. if ( order === undefined || order === 'XYZ' ) {
  2807. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2808. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2809. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2810. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2811. } else if ( order === 'YXZ' ) {
  2812. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2813. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2814. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2815. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2816. } else if ( order === 'ZXY' ) {
  2817. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2818. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2819. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2820. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2821. } else if ( order === 'ZYX' ) {
  2822. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2823. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2824. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2825. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2826. } else if ( order === 'YZX' ) {
  2827. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2828. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2829. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2830. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2831. } else if ( order === 'XZY' ) {
  2832. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2833. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2834. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2835. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2836. }
  2837. return this;
  2838. },
  2839. setFromAxisAngle: function ( axis, angle ) {
  2840. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2841. // axis have to be normalized
  2842. var halfAngle = angle / 2,
  2843. s = Math.sin( halfAngle );
  2844. this.x = axis.x * s;
  2845. this.y = axis.y * s;
  2846. this.z = axis.z * s;
  2847. this.w = Math.cos( halfAngle );
  2848. return this;
  2849. },
  2850. setFromRotationMatrix: function ( m ) {
  2851. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2852. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2853. var te = m.elements,
  2854. m11 = te[0], m12 = te[4], m13 = te[8],
  2855. m21 = te[1], m22 = te[5], m23 = te[9],
  2856. m31 = te[2], m32 = te[6], m33 = te[10],
  2857. trace = m11 + m22 + m33,
  2858. s;
  2859. if( trace > 0 ) {
  2860. s = 0.5 / Math.sqrt( trace + 1.0 );
  2861. this.w = 0.25 / s;
  2862. this.x = ( m32 - m23 ) * s;
  2863. this.y = ( m13 - m31 ) * s;
  2864. this.z = ( m21 - m12 ) * s;
  2865. } else if ( m11 > m22 && m11 > m33 ) {
  2866. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2867. this.w = (m32 - m23 ) / s;
  2868. this.x = 0.25 * s;
  2869. this.y = (m12 + m21 ) / s;
  2870. this.z = (m13 + m31 ) / s;
  2871. } else if (m22 > m33) {
  2872. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2873. this.w = (m13 - m31 ) / s;
  2874. this.x = (m12 + m21 ) / s;
  2875. this.y = 0.25 * s;
  2876. this.z = (m23 + m32 ) / s;
  2877. } else {
  2878. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2879. this.w = ( m21 - m12 ) / s;
  2880. this.x = ( m13 + m31 ) / s;
  2881. this.y = ( m23 + m32 ) / s;
  2882. this.z = 0.25 * s;
  2883. }
  2884. return this;
  2885. },
  2886. inverse: function () {
  2887. this.conjugate().normalize();
  2888. return this;
  2889. },
  2890. conjugate: function () {
  2891. this.x *= -1;
  2892. this.y *= -1;
  2893. this.z *= -1;
  2894. return this;
  2895. },
  2896. lengthSq: function () {
  2897. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2898. },
  2899. length: function () {
  2900. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2901. },
  2902. normalize: function () {
  2903. var l = this.length();
  2904. if ( l === 0 ) {
  2905. this.x = 0;
  2906. this.y = 0;
  2907. this.z = 0;
  2908. this.w = 1;
  2909. } else {
  2910. l = 1 / l;
  2911. this.x = this.x * l;
  2912. this.y = this.y * l;
  2913. this.z = this.z * l;
  2914. this.w = this.w * l;
  2915. }
  2916. return this;
  2917. },
  2918. multiply: function ( a, b ) {
  2919. this.copy( a );
  2920. return this.multiplySelf( b );
  2921. },
  2922. multiplySelf: function ( b ) {
  2923. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2924. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2925. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2926. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2927. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2928. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2929. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2930. return this;
  2931. },
  2932. slerpSelf: function ( qb, t ) {
  2933. var x = this.x, y = this.y, z = this.z, w = this.w;
  2934. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2935. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  2936. if ( cosHalfTheta < 0 ) {
  2937. this.w = -qb.w;
  2938. this.x = -qb.x;
  2939. this.y = -qb.y;
  2940. this.z = -qb.z;
  2941. cosHalfTheta = -cosHalfTheta;
  2942. } else {
  2943. this.copy( qb );
  2944. }
  2945. if ( cosHalfTheta >= 1.0 ) {
  2946. this.w = w;
  2947. this.x = x;
  2948. this.y = y;
  2949. this.z = z;
  2950. return this;
  2951. }
  2952. var halfTheta = Math.acos( cosHalfTheta );
  2953. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2954. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2955. this.w = 0.5 * ( w + this.w );
  2956. this.x = 0.5 * ( x + this.x );
  2957. this.y = 0.5 * ( y + this.y );
  2958. this.z = 0.5 * ( z + this.z );
  2959. return this;
  2960. }
  2961. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2962. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2963. this.w = ( w * ratioA + this.w * ratioB );
  2964. this.x = ( x * ratioA + this.x * ratioB );
  2965. this.y = ( y * ratioA + this.y * ratioB );
  2966. this.z = ( z * ratioA + this.z * ratioB );
  2967. return this;
  2968. },
  2969. equals: function ( v ) {
  2970. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  2971. },
  2972. clone: function () {
  2973. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2974. }
  2975. }
  2976. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2977. return qm.copy( qa ).slerpSelf( qb, t );
  2978. }
  2979. /**
  2980. * Spline from Tween.js, slightly optimized (and trashed)
  2981. * http://sole.github.com/tween.js/examples/05_spline.html
  2982. *
  2983. * @author mrdoob / http://mrdoob.com/
  2984. * @author alteredq / http://alteredqualia.com/
  2985. */
  2986. THREE.Spline = function ( points ) {
  2987. this.points = points;
  2988. var c = [], v3 = { x: 0, y: 0, z: 0 },
  2989. point, intPoint, weight, w2, w3,
  2990. pa, pb, pc, pd;
  2991. this.initFromArray = function( a ) {
  2992. this.points = [];
  2993. for ( var i = 0; i < a.length; i++ ) {
  2994. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  2995. }
  2996. };
  2997. this.getPoint = function ( k ) {
  2998. point = ( this.points.length - 1 ) * k;
  2999. intPoint = Math.floor( point );
  3000. weight = point - intPoint;
  3001. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3002. c[ 1 ] = intPoint;
  3003. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3004. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3005. pa = this.points[ c[ 0 ] ];
  3006. pb = this.points[ c[ 1 ] ];
  3007. pc = this.points[ c[ 2 ] ];
  3008. pd = this.points[ c[ 3 ] ];
  3009. w2 = weight * weight;
  3010. w3 = weight * w2;
  3011. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3012. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3013. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3014. return v3;
  3015. };
  3016. this.getControlPointsArray = function () {
  3017. var i, p, l = this.points.length,
  3018. coords = [];
  3019. for ( i = 0; i < l; i ++ ) {
  3020. p = this.points[ i ];
  3021. coords[ i ] = [ p.x, p.y, p.z ];
  3022. }
  3023. return coords;
  3024. };
  3025. // approximate length by summing linear segments
  3026. this.getLength = function ( nSubDivisions ) {
  3027. var i, index, nSamples, position,
  3028. point = 0, intPoint = 0, oldIntPoint = 0,
  3029. oldPosition = new THREE.Vector3(),
  3030. tmpVec = new THREE.Vector3(),
  3031. chunkLengths = [],
  3032. totalLength = 0;
  3033. // first point has 0 length
  3034. chunkLengths[ 0 ] = 0;
  3035. if ( !nSubDivisions ) nSubDivisions = 100;
  3036. nSamples = this.points.length * nSubDivisions;
  3037. oldPosition.copy( this.points[ 0 ] );
  3038. for ( i = 1; i < nSamples; i ++ ) {
  3039. index = i / nSamples;
  3040. position = this.getPoint( index );
  3041. tmpVec.copy( position );
  3042. totalLength += tmpVec.distanceTo( oldPosition );
  3043. oldPosition.copy( position );
  3044. point = ( this.points.length - 1 ) * index;
  3045. intPoint = Math.floor( point );
  3046. if ( intPoint != oldIntPoint ) {
  3047. chunkLengths[ intPoint ] = totalLength;
  3048. oldIntPoint = intPoint;
  3049. }
  3050. }
  3051. // last point ends with total length
  3052. chunkLengths[ chunkLengths.length ] = totalLength;
  3053. return { chunks: chunkLengths, total: totalLength };
  3054. };
  3055. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3056. var i, j,
  3057. index, indexCurrent, indexNext,
  3058. linearDistance, realDistance,
  3059. sampling, position,
  3060. newpoints = [],
  3061. tmpVec = new THREE.Vector3(),
  3062. sl = this.getLength();
  3063. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3064. for ( i = 1; i < this.points.length; i++ ) {
  3065. //tmpVec.copy( this.points[ i - 1 ] );
  3066. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3067. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3068. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3069. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3070. indexNext = i / ( this.points.length - 1 );
  3071. for ( j = 1; j < sampling - 1; j++ ) {
  3072. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3073. position = this.getPoint( index );
  3074. newpoints.push( tmpVec.copy( position ).clone() );
  3075. }
  3076. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3077. }
  3078. this.points = newpoints;
  3079. };
  3080. // Catmull-Rom
  3081. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3082. var v0 = ( p2 - p0 ) * 0.5,
  3083. v1 = ( p3 - p1 ) * 0.5;
  3084. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3085. };
  3086. };
  3087. /**
  3088. * @author bhouston / http://exocortex.com
  3089. * @author mrdoob / http://mrdoob.com/
  3090. */
  3091. THREE.Triangle = function ( a, b, c ) {
  3092. this.a = new THREE.Vector3();
  3093. this.b = new THREE.Vector3();
  3094. this.c = new THREE.Vector3();
  3095. if( a !== undefined && b !== undefined && c !== undefined ) {
  3096. this.a.copy( a );
  3097. this.b.copy( b );
  3098. this.c.copy( c );
  3099. }
  3100. };
  3101. THREE.Triangle.normal = function( a, b, c, optionalTarget ) {
  3102. var result = optionalTarget || new THREE.Vector3();
  3103. result.sub( c, b );
  3104. THREE.Triangle.__v0.sub( a, b );
  3105. result.crossSelf( THREE.Triangle.__v0 );
  3106. var resultLengthSq = result.lengthSq();
  3107. if( resultLengthSq > 0 ) {
  3108. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3109. }
  3110. return result.set( 0, 0, 0 );
  3111. };
  3112. // static/instance method to calculate barycoordinates
  3113. THREE.Triangle.barycoordFromPoint = function ( point, a, b, c, optionalTarget ) {
  3114. THREE.Triangle.__v0.sub( c, a );
  3115. THREE.Triangle.__v1.sub( b, a );
  3116. THREE.Triangle.__v2.sub( point, a );
  3117. var dot00 = THREE.Triangle.__v0.dot( THREE.Triangle.__v0 );
  3118. var dot01 = THREE.Triangle.__v0.dot( THREE.Triangle.__v1 );
  3119. var dot02 = THREE.Triangle.__v0.dot( THREE.Triangle.__v2 );
  3120. var dot11 = THREE.Triangle.__v1.dot( THREE.Triangle.__v1 );
  3121. var dot12 = THREE.Triangle.__v1.dot( THREE.Triangle.__v2 );
  3122. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3123. var result = optionalTarget || new THREE.Vector3();
  3124. // colinear or singular triangle
  3125. if( denom == 0 ) {
  3126. // arbitrary location outside of triangle?
  3127. // not sure if this is the best idea, maybe should be returning undefined
  3128. return result.set( -2, -1, -1 );
  3129. }
  3130. var invDenom = 1 / denom;
  3131. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3132. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3133. // barycoordinates must always sum to 1
  3134. return result.set( 1 - u - v, v, u );
  3135. };
  3136. THREE.Triangle.containsPoint = function ( point, a, b, c ) {
  3137. // NOTE: need to use __v3 here because __v0, __v1 and __v2 are used in barycoordFromPoint.
  3138. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, THREE.Triangle.__v3 );
  3139. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3140. };
  3141. THREE.Triangle.prototype = {
  3142. constructor: THREE.Triangle,
  3143. set: function ( a, b, c ) {
  3144. this.a.copy( a );
  3145. this.b.copy( b );
  3146. this.c.copy( c );
  3147. return this;
  3148. },
  3149. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3150. this.a.copy( points[i0] );
  3151. this.b.copy( points[i1] );
  3152. this.c.copy( points[i2] );
  3153. return this;
  3154. },
  3155. copy: function ( triangle ) {
  3156. this.a.copy( triangle.a );
  3157. this.b.copy( triangle.b );
  3158. this.c.copy( triangle.c );
  3159. return this;
  3160. },
  3161. area: function () {
  3162. THREE.Triangle.__v0.sub( this.c, this.b );
  3163. THREE.Triangle.__v1.sub( this.a, this.b );
  3164. return THREE.Triangle.__v0.crossSelf( THREE.Triangle.__v1 ).length() * 0.5;
  3165. },
  3166. midpoint: function ( optionalTarget ) {
  3167. var result = optionalTarget || new THREE.Vector3();
  3168. return result.add( this.a, this.b ).addSelf( this.c ).multiplyScalar( 1 / 3 );
  3169. },
  3170. normal: function ( optionalTarget ) {
  3171. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3172. },
  3173. plane: function ( optionalTarget ) {
  3174. var result = optionalTarget || new THREE.Plane();
  3175. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3176. },
  3177. barycoordFromPoint: function ( point, optionalTarget ) {
  3178. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3179. },
  3180. containsPoint: function ( point ) {
  3181. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3182. },
  3183. equals: function ( triangle ) {
  3184. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3185. },
  3186. clone: function () {
  3187. return new THREE.Triangle().copy( this );
  3188. }
  3189. };
  3190. THREE.Triangle.__v0 = new THREE.Vector3();
  3191. THREE.Triangle.__v1 = new THREE.Vector3();
  3192. THREE.Triangle.__v2 = new THREE.Vector3();
  3193. THREE.Triangle.__v3 = new THREE.Vector3();
  3194. /**
  3195. * @author mrdoob / http://mrdoob.com/
  3196. */
  3197. THREE.Vertex = function ( v ) {
  3198. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3199. return v;
  3200. };
  3201. /**
  3202. * @author mrdoob / http://mrdoob.com/
  3203. */
  3204. THREE.UV = function ( u, v ) {
  3205. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3206. return new THREE.Vector2( u, v );
  3207. };
  3208. /**
  3209. * @author alteredq / http://alteredqualia.com/
  3210. */
  3211. THREE.Clock = function ( autoStart ) {
  3212. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3213. this.startTime = 0;
  3214. this.oldTime = 0;
  3215. this.elapsedTime = 0;
  3216. this.running = false;
  3217. };
  3218. THREE.Clock.prototype.start = function () {
  3219. this.startTime = Date.now();
  3220. this.oldTime = this.startTime;
  3221. this.running = true;
  3222. };
  3223. THREE.Clock.prototype.stop = function () {
  3224. this.getElapsedTime();
  3225. this.running = false;
  3226. };
  3227. THREE.Clock.prototype.getElapsedTime = function () {
  3228. this.getDelta();
  3229. return this.elapsedTime;
  3230. };
  3231. THREE.Clock.prototype.getDelta = function () {
  3232. var diff = 0;
  3233. if ( this.autoStart && ! this.running ) {
  3234. this.start();
  3235. }
  3236. if ( this.running ) {
  3237. var newTime = Date.now();
  3238. diff = 0.001 * ( newTime - this.oldTime );
  3239. this.oldTime = newTime;
  3240. this.elapsedTime += diff;
  3241. }
  3242. return diff;
  3243. };/**
  3244. * https://github.com/mrdoob/eventdispatcher.js/
  3245. */
  3246. THREE.EventDispatcher = function () {
  3247. var listeners = {};
  3248. this.addEventListener = function ( type, listener ) {
  3249. if ( listeners[ type ] === undefined ) {
  3250. listeners[ type ] = [];
  3251. }
  3252. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3253. listeners[ type ].push( listener );
  3254. }
  3255. };
  3256. this.removeEventListener = function ( type, listener ) {
  3257. var index = listeners[ type ].indexOf( listener );
  3258. if ( index !== - 1 ) {
  3259. listeners[ type ].splice( index, 1 );
  3260. }
  3261. };
  3262. this.dispatchEvent = function ( event ) {
  3263. var listenerArray = listeners[ event.type ];
  3264. if ( listenerArray !== undefined ) {
  3265. event.target = this;
  3266. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3267. listenerArray[ i ].call( this, event );
  3268. }
  3269. }
  3270. };
  3271. };
  3272. /**
  3273. * @author mrdoob / http://mrdoob.com/
  3274. * @author bhouston / http://exocortex.com/
  3275. */
  3276. ( function ( THREE ) {
  3277. THREE.Raycaster = function ( origin, direction, near, far ) {
  3278. this.ray = new THREE.Ray( origin, direction );
  3279. // normalized ray.direction required for accurate distance calculations
  3280. if( this.ray.direction.length() > 0 ) {
  3281. this.ray.direction.normalize();
  3282. }
  3283. this.near = near || 0;
  3284. this.far = far || Infinity;
  3285. };
  3286. var sphere = new THREE.Sphere();
  3287. var localRay = new THREE.Ray();
  3288. var facePlane = new THREE.Plane();
  3289. var intersectPoint = new THREE.Vector3();
  3290. var inverseMatrix = new THREE.Matrix4();
  3291. var descSort = function ( a, b ) {
  3292. return a.distance - b.distance;
  3293. };
  3294. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  3295. // http://www.blackpawn.com/texts/pointinpoly/default.html
  3296. var intersectObject = function ( object, raycaster, intersects ) {
  3297. if ( object instanceof THREE.Particle ) {
  3298. var distance = raycaster.ray.distanceToPoint( object.matrixWorld.getPosition() );
  3299. if ( distance > object.scale.x ) {
  3300. return intersects;
  3301. }
  3302. intersects.push( {
  3303. distance: distance,
  3304. point: object.position,
  3305. face: null,
  3306. object: object
  3307. } );
  3308. } else if ( object instanceof THREE.Mesh ) {
  3309. // Checking boundingSphere distance to ray
  3310. sphere.set(
  3311. object.matrixWorld.getPosition(),
  3312. object.geometry.boundingSphere.radius* object.matrixWorld.getMaxScaleOnAxis() );
  3313. if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
  3314. return intersects;
  3315. }
  3316. // Checking faces
  3317. var geometry = object.geometry;
  3318. var vertices = geometry.vertices;
  3319. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3320. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3321. var side = object.material.side;
  3322. var a, b, c, d;
  3323. var precision = raycaster.precision;
  3324. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  3325. inverseMatrix.getInverse( object.matrixWorld );
  3326. localRay.copy( raycaster.ray ).transform( inverseMatrix );
  3327. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3328. var face = geometry.faces[ f ];
  3329. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3330. if ( material === undefined ) continue;
  3331. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3332. var planeDistance = localRay.distanceToPlane( facePlane );
  3333. // bail if raycaster and plane are parallel
  3334. if ( Math.abs( planeDistance ) < precision ) continue;
  3335. // if negative distance, then plane is behind raycaster
  3336. if ( planeDistance < 0 ) continue;
  3337. // check if we hit the wrong side of a single sided face
  3338. side = material.side;
  3339. if( side !== THREE.DoubleSide ) {
  3340. var planeSign = localRay.direction.dot( facePlane.normal );
  3341. if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3342. }
  3343. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3344. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3345. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3346. if ( face instanceof THREE.Face3 ) {
  3347. a = vertices[ face.a ];
  3348. b = vertices[ face.b ];
  3349. c = vertices[ face.c ];
  3350. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3351. } else if ( face instanceof THREE.Face4 ) {
  3352. a = vertices[ face.a ];
  3353. b = vertices[ face.b ];
  3354. c = vertices[ face.c ];
  3355. d = vertices[ face.d ];
  3356. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3357. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3358. } else {
  3359. // This is added because if we call out of this if/else group when none of the cases
  3360. // match it will add a point to the intersection list erroneously.
  3361. throw Error( "face type not supported" );
  3362. }
  3363. intersects.push( {
  3364. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3365. point: raycaster.ray.at( planeDistance ),
  3366. face: face,
  3367. faceIndex: f,
  3368. object: object
  3369. } );
  3370. }
  3371. }
  3372. };
  3373. var intersectDescendants = function ( object, raycaster, intersects ) {
  3374. var descendants = object.getDescendants();
  3375. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3376. intersectObject( descendants[ i ], raycaster, intersects );
  3377. }
  3378. };
  3379. //
  3380. THREE.Raycaster.prototype.precision = 0.0001;
  3381. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3382. this.ray.set( origin, direction );
  3383. // normalized ray.direction required for accurate distance calculations
  3384. if( this.ray.direction.length() > 0 ) {
  3385. this.ray.direction.normalize();
  3386. }
  3387. };
  3388. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3389. var intersects = [];
  3390. if ( recursive === true ) {
  3391. intersectDescendants( object, this, intersects );
  3392. }
  3393. intersectObject( object, this, intersects );
  3394. intersects.sort( descSort );
  3395. return intersects;
  3396. };
  3397. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3398. var intersects = [];
  3399. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3400. intersectObject( objects[ i ], this, intersects );
  3401. if ( recursive === true ) {
  3402. intersectDescendants( objects[ i ], this, intersects );
  3403. }
  3404. }
  3405. intersects.sort( descSort );
  3406. return intersects;
  3407. };
  3408. }( THREE ) );
  3409. /**
  3410. * @author mrdoob / http://mrdoob.com/
  3411. * @author mikael emtinger / http://gomo.se/
  3412. * @author alteredq / http://alteredqualia.com/
  3413. */
  3414. THREE.Object3D = function () {
  3415. this.id = THREE.Object3DIdCount ++;
  3416. this.name = '';
  3417. this.properties = {};
  3418. this.parent = undefined;
  3419. this.children = [];
  3420. this.up = new THREE.Vector3( 0, 1, 0 );
  3421. this.position = new THREE.Vector3();
  3422. this.rotation = new THREE.Vector3();
  3423. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3424. this.scale = new THREE.Vector3( 1, 1, 1 );
  3425. this.renderDepth = null;
  3426. this.rotationAutoUpdate = true;
  3427. this.matrix = new THREE.Matrix4();
  3428. this.matrixWorld = new THREE.Matrix4();
  3429. this.matrixRotationWorld = new THREE.Matrix4();
  3430. this.matrixAutoUpdate = true;
  3431. this.matrixWorldNeedsUpdate = true;
  3432. this.quaternion = new THREE.Quaternion();
  3433. this.useQuaternion = false;
  3434. this.visible = true;
  3435. this.castShadow = false;
  3436. this.receiveShadow = false;
  3437. this.frustumCulled = true;
  3438. this._vector = new THREE.Vector3();
  3439. };
  3440. THREE.Object3D.prototype = {
  3441. constructor: THREE.Object3D,
  3442. applyMatrix: function ( matrix ) {
  3443. this.matrix.multiply( matrix, this.matrix );
  3444. this.scale.getScaleFromMatrix( this.matrix );
  3445. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  3446. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  3447. this.position.getPositionFromMatrix( this.matrix );
  3448. },
  3449. translate: function ( distance, axis ) {
  3450. this.matrix.rotateAxis( axis );
  3451. this.position.addSelf( axis.multiplyScalar( distance ) );
  3452. },
  3453. translateX: function ( distance ) {
  3454. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  3455. },
  3456. translateY: function ( distance ) {
  3457. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  3458. },
  3459. translateZ: function ( distance ) {
  3460. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  3461. },
  3462. localToWorld: function ( vector ) {
  3463. return vector.applyMatrix4( this.matrixWorld );
  3464. },
  3465. worldToLocal: function ( vector ) {
  3466. return vector.applyMatrix4( THREE.Object3D.__m1.getInverse( this.matrixWorld ) );
  3467. },
  3468. lookAt: function ( vector ) {
  3469. // TODO: Add hierarchy support.
  3470. this.matrix.lookAt( vector, this.position, this.up );
  3471. if ( this.rotationAutoUpdate ) {
  3472. if ( this.useQuaternion === false ) {
  3473. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3474. } else {
  3475. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  3476. }
  3477. }
  3478. },
  3479. add: function ( object ) {
  3480. if ( object === this ) {
  3481. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3482. return;
  3483. }
  3484. if ( object instanceof THREE.Object3D ) {
  3485. if ( object.parent !== undefined ) {
  3486. object.parent.remove( object );
  3487. }
  3488. object.parent = this;
  3489. this.children.push( object );
  3490. // add to scene
  3491. var scene = this;
  3492. while ( scene.parent !== undefined ) {
  3493. scene = scene.parent;
  3494. }
  3495. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3496. scene.__addObject( object );
  3497. }
  3498. }
  3499. },
  3500. remove: function ( object ) {
  3501. var index = this.children.indexOf( object );
  3502. if ( index !== - 1 ) {
  3503. object.parent = undefined;
  3504. this.children.splice( index, 1 );
  3505. // remove from scene
  3506. var scene = this;
  3507. while ( scene.parent !== undefined ) {
  3508. scene = scene.parent;
  3509. }
  3510. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3511. scene.__removeObject( object );
  3512. }
  3513. }
  3514. },
  3515. traverse: function ( callback ) {
  3516. callback( this );
  3517. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3518. this.children[ i ].traverse( callback );
  3519. }
  3520. },
  3521. getChildByName: function ( name, recursive ) {
  3522. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3523. var child = this.children[ i ];
  3524. if ( child.name === name ) {
  3525. return child;
  3526. }
  3527. if ( recursive === true ) {
  3528. child = child.getChildByName( name, recursive );
  3529. if ( child !== undefined ) {
  3530. return child;
  3531. }
  3532. }
  3533. }
  3534. return undefined;
  3535. },
  3536. getDescendants: function ( array ) {
  3537. if ( array === undefined ) array = [];
  3538. Array.prototype.push.apply( array, this.children );
  3539. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3540. this.children[ i ].getDescendants( array );
  3541. }
  3542. return array;
  3543. },
  3544. updateMatrix: function () {
  3545. this.matrix.setPosition( this.position );
  3546. if ( this.useQuaternion === false ) {
  3547. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  3548. } else {
  3549. this.matrix.setRotationFromQuaternion( this.quaternion );
  3550. }
  3551. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  3552. this.matrix.scale( this.scale );
  3553. }
  3554. this.matrixWorldNeedsUpdate = true;
  3555. },
  3556. updateMatrixWorld: function ( force ) {
  3557. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  3558. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  3559. if ( this.parent === undefined ) {
  3560. this.matrixWorld.copy( this.matrix );
  3561. } else {
  3562. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  3563. }
  3564. this.matrixWorldNeedsUpdate = false;
  3565. force = true;
  3566. }
  3567. // update children
  3568. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3569. this.children[ i ].updateMatrixWorld( force );
  3570. }
  3571. },
  3572. clone: function ( object ) {
  3573. if ( object === undefined ) object = new THREE.Object3D();
  3574. object.name = this.name;
  3575. object.up.copy( this.up );
  3576. object.position.copy( this.position );
  3577. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  3578. object.eulerOrder = this.eulerOrder;
  3579. object.scale.copy( this.scale );
  3580. object.renderDepth = this.renderDepth;
  3581. object.rotationAutoUpdate = this.rotationAutoUpdate;
  3582. object.matrix.copy( this.matrix );
  3583. object.matrixWorld.copy( this.matrixWorld );
  3584. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  3585. object.matrixAutoUpdate = this.matrixAutoUpdate;
  3586. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  3587. object.quaternion.copy( this.quaternion );
  3588. object.useQuaternion = this.useQuaternion;
  3589. object.visible = this.visible;
  3590. object.castShadow = this.castShadow;
  3591. object.receiveShadow = this.receiveShadow;
  3592. object.frustumCulled = this.frustumCulled;
  3593. for ( var i = 0; i < this.children.length; i ++ ) {
  3594. var child = this.children[ i ];
  3595. object.add( child.clone() );
  3596. }
  3597. return object;
  3598. }
  3599. };
  3600. THREE.Object3D.__m1 = new THREE.Matrix4();
  3601. THREE.Object3D.defaultEulerOrder = 'XYZ',
  3602. THREE.Object3DIdCount = 0;
  3603. /**
  3604. * @author mrdoob / http://mrdoob.com/
  3605. * @author supereggbert / http://www.paulbrunt.co.uk/
  3606. * @author julianwa / https://github.com/julianwa
  3607. */
  3608. THREE.Projector = function() {
  3609. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  3610. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  3611. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  3612. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  3613. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  3614. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  3615. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  3616. _vector3 = new THREE.Vector3(),
  3617. _vector4 = new THREE.Vector4(),
  3618. _viewMatrix = new THREE.Matrix4(),
  3619. _viewProjectionMatrix = new THREE.Matrix4(),
  3620. _modelMatrix,
  3621. _modelViewProjectionMatrix = new THREE.Matrix4(),
  3622. _normalMatrix = new THREE.Matrix3(),
  3623. _normalViewMatrix = new THREE.Matrix3(),
  3624. _centroid = new THREE.Vector3(),
  3625. _frustum = new THREE.Frustum(),
  3626. _clippedVertex1PositionScreen = new THREE.Vector4(),
  3627. _clippedVertex2PositionScreen = new THREE.Vector4(),
  3628. _face3VertexNormals;
  3629. this.projectVector = function ( vector, camera ) {
  3630. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3631. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  3632. return vector.applyMatrix4( _viewProjectionMatrix );
  3633. };
  3634. this.unprojectVector = function ( vector, camera ) {
  3635. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  3636. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  3637. return vector.applyMatrix4( _viewProjectionMatrix );
  3638. };
  3639. this.pickingRay = function ( vector, camera ) {
  3640. // set two vectors with opposing z values
  3641. vector.z = -1.0;
  3642. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  3643. this.unprojectVector( vector, camera );
  3644. this.unprojectVector( end, camera );
  3645. // find direction from vector to end
  3646. end.subSelf( vector ).normalize();
  3647. return new THREE.Raycaster( vector, end );
  3648. };
  3649. var projectGraph = function ( root, sortObjects ) {
  3650. _objectCount = 0;
  3651. _renderData.objects.length = 0;
  3652. _renderData.sprites.length = 0;
  3653. _renderData.lights.length = 0;
  3654. var projectObject = function ( parent ) {
  3655. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  3656. var object = parent.children[ c ];
  3657. if ( object.visible === false ) continue;
  3658. if ( object instanceof THREE.Light ) {
  3659. _renderData.lights.push( object );
  3660. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  3661. if ( object.frustumCulled === false || _frustum.contains( object ) === true ) {
  3662. _object = getNextObjectInPool();
  3663. _object.object = object;
  3664. if ( object.renderDepth !== null ) {
  3665. _object.z = object.renderDepth;
  3666. } else {
  3667. _vector3.copy( object.matrixWorld.getPosition() );
  3668. _vector3.applyMatrix4( _viewProjectionMatrix );
  3669. _object.z = _vector3.z;
  3670. }
  3671. _renderData.objects.push( _object );
  3672. }
  3673. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  3674. _object = getNextObjectInPool();
  3675. _object.object = object;
  3676. // TODO: Find an elegant and performant solution and remove this dupe code.
  3677. if ( object.renderDepth !== null ) {
  3678. _object.z = object.renderDepth;
  3679. } else {
  3680. _vector3.copy( object.matrixWorld.getPosition() );
  3681. _vector3.applyMatrix4( _viewProjectionMatrix );
  3682. _object.z = _vector3.z;
  3683. }
  3684. _renderData.sprites.push( _object );
  3685. } else {
  3686. _object = getNextObjectInPool();
  3687. _object.object = object;
  3688. if ( object.renderDepth !== null ) {
  3689. _object.z = object.renderDepth;
  3690. } else {
  3691. _vector3.copy( object.matrixWorld.getPosition() );
  3692. _vector3.applyMatrix4( _viewProjectionMatrix );
  3693. _object.z = _vector3.z;
  3694. }
  3695. _renderData.objects.push( _object );
  3696. }
  3697. projectObject( object );
  3698. }
  3699. };
  3700. projectObject( root );
  3701. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  3702. return _renderData;
  3703. };
  3704. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  3705. var near = camera.near, far = camera.far, visible = false,
  3706. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  3707. geometry, vertices, vertex, vertexPositionScreen,
  3708. faces, face, faceVertexNormals, faceVertexUvs, uvs,
  3709. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  3710. _face3Count = 0;
  3711. _face4Count = 0;
  3712. _lineCount = 0;
  3713. _particleCount = 0;
  3714. _renderData.elements.length = 0;
  3715. scene.updateMatrixWorld();
  3716. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  3717. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  3718. _viewProjectionMatrix.multiply( camera.projectionMatrix, _viewMatrix );
  3719. _normalViewMatrix.getInverse( _viewMatrix );
  3720. _normalViewMatrix.transpose();
  3721. _frustum.setFromMatrix( _viewProjectionMatrix );
  3722. _renderData = projectGraph( scene, sortObjects );
  3723. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  3724. object = _renderData.objects[ o ].object;
  3725. _modelMatrix = object.matrixWorld;
  3726. _vertexCount = 0;
  3727. if ( object instanceof THREE.Mesh ) {
  3728. geometry = object.geometry;
  3729. vertices = geometry.vertices;
  3730. faces = geometry.faces;
  3731. faceVertexUvs = geometry.faceVertexUvs;
  3732. _normalMatrix.getInverse( _modelMatrix );
  3733. _normalMatrix.transpose();
  3734. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3735. objectMaterials = isFaceMaterial === true ? object.material : null;
  3736. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  3737. _vertex = getNextVertexInPool();
  3738. _vertex.positionWorld.copy( vertices[ v ] );
  3739. _vertex.positionWorld.applyMatrix4( _modelMatrix );
  3740. _vertex.positionScreen.copy( _vertex.positionWorld );
  3741. _vertex.positionScreen.applyMatrix4( _viewProjectionMatrix );
  3742. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  3743. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  3744. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  3745. }
  3746. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  3747. face = faces[ f ];
  3748. var material = isFaceMaterial === true
  3749. ? objectMaterials.materials[ face.materialIndex ]
  3750. : object.material;
  3751. if ( material === undefined ) continue;
  3752. var side = material.side;
  3753. if ( face instanceof THREE.Face3 ) {
  3754. v1 = _vertexPool[ face.a ];
  3755. v2 = _vertexPool[ face.b ];
  3756. v3 = _vertexPool[ face.c ];
  3757. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  3758. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3759. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  3760. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3761. _face = getNextFace3InPool();
  3762. _face.v1.copy( v1 );
  3763. _face.v2.copy( v2 );
  3764. _face.v3.copy( v3 );
  3765. } else {
  3766. continue;
  3767. }
  3768. } else {
  3769. continue;
  3770. }
  3771. } else if ( face instanceof THREE.Face4 ) {
  3772. v1 = _vertexPool[ face.a ];
  3773. v2 = _vertexPool[ face.b ];
  3774. v3 = _vertexPool[ face.c ];
  3775. v4 = _vertexPool[ face.d ];
  3776. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  3777. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3778. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  3779. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  3780. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  3781. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3782. _face = getNextFace4InPool();
  3783. _face.v1.copy( v1 );
  3784. _face.v2.copy( v2 );
  3785. _face.v3.copy( v3 );
  3786. _face.v4.copy( v4 );
  3787. } else {
  3788. continue;
  3789. }
  3790. } else {
  3791. continue;
  3792. }
  3793. }
  3794. _face.normalModel.copy( face.normal );
  3795. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  3796. _face.normalModel.negate();
  3797. }
  3798. _face.normalModel.applyMatrix3( _normalMatrix );
  3799. _face.normalModel.normalize();
  3800. _face.normalModelView.copy( _face.normalModel );
  3801. _face.normalModelView.applyMatrix3( _normalViewMatrix );
  3802. _face.centroidModel.copy( face.centroid );
  3803. _face.centroidModel.applyMatrix4( _modelMatrix );
  3804. faceVertexNormals = face.vertexNormals;
  3805. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  3806. var normalModel = _face.vertexNormalsModel[ n ];
  3807. normalModel.copy( faceVertexNormals[ n ] );
  3808. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  3809. normalModel.negate();
  3810. }
  3811. normalModel.applyMatrix3( _normalMatrix );
  3812. normalModel.normalize();
  3813. var normalModelView = _face.vertexNormalsModelView[ n ];
  3814. normalModelView.copy( normalModel );
  3815. normalModelView.applyMatrix3( _normalViewMatrix );
  3816. }
  3817. _face.vertexNormalsLength = faceVertexNormals.length;
  3818. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  3819. uvs = faceVertexUvs[ c ][ f ];
  3820. if ( uvs === undefined ) continue;
  3821. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  3822. _face.uvs[ c ][ u ] = uvs[ u ];
  3823. }
  3824. }
  3825. _face.color = face.color;
  3826. _face.material = material;
  3827. _centroid.copy( _face.centroidModel )
  3828. _centroid.applyMatrix4( _viewProjectionMatrix );
  3829. _face.z = _centroid.z;
  3830. _renderData.elements.push( _face );
  3831. }
  3832. } else if ( object instanceof THREE.Line ) {
  3833. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, _modelMatrix );
  3834. vertices = object.geometry.vertices;
  3835. v1 = getNextVertexInPool();
  3836. v1.positionScreen.copy( vertices[ 0 ] );
  3837. v1.positionScreen.applyMatrix4( _modelViewProjectionMatrix );
  3838. // Handle LineStrip and LinePieces
  3839. var step = object.type === THREE.LinePieces ? 2 : 1;
  3840. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  3841. v1 = getNextVertexInPool();
  3842. v1.positionScreen.copy( vertices[ v ] );
  3843. v1.positionScreen.applyMatrix4( _modelViewProjectionMatrix );
  3844. if ( ( v + 1 ) % step > 0 ) continue;
  3845. v2 = _vertexPool[ _vertexCount - 2 ];
  3846. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  3847. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  3848. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  3849. // Perform the perspective divide
  3850. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  3851. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  3852. _line = getNextLineInPool();
  3853. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  3854. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  3855. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  3856. _line.material = object.material;
  3857. _renderData.elements.push( _line );
  3858. }
  3859. }
  3860. }
  3861. }
  3862. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  3863. object = _renderData.sprites[ o ].object;
  3864. _modelMatrix = object.matrixWorld;
  3865. if ( object instanceof THREE.Particle ) {
  3866. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  3867. _vector4.applyMatrix4( _viewProjectionMatrix );
  3868. _vector4.z /= _vector4.w;
  3869. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  3870. _particle = getNextParticleInPool();
  3871. _particle.object = object;
  3872. _particle.x = _vector4.x / _vector4.w;
  3873. _particle.y = _vector4.y / _vector4.w;
  3874. _particle.z = _vector4.z;
  3875. _particle.rotation = object.rotation.z;
  3876. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  3877. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  3878. _particle.material = object.material;
  3879. _renderData.elements.push( _particle );
  3880. }
  3881. }
  3882. }
  3883. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  3884. return _renderData;
  3885. };
  3886. // Pools
  3887. function getNextObjectInPool() {
  3888. if ( _objectCount === _objectPoolLength ) {
  3889. var object = new THREE.RenderableObject();
  3890. _objectPool.push( object );
  3891. _objectPoolLength ++;
  3892. _objectCount ++;
  3893. return object;
  3894. }
  3895. return _objectPool[ _objectCount ++ ];
  3896. }
  3897. function getNextVertexInPool() {
  3898. if ( _vertexCount === _vertexPoolLength ) {
  3899. var vertex = new THREE.RenderableVertex();
  3900. _vertexPool.push( vertex );
  3901. _vertexPoolLength ++;
  3902. _vertexCount ++;
  3903. return vertex;
  3904. }
  3905. return _vertexPool[ _vertexCount ++ ];
  3906. }
  3907. function getNextFace3InPool() {
  3908. if ( _face3Count === _face3PoolLength ) {
  3909. var face = new THREE.RenderableFace3();
  3910. _face3Pool.push( face );
  3911. _face3PoolLength ++;
  3912. _face3Count ++;
  3913. return face;
  3914. }
  3915. return _face3Pool[ _face3Count ++ ];
  3916. }
  3917. function getNextFace4InPool() {
  3918. if ( _face4Count === _face4PoolLength ) {
  3919. var face = new THREE.RenderableFace4();
  3920. _face4Pool.push( face );
  3921. _face4PoolLength ++;
  3922. _face4Count ++;
  3923. return face;
  3924. }
  3925. return _face4Pool[ _face4Count ++ ];
  3926. }
  3927. function getNextLineInPool() {
  3928. if ( _lineCount === _linePoolLength ) {
  3929. var line = new THREE.RenderableLine();
  3930. _linePool.push( line );
  3931. _linePoolLength ++;
  3932. _lineCount ++
  3933. return line;
  3934. }
  3935. return _linePool[ _lineCount ++ ];
  3936. }
  3937. function getNextParticleInPool() {
  3938. if ( _particleCount === _particlePoolLength ) {
  3939. var particle = new THREE.RenderableParticle();
  3940. _particlePool.push( particle );
  3941. _particlePoolLength ++;
  3942. _particleCount ++
  3943. return particle;
  3944. }
  3945. return _particlePool[ _particleCount ++ ];
  3946. }
  3947. //
  3948. function painterSort( a, b ) {
  3949. return b.z - a.z;
  3950. }
  3951. function clipLine( s1, s2 ) {
  3952. var alpha1 = 0, alpha2 = 1,
  3953. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  3954. // Z = -1 and Z = +1, respectively.
  3955. bc1near = s1.z + s1.w,
  3956. bc2near = s2.z + s2.w,
  3957. bc1far = - s1.z + s1.w,
  3958. bc2far = - s2.z + s2.w;
  3959. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  3960. // Both vertices lie entirely within all clip planes.
  3961. return true;
  3962. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  3963. // Both vertices lie entirely outside one of the clip planes.
  3964. return false;
  3965. } else {
  3966. // The line segment spans at least one clip plane.
  3967. if ( bc1near < 0 ) {
  3968. // v1 lies outside the near plane, v2 inside
  3969. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  3970. } else if ( bc2near < 0 ) {
  3971. // v2 lies outside the near plane, v1 inside
  3972. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  3973. }
  3974. if ( bc1far < 0 ) {
  3975. // v1 lies outside the far plane, v2 inside
  3976. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  3977. } else if ( bc2far < 0 ) {
  3978. // v2 lies outside the far plane, v2 inside
  3979. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  3980. }
  3981. if ( alpha2 < alpha1 ) {
  3982. // The line segment spans two boundaries, but is outside both of them.
  3983. // (This can't happen when we're only clipping against just near/far but good
  3984. // to leave the check here for future usage if other clip planes are added.)
  3985. return false;
  3986. } else {
  3987. // Update the s1 and s2 vertices to match the clipped line segment.
  3988. s1.lerpSelf( s2, alpha1 );
  3989. s2.lerpSelf( s1, 1 - alpha2 );
  3990. return true;
  3991. }
  3992. }
  3993. }
  3994. };
  3995. /**
  3996. * @author mrdoob / http://mrdoob.com/
  3997. * @author alteredq / http://alteredqualia.com/
  3998. */
  3999. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4000. this.a = a;
  4001. this.b = b;
  4002. this.c = c;
  4003. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4004. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4005. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4006. this.vertexColors = color instanceof Array ? color : [];
  4007. this.vertexTangents = [];
  4008. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4009. this.centroid = new THREE.Vector3();
  4010. };
  4011. THREE.Face3.prototype = {
  4012. constructor: THREE.Face3,
  4013. clone: function () {
  4014. var face = new THREE.Face3( this.a, this.b, this.c );
  4015. face.normal.copy( this.normal );
  4016. face.color.copy( this.color );
  4017. face.centroid.copy( this.centroid );
  4018. face.materialIndex = this.materialIndex;
  4019. var i, il;
  4020. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4021. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4022. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4023. return face;
  4024. }
  4025. };
  4026. /**
  4027. * @author mrdoob / http://mrdoob.com/
  4028. * @author alteredq / http://alteredqualia.com/
  4029. */
  4030. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4031. this.a = a;
  4032. this.b = b;
  4033. this.c = c;
  4034. this.d = d;
  4035. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4036. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4037. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4038. this.vertexColors = color instanceof Array ? color : [];
  4039. this.vertexTangents = [];
  4040. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4041. this.centroid = new THREE.Vector3();
  4042. };
  4043. THREE.Face4.prototype = {
  4044. constructor: THREE.Face4,
  4045. clone: function () {
  4046. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4047. face.normal.copy( this.normal );
  4048. face.color.copy( this.color );
  4049. face.centroid.copy( this.centroid );
  4050. face.materialIndex = this.materialIndex;
  4051. var i, il;
  4052. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4053. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4054. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4055. return face;
  4056. }
  4057. };
  4058. /**
  4059. * @author mrdoob / http://mrdoob.com/
  4060. * @author kile / http://kile.stravaganza.org/
  4061. * @author alteredq / http://alteredqualia.com/
  4062. * @author mikael emtinger / http://gomo.se/
  4063. * @author zz85 / http://www.lab4games.net/zz85/blog
  4064. * @author bhouston / http://exocortex.com
  4065. */
  4066. THREE.Geometry = function () {
  4067. THREE.EventDispatcher.call( this );
  4068. this.id = THREE.GeometryIdCount ++;
  4069. this.name = '';
  4070. this.vertices = [];
  4071. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4072. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4073. this.faces = [];
  4074. this.faceUvs = [[]];
  4075. this.faceVertexUvs = [[]];
  4076. this.morphTargets = [];
  4077. this.morphColors = [];
  4078. this.morphNormals = [];
  4079. this.skinWeights = [];
  4080. this.skinIndices = [];
  4081. this.lineDistances = [];
  4082. this.boundingBox = null;
  4083. this.boundingSphere = null;
  4084. this.hasTangents = false;
  4085. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4086. // update flags
  4087. this.verticesNeedUpdate = false;
  4088. this.elementsNeedUpdate = false;
  4089. this.uvsNeedUpdate = false;
  4090. this.normalsNeedUpdate = false;
  4091. this.tangentsNeedUpdate = false;
  4092. this.colorsNeedUpdate = false;
  4093. this.lineDistancesNeedUpdate = false;
  4094. this.buffersNeedUpdate = false;
  4095. };
  4096. THREE.Geometry.prototype = {
  4097. constructor: THREE.Geometry,
  4098. applyMatrix: function ( matrix ) {
  4099. var normalMatrix = new THREE.Matrix3().getInverse( matrix ).transpose();
  4100. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4101. var vertex = this.vertices[ i ];
  4102. vertex.applyMatrix4( matrix );
  4103. }
  4104. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4105. var face = this.faces[ i ];
  4106. face.normal.applyMatrix3( normalMatrix ).normalize();
  4107. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4108. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4109. }
  4110. face.centroid.applyMatrix4( matrix );
  4111. }
  4112. },
  4113. computeCentroids: function () {
  4114. var f, fl, face;
  4115. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4116. face = this.faces[ f ];
  4117. face.centroid.set( 0, 0, 0 );
  4118. if ( face instanceof THREE.Face3 ) {
  4119. face.centroid.addSelf( this.vertices[ face.a ] );
  4120. face.centroid.addSelf( this.vertices[ face.b ] );
  4121. face.centroid.addSelf( this.vertices[ face.c ] );
  4122. face.centroid.divideScalar( 3 );
  4123. } else if ( face instanceof THREE.Face4 ) {
  4124. face.centroid.addSelf( this.vertices[ face.a ] );
  4125. face.centroid.addSelf( this.vertices[ face.b ] );
  4126. face.centroid.addSelf( this.vertices[ face.c ] );
  4127. face.centroid.addSelf( this.vertices[ face.d ] );
  4128. face.centroid.divideScalar( 4 );
  4129. }
  4130. }
  4131. },
  4132. computeFaceNormals: function () {
  4133. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  4134. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4135. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4136. face = this.faces[ f ];
  4137. vA = this.vertices[ face.a ];
  4138. vB = this.vertices[ face.b ];
  4139. vC = this.vertices[ face.c ];
  4140. cb.sub( vC, vB );
  4141. ab.sub( vA, vB );
  4142. cb.crossSelf( ab );
  4143. cb.normalize();
  4144. face.normal.copy( cb );
  4145. }
  4146. },
  4147. computeVertexNormals: function ( areaWeighted ) {
  4148. var v, vl, f, fl, face, vertices;
  4149. // create internal buffers for reuse when calling this method repeatedly
  4150. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4151. if ( this.__tmpVertices === undefined ) {
  4152. this.__tmpVertices = new Array( this.vertices.length );
  4153. vertices = this.__tmpVertices;
  4154. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4155. vertices[ v ] = new THREE.Vector3();
  4156. }
  4157. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4158. face = this.faces[ f ];
  4159. if ( face instanceof THREE.Face3 ) {
  4160. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4161. } else if ( face instanceof THREE.Face4 ) {
  4162. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4163. }
  4164. }
  4165. } else {
  4166. vertices = this.__tmpVertices;
  4167. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4168. vertices[ v ].set( 0, 0, 0 );
  4169. }
  4170. }
  4171. if ( areaWeighted ) {
  4172. // vertex normals weighted by triangle areas
  4173. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4174. var vA, vB, vC, vD;
  4175. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4176. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4177. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4178. face = this.faces[ f ];
  4179. if ( face instanceof THREE.Face3 ) {
  4180. vA = this.vertices[ face.a ];
  4181. vB = this.vertices[ face.b ];
  4182. vC = this.vertices[ face.c ];
  4183. cb.sub( vC, vB );
  4184. ab.sub( vA, vB );
  4185. cb.crossSelf( ab );
  4186. vertices[ face.a ].addSelf( cb );
  4187. vertices[ face.b ].addSelf( cb );
  4188. vertices[ face.c ].addSelf( cb );
  4189. } else if ( face instanceof THREE.Face4 ) {
  4190. vA = this.vertices[ face.a ];
  4191. vB = this.vertices[ face.b ];
  4192. vC = this.vertices[ face.c ];
  4193. vD = this.vertices[ face.d ];
  4194. // abd
  4195. db.sub( vD, vB );
  4196. ab.sub( vA, vB );
  4197. db.crossSelf( ab );
  4198. vertices[ face.a ].addSelf( db );
  4199. vertices[ face.b ].addSelf( db );
  4200. vertices[ face.d ].addSelf( db );
  4201. // bcd
  4202. dc.sub( vD, vC );
  4203. bc.sub( vB, vC );
  4204. dc.crossSelf( bc );
  4205. vertices[ face.b ].addSelf( dc );
  4206. vertices[ face.c ].addSelf( dc );
  4207. vertices[ face.d ].addSelf( dc );
  4208. }
  4209. }
  4210. } else {
  4211. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4212. face = this.faces[ f ];
  4213. if ( face instanceof THREE.Face3 ) {
  4214. vertices[ face.a ].addSelf( face.normal );
  4215. vertices[ face.b ].addSelf( face.normal );
  4216. vertices[ face.c ].addSelf( face.normal );
  4217. } else if ( face instanceof THREE.Face4 ) {
  4218. vertices[ face.a ].addSelf( face.normal );
  4219. vertices[ face.b ].addSelf( face.normal );
  4220. vertices[ face.c ].addSelf( face.normal );
  4221. vertices[ face.d ].addSelf( face.normal );
  4222. }
  4223. }
  4224. }
  4225. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4226. vertices[ v ].normalize();
  4227. }
  4228. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4229. face = this.faces[ f ];
  4230. if ( face instanceof THREE.Face3 ) {
  4231. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4232. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4233. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4234. } else if ( face instanceof THREE.Face4 ) {
  4235. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4236. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4237. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4238. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4239. }
  4240. }
  4241. },
  4242. computeMorphNormals: function () {
  4243. var i, il, f, fl, face;
  4244. // save original normals
  4245. // - create temp variables on first access
  4246. // otherwise just copy (for faster repeated calls)
  4247. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4248. face = this.faces[ f ];
  4249. if ( ! face.__originalFaceNormal ) {
  4250. face.__originalFaceNormal = face.normal.clone();
  4251. } else {
  4252. face.__originalFaceNormal.copy( face.normal );
  4253. }
  4254. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4255. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4256. if ( ! face.__originalVertexNormals[ i ] ) {
  4257. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4258. } else {
  4259. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4260. }
  4261. }
  4262. }
  4263. // use temp geometry to compute face and vertex normals for each morph
  4264. var tmpGeo = new THREE.Geometry();
  4265. tmpGeo.faces = this.faces;
  4266. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4267. // create on first access
  4268. if ( ! this.morphNormals[ i ] ) {
  4269. this.morphNormals[ i ] = {};
  4270. this.morphNormals[ i ].faceNormals = [];
  4271. this.morphNormals[ i ].vertexNormals = [];
  4272. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4273. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4274. var faceNormal, vertexNormals;
  4275. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4276. face = this.faces[ f ];
  4277. faceNormal = new THREE.Vector3();
  4278. if ( face instanceof THREE.Face3 ) {
  4279. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4280. } else {
  4281. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4282. }
  4283. dstNormalsFace.push( faceNormal );
  4284. dstNormalsVertex.push( vertexNormals );
  4285. }
  4286. }
  4287. var morphNormals = this.morphNormals[ i ];
  4288. // set vertices to morph target
  4289. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4290. // compute morph normals
  4291. tmpGeo.computeFaceNormals();
  4292. tmpGeo.computeVertexNormals();
  4293. // store morph normals
  4294. var faceNormal, vertexNormals;
  4295. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4296. face = this.faces[ f ];
  4297. faceNormal = morphNormals.faceNormals[ f ];
  4298. vertexNormals = morphNormals.vertexNormals[ f ];
  4299. faceNormal.copy( face.normal );
  4300. if ( face instanceof THREE.Face3 ) {
  4301. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4302. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4303. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4304. } else {
  4305. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4306. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4307. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4308. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4309. }
  4310. }
  4311. }
  4312. // restore original normals
  4313. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4314. face = this.faces[ f ];
  4315. face.normal = face.__originalFaceNormal;
  4316. face.vertexNormals = face.__originalVertexNormals;
  4317. }
  4318. },
  4319. computeTangents: function () {
  4320. // based on http://www.terathon.com/code/tangent.html
  4321. // tangents go to vertices
  4322. var f, fl, v, vl, i, il, vertexIndex,
  4323. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4324. x1, x2, y1, y2, z1, z2,
  4325. s1, s2, t1, t2, r, t, test,
  4326. tan1 = [], tan2 = [],
  4327. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4328. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4329. n = new THREE.Vector3(), w;
  4330. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4331. tan1[ v ] = new THREE.Vector3();
  4332. tan2[ v ] = new THREE.Vector3();
  4333. }
  4334. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4335. vA = context.vertices[ a ];
  4336. vB = context.vertices[ b ];
  4337. vC = context.vertices[ c ];
  4338. uvA = uv[ ua ];
  4339. uvB = uv[ ub ];
  4340. uvC = uv[ uc ];
  4341. x1 = vB.x - vA.x;
  4342. x2 = vC.x - vA.x;
  4343. y1 = vB.y - vA.y;
  4344. y2 = vC.y - vA.y;
  4345. z1 = vB.z - vA.z;
  4346. z2 = vC.z - vA.z;
  4347. s1 = uvB.x - uvA.x;
  4348. s2 = uvC.x - uvA.x;
  4349. t1 = uvB.y - uvA.y;
  4350. t2 = uvC.y - uvA.y;
  4351. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4352. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4353. ( t2 * y1 - t1 * y2 ) * r,
  4354. ( t2 * z1 - t1 * z2 ) * r );
  4355. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4356. ( s1 * y2 - s2 * y1 ) * r,
  4357. ( s1 * z2 - s2 * z1 ) * r );
  4358. tan1[ a ].addSelf( sdir );
  4359. tan1[ b ].addSelf( sdir );
  4360. tan1[ c ].addSelf( sdir );
  4361. tan2[ a ].addSelf( tdir );
  4362. tan2[ b ].addSelf( tdir );
  4363. tan2[ c ].addSelf( tdir );
  4364. }
  4365. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4366. face = this.faces[ f ];
  4367. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4368. if ( face instanceof THREE.Face3 ) {
  4369. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4370. } else if ( face instanceof THREE.Face4 ) {
  4371. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4372. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4373. }
  4374. }
  4375. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4376. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4377. face = this.faces[ f ];
  4378. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4379. n.copy( face.vertexNormals[ i ] );
  4380. vertexIndex = face[ faceIndex[ i ] ];
  4381. t = tan1[ vertexIndex ];
  4382. // Gram-Schmidt orthogonalize
  4383. tmp.copy( t );
  4384. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4385. // Calculate handedness
  4386. tmp2.cross( face.vertexNormals[ i ], t );
  4387. test = tmp2.dot( tan2[ vertexIndex ] );
  4388. w = (test < 0.0) ? -1.0 : 1.0;
  4389. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4390. }
  4391. }
  4392. this.hasTangents = true;
  4393. },
  4394. computeLineDistances: function ( ) {
  4395. var d = 0;
  4396. var vertices = this.vertices;
  4397. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4398. if ( i > 0 ) {
  4399. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4400. }
  4401. this.lineDistances[ i ] = d;
  4402. }
  4403. },
  4404. computeBoundingBox: function () {
  4405. if ( this.boundingBox === null ) {
  4406. this.boundingBox = new THREE.Box3();
  4407. }
  4408. this.boundingBox.setFromPoints( this.vertices );
  4409. },
  4410. computeBoundingSphere: function () {
  4411. if ( this.boundingSphere === null ) {
  4412. this.boundingSphere = new THREE.Sphere();
  4413. }
  4414. this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
  4415. },
  4416. /*
  4417. * Checks for duplicate vertices with hashmap.
  4418. * Duplicated vertices are removed
  4419. * and faces' vertices are updated.
  4420. */
  4421. mergeVertices: function () {
  4422. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4423. var unique = [], changes = [];
  4424. var v, key;
  4425. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4426. var precision = Math.pow( 10, precisionPoints );
  4427. var i,il, face;
  4428. var abcd = 'abcd', o, k, j, jl, u;
  4429. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4430. v = this.vertices[ i ];
  4431. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  4432. if ( verticesMap[ key ] === undefined ) {
  4433. verticesMap[ key ] = i;
  4434. unique.push( this.vertices[ i ] );
  4435. changes[ i ] = unique.length - 1;
  4436. } else {
  4437. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4438. changes[ i ] = changes[ verticesMap[ key ] ];
  4439. }
  4440. };
  4441. // Start to patch face indices
  4442. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4443. face = this.faces[ i ];
  4444. if ( face instanceof THREE.Face3 ) {
  4445. face.a = changes[ face.a ];
  4446. face.b = changes[ face.b ];
  4447. face.c = changes[ face.c ];
  4448. } else if ( face instanceof THREE.Face4 ) {
  4449. face.a = changes[ face.a ];
  4450. face.b = changes[ face.b ];
  4451. face.c = changes[ face.c ];
  4452. face.d = changes[ face.d ];
  4453. // check dups in (a, b, c, d) and convert to -> face3
  4454. o = [ face.a, face.b, face.c, face.d ];
  4455. for ( k = 3; k > 0; k -- ) {
  4456. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  4457. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  4458. o.splice( k, 1 );
  4459. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  4460. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4461. u = this.faceVertexUvs[ j ][ i ];
  4462. if ( u ) u.splice( k, 1 );
  4463. }
  4464. this.faces[ i ].vertexColors = face.vertexColors;
  4465. break;
  4466. }
  4467. }
  4468. }
  4469. }
  4470. // Use unique set of vertices
  4471. var diff = this.vertices.length - unique.length;
  4472. this.vertices = unique;
  4473. return diff;
  4474. },
  4475. clone: function () {
  4476. var geometry = new THREE.Geometry();
  4477. var vertices = this.vertices;
  4478. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4479. geometry.vertices.push( vertices[ i ].clone() );
  4480. }
  4481. var faces = this.faces;
  4482. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4483. geometry.faces.push( faces[ i ].clone() );
  4484. }
  4485. var uvs = this.faceVertexUvs[ 0 ];
  4486. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4487. var uv = uvs[ i ], uvCopy = [];
  4488. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4489. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  4490. }
  4491. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4492. }
  4493. return geometry;
  4494. },
  4495. dispose: function () {
  4496. this.dispatchEvent( { type: 'dispose' } );
  4497. }
  4498. };
  4499. THREE.GeometryIdCount = 0;
  4500. /**
  4501. * @author alteredq / http://alteredqualia.com/
  4502. */
  4503. THREE.BufferGeometry = function () {
  4504. THREE.EventDispatcher.call( this );
  4505. this.id = THREE.GeometryIdCount ++;
  4506. // attributes
  4507. this.attributes = {};
  4508. // attributes typed arrays are kept only if dynamic flag is set
  4509. this.dynamic = false;
  4510. // offsets for chunks when using indexed elements
  4511. this.offsets = [];
  4512. // boundings
  4513. this.boundingBox = null;
  4514. this.boundingSphere = null;
  4515. this.hasTangents = false;
  4516. // for compatibility
  4517. this.morphTargets = [];
  4518. };
  4519. THREE.BufferGeometry.prototype = {
  4520. constructor : THREE.BufferGeometry,
  4521. applyMatrix: function ( matrix ) {
  4522. var positionArray;
  4523. var normalArray;
  4524. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  4525. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  4526. if ( positionArray !== undefined ) {
  4527. matrix.multiplyVector3Array( positionArray );
  4528. this.verticesNeedUpdate = true;
  4529. }
  4530. if ( normalArray !== undefined ) {
  4531. var normalMatrix = new THREE.Matrix3();
  4532. normalMatrix.getInverse( matrix ).transpose();
  4533. normalMatrix.multiplyVector3Array( normalArray );
  4534. this.normalizeNormals();
  4535. this.normalsNeedUpdate = true;
  4536. }
  4537. },
  4538. computeBoundingBox: function () {
  4539. if ( this.boundingBox === null ) {
  4540. this.boundingBox = new THREE.Box3();
  4541. }
  4542. var positions = this.attributes[ "position" ].array;
  4543. if ( positions ) {
  4544. var bb = this.boundingBox;
  4545. var x, y, z;
  4546. if( positions.length >= 3 ) {
  4547. bb.min.x = bb.max.x = positions[ 0 ];
  4548. bb.min.y = bb.max.y = positions[ 1 ];
  4549. bb.min.z = bb.max.z = positions[ 2 ];
  4550. }
  4551. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  4552. x = positions[ i ];
  4553. y = positions[ i + 1 ];
  4554. z = positions[ i + 2 ];
  4555. // bounding box
  4556. if ( x < bb.min.x ) {
  4557. bb.min.x = x;
  4558. } else if ( x > bb.max.x ) {
  4559. bb.max.x = x;
  4560. }
  4561. if ( y < bb.min.y ) {
  4562. bb.min.y = y;
  4563. } else if ( y > bb.max.y ) {
  4564. bb.max.y = y;
  4565. }
  4566. if ( z < bb.min.z ) {
  4567. bb.min.z = z;
  4568. } else if ( z > bb.max.z ) {
  4569. bb.max.z = z;
  4570. }
  4571. }
  4572. }
  4573. if ( positions === undefined || positions.length === 0 ) {
  4574. this.boundingBox.min.set( 0, 0, 0 );
  4575. this.boundingBox.max.set( 0, 0, 0 );
  4576. }
  4577. },
  4578. computeBoundingSphere: function () {
  4579. if ( this.boundingSphere === null ) {
  4580. this.boundingSphere = new THREE.Sphere();
  4581. }
  4582. var positions = this.attributes[ "position" ].array;
  4583. if ( positions ) {
  4584. var radiusSq, maxRadiusSq = 0;
  4585. var x, y, z;
  4586. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4587. x = positions[ i ];
  4588. y = positions[ i + 1 ];
  4589. z = positions[ i + 2 ];
  4590. radiusSq = x * x + y * y + z * z;
  4591. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  4592. }
  4593. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  4594. }
  4595. },
  4596. computeVertexNormals: function () {
  4597. if ( this.attributes[ "position" ] ) {
  4598. var i, il;
  4599. var j, jl;
  4600. var nVertexElements = this.attributes[ "position" ].array.length;
  4601. if ( this.attributes[ "normal" ] === undefined ) {
  4602. this.attributes[ "normal" ] = {
  4603. itemSize: 3,
  4604. array: new Float32Array( nVertexElements ),
  4605. numItems: nVertexElements
  4606. };
  4607. } else {
  4608. // reset existing normals to zero
  4609. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  4610. this.attributes[ "normal" ].array[ i ] = 0;
  4611. }
  4612. }
  4613. var positions = this.attributes[ "position" ].array;
  4614. var normals = this.attributes[ "normal" ].array;
  4615. var vA, vB, vC, x, y, z,
  4616. pA = new THREE.Vector3(),
  4617. pB = new THREE.Vector3(),
  4618. pC = new THREE.Vector3(),
  4619. cb = new THREE.Vector3(),
  4620. ab = new THREE.Vector3();
  4621. // indexed elements
  4622. if ( this.attributes[ "index" ] ) {
  4623. var indices = this.attributes[ "index" ].array;
  4624. var offsets = this.offsets;
  4625. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4626. var start = offsets[ j ].start;
  4627. var count = offsets[ j ].count;
  4628. var index = offsets[ j ].index;
  4629. for ( i = start, il = start + count; i < il; i += 3 ) {
  4630. vA = index + indices[ i ];
  4631. vB = index + indices[ i + 1 ];
  4632. vC = index + indices[ i + 2 ];
  4633. x = positions[ vA * 3 ];
  4634. y = positions[ vA * 3 + 1 ];
  4635. z = positions[ vA * 3 + 2 ];
  4636. pA.set( x, y, z );
  4637. x = positions[ vB * 3 ];
  4638. y = positions[ vB * 3 + 1 ];
  4639. z = positions[ vB * 3 + 2 ];
  4640. pB.set( x, y, z );
  4641. x = positions[ vC * 3 ];
  4642. y = positions[ vC * 3 + 1 ];
  4643. z = positions[ vC * 3 + 2 ];
  4644. pC.set( x, y, z );
  4645. cb.sub( pC, pB );
  4646. ab.sub( pA, pB );
  4647. cb.crossSelf( ab );
  4648. normals[ vA * 3 ] += cb.x;
  4649. normals[ vA * 3 + 1 ] += cb.y;
  4650. normals[ vA * 3 + 2 ] += cb.z;
  4651. normals[ vB * 3 ] += cb.x;
  4652. normals[ vB * 3 + 1 ] += cb.y;
  4653. normals[ vB * 3 + 2 ] += cb.z;
  4654. normals[ vC * 3 ] += cb.x;
  4655. normals[ vC * 3 + 1 ] += cb.y;
  4656. normals[ vC * 3 + 2 ] += cb.z;
  4657. }
  4658. }
  4659. // non-indexed elements (unconnected triangle soup)
  4660. } else {
  4661. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  4662. x = positions[ i ];
  4663. y = positions[ i + 1 ];
  4664. z = positions[ i + 2 ];
  4665. pA.set( x, y, z );
  4666. x = positions[ i + 3 ];
  4667. y = positions[ i + 4 ];
  4668. z = positions[ i + 5 ];
  4669. pB.set( x, y, z );
  4670. x = positions[ i + 6 ];
  4671. y = positions[ i + 7 ];
  4672. z = positions[ i + 8 ];
  4673. pC.set( x, y, z );
  4674. cb.sub( pC, pB );
  4675. ab.sub( pA, pB );
  4676. cb.crossSelf( ab );
  4677. normals[ i ] = cb.x;
  4678. normals[ i + 1 ] = cb.y;
  4679. normals[ i + 2 ] = cb.z;
  4680. normals[ i + 3 ] = cb.x;
  4681. normals[ i + 4 ] = cb.y;
  4682. normals[ i + 5 ] = cb.z;
  4683. normals[ i + 6 ] = cb.x;
  4684. normals[ i + 7 ] = cb.y;
  4685. normals[ i + 8 ] = cb.z;
  4686. }
  4687. }
  4688. this.normalizeNormals();
  4689. this.normalsNeedUpdate = true;
  4690. }
  4691. },
  4692. normalizeNormals: function () {
  4693. var normals = this.attributes[ "normal" ].array;
  4694. var x, y, z, n;
  4695. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  4696. x = normals[ i ];
  4697. y = normals[ i + 1 ];
  4698. z = normals[ i + 2 ];
  4699. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  4700. normals[ i ] *= n;
  4701. normals[ i + 1 ] *= n;
  4702. normals[ i + 2 ] *= n;
  4703. }
  4704. },
  4705. computeTangents: function () {
  4706. // based on http://www.terathon.com/code/tangent.html
  4707. // (per vertex tangents)
  4708. if ( this.attributes[ "index" ] === undefined ||
  4709. this.attributes[ "position" ] === undefined ||
  4710. this.attributes[ "normal" ] === undefined ||
  4711. this.attributes[ "uv" ] === undefined ) {
  4712. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  4713. return;
  4714. }
  4715. var indices = this.attributes[ "index" ].array;
  4716. var positions = this.attributes[ "position" ].array;
  4717. var normals = this.attributes[ "normal" ].array;
  4718. var uvs = this.attributes[ "uv" ].array;
  4719. var nVertices = positions.length / 3;
  4720. if ( this.attributes[ "tangent" ] === undefined ) {
  4721. var nTangentElements = 4 * nVertices;
  4722. this.attributes[ "tangent" ] = {
  4723. itemSize: 4,
  4724. array: new Float32Array( nTangentElements ),
  4725. numItems: nTangentElements
  4726. };
  4727. }
  4728. var tangents = this.attributes[ "tangent" ].array;
  4729. var tan1 = [], tan2 = [];
  4730. for ( var k = 0; k < nVertices; k ++ ) {
  4731. tan1[ k ] = new THREE.Vector3();
  4732. tan2[ k ] = new THREE.Vector3();
  4733. }
  4734. var xA, yA, zA,
  4735. xB, yB, zB,
  4736. xC, yC, zC,
  4737. uA, vA,
  4738. uB, vB,
  4739. uC, vC,
  4740. x1, x2, y1, y2, z1, z2,
  4741. s1, s2, t1, t2, r;
  4742. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  4743. function handleTriangle( a, b, c ) {
  4744. xA = positions[ a * 3 ];
  4745. yA = positions[ a * 3 + 1 ];
  4746. zA = positions[ a * 3 + 2 ];
  4747. xB = positions[ b * 3 ];
  4748. yB = positions[ b * 3 + 1 ];
  4749. zB = positions[ b * 3 + 2 ];
  4750. xC = positions[ c * 3 ];
  4751. yC = positions[ c * 3 + 1 ];
  4752. zC = positions[ c * 3 + 2 ];
  4753. uA = uvs[ a * 2 ];
  4754. vA = uvs[ a * 2 + 1 ];
  4755. uB = uvs[ b * 2 ];
  4756. vB = uvs[ b * 2 + 1 ];
  4757. uC = uvs[ c * 2 ];
  4758. vC = uvs[ c * 2 + 1 ];
  4759. x1 = xB - xA;
  4760. x2 = xC - xA;
  4761. y1 = yB - yA;
  4762. y2 = yC - yA;
  4763. z1 = zB - zA;
  4764. z2 = zC - zA;
  4765. s1 = uB - uA;
  4766. s2 = uC - uA;
  4767. t1 = vB - vA;
  4768. t2 = vC - vA;
  4769. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4770. sdir.set(
  4771. ( t2 * x1 - t1 * x2 ) * r,
  4772. ( t2 * y1 - t1 * y2 ) * r,
  4773. ( t2 * z1 - t1 * z2 ) * r
  4774. );
  4775. tdir.set(
  4776. ( s1 * x2 - s2 * x1 ) * r,
  4777. ( s1 * y2 - s2 * y1 ) * r,
  4778. ( s1 * z2 - s2 * z1 ) * r
  4779. );
  4780. tan1[ a ].addSelf( sdir );
  4781. tan1[ b ].addSelf( sdir );
  4782. tan1[ c ].addSelf( sdir );
  4783. tan2[ a ].addSelf( tdir );
  4784. tan2[ b ].addSelf( tdir );
  4785. tan2[ c ].addSelf( tdir );
  4786. }
  4787. var i, il;
  4788. var j, jl;
  4789. var iA, iB, iC;
  4790. var offsets = this.offsets;
  4791. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4792. var start = offsets[ j ].start;
  4793. var count = offsets[ j ].count;
  4794. var index = offsets[ j ].index;
  4795. for ( i = start, il = start + count; i < il; i += 3 ) {
  4796. iA = index + indices[ i ];
  4797. iB = index + indices[ i + 1 ];
  4798. iC = index + indices[ i + 2 ];
  4799. handleTriangle( iA, iB, iC );
  4800. }
  4801. }
  4802. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  4803. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  4804. var w, t, test;
  4805. var nx, ny, nz;
  4806. function handleVertex( v ) {
  4807. n.x = normals[ v * 3 ];
  4808. n.y = normals[ v * 3 + 1 ];
  4809. n.z = normals[ v * 3 + 2 ];
  4810. n2.copy( n );
  4811. t = tan1[ v ];
  4812. // Gram-Schmidt orthogonalize
  4813. tmp.copy( t );
  4814. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4815. // Calculate handedness
  4816. tmp2.cross( n2, t );
  4817. test = tmp2.dot( tan2[ v ] );
  4818. w = ( test < 0.0 ) ? -1.0 : 1.0;
  4819. tangents[ v * 4 ] = tmp.x;
  4820. tangents[ v * 4 + 1 ] = tmp.y;
  4821. tangents[ v * 4 + 2 ] = tmp.z;
  4822. tangents[ v * 4 + 3 ] = w;
  4823. }
  4824. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4825. var start = offsets[ j ].start;
  4826. var count = offsets[ j ].count;
  4827. var index = offsets[ j ].index;
  4828. for ( i = start, il = start + count; i < il; i += 3 ) {
  4829. iA = index + indices[ i ];
  4830. iB = index + indices[ i + 1 ];
  4831. iC = index + indices[ i + 2 ];
  4832. handleVertex( iA );
  4833. handleVertex( iB );
  4834. handleVertex( iC );
  4835. }
  4836. }
  4837. this.hasTangents = true;
  4838. this.tangentsNeedUpdate = true;
  4839. },
  4840. dispose: function () {
  4841. this.dispatchEvent( { type: 'dispose' } );
  4842. }
  4843. };
  4844. /**
  4845. * @author mrdoob / http://mrdoob.com/
  4846. * @author mikael emtinger / http://gomo.se/
  4847. */
  4848. THREE.Camera = function () {
  4849. THREE.Object3D.call( this );
  4850. this.matrixWorldInverse = new THREE.Matrix4();
  4851. this.projectionMatrix = new THREE.Matrix4();
  4852. this.projectionMatrixInverse = new THREE.Matrix4();
  4853. };
  4854. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  4855. THREE.Camera.prototype.lookAt = function ( vector ) {
  4856. // TODO: Add hierarchy support.
  4857. this.matrix.lookAt( this.position, vector, this.up );
  4858. if ( this.rotationAutoUpdate === true ) {
  4859. if ( this.useQuaternion === false ) {
  4860. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  4861. } else {
  4862. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  4863. }
  4864. }
  4865. };
  4866. /**
  4867. * @author alteredq / http://alteredqualia.com/
  4868. */
  4869. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  4870. THREE.Camera.call( this );
  4871. this.left = left;
  4872. this.right = right;
  4873. this.top = top;
  4874. this.bottom = bottom;
  4875. this.near = ( near !== undefined ) ? near : 0.1;
  4876. this.far = ( far !== undefined ) ? far : 2000;
  4877. this.updateProjectionMatrix();
  4878. };
  4879. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  4880. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  4881. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  4882. };
  4883. /**
  4884. * @author mrdoob / http://mrdoob.com/
  4885. * @author greggman / http://games.greggman.com/
  4886. * @author zz85 / http://www.lab4games.net/zz85/blog
  4887. */
  4888. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  4889. THREE.Camera.call( this );
  4890. this.fov = fov !== undefined ? fov : 50;
  4891. this.aspect = aspect !== undefined ? aspect : 1;
  4892. this.near = near !== undefined ? near : 0.1;
  4893. this.far = far !== undefined ? far : 2000;
  4894. this.updateProjectionMatrix();
  4895. };
  4896. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  4897. /**
  4898. * Uses Focal Length (in mm) to estimate and set FOV
  4899. * 35mm (fullframe) camera is used if frame size is not specified;
  4900. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  4901. */
  4902. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  4903. if ( frameHeight === undefined ) frameHeight = 24;
  4904. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  4905. this.updateProjectionMatrix();
  4906. }
  4907. /**
  4908. * Sets an offset in a larger frustum. This is useful for multi-window or
  4909. * multi-monitor/multi-machine setups.
  4910. *
  4911. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  4912. * the monitors are in grid like this
  4913. *
  4914. * +---+---+---+
  4915. * | A | B | C |
  4916. * +---+---+---+
  4917. * | D | E | F |
  4918. * +---+---+---+
  4919. *
  4920. * then for each monitor you would call it like this
  4921. *
  4922. * var w = 1920;
  4923. * var h = 1080;
  4924. * var fullWidth = w * 3;
  4925. * var fullHeight = h * 2;
  4926. *
  4927. * --A--
  4928. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  4929. * --B--
  4930. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  4931. * --C--
  4932. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  4933. * --D--
  4934. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  4935. * --E--
  4936. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  4937. * --F--
  4938. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  4939. *
  4940. * Note there is no reason monitors have to be the same size or in a grid.
  4941. */
  4942. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  4943. this.fullWidth = fullWidth;
  4944. this.fullHeight = fullHeight;
  4945. this.x = x;
  4946. this.y = y;
  4947. this.width = width;
  4948. this.height = height;
  4949. this.updateProjectionMatrix();
  4950. };
  4951. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  4952. if ( this.fullWidth ) {
  4953. var aspect = this.fullWidth / this.fullHeight;
  4954. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  4955. var bottom = -top;
  4956. var left = aspect * bottom;
  4957. var right = aspect * top;
  4958. var width = Math.abs( right - left );
  4959. var height = Math.abs( top - bottom );
  4960. this.projectionMatrix.makeFrustum(
  4961. left + this.x * width / this.fullWidth,
  4962. left + ( this.x + this.width ) * width / this.fullWidth,
  4963. top - ( this.y + this.height ) * height / this.fullHeight,
  4964. top - this.y * height / this.fullHeight,
  4965. this.near,
  4966. this.far
  4967. );
  4968. } else {
  4969. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  4970. }
  4971. };
  4972. /**
  4973. * @author mrdoob / http://mrdoob.com/
  4974. * @author alteredq / http://alteredqualia.com/
  4975. */
  4976. THREE.Light = function ( hex ) {
  4977. THREE.Object3D.call( this );
  4978. this.color = new THREE.Color( hex );
  4979. };
  4980. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  4981. /**
  4982. * @author mrdoob / http://mrdoob.com/
  4983. */
  4984. THREE.AmbientLight = function ( hex ) {
  4985. THREE.Light.call( this, hex );
  4986. };
  4987. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  4988. /**
  4989. * @author MPanknin / http://www.redplant.de/
  4990. * @author alteredq / http://alteredqualia.com/
  4991. */
  4992. THREE.AreaLight = function ( hex, intensity ) {
  4993. THREE.Light.call( this, hex );
  4994. this.normal = new THREE.Vector3( 0, -1, 0 );
  4995. this.right = new THREE.Vector3( 1, 0, 0 );
  4996. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4997. this.width = 1.0;
  4998. this.height = 1.0;
  4999. this.constantAttenuation = 1.5;
  5000. this.linearAttenuation = 0.5;
  5001. this.quadraticAttenuation = 0.1;
  5002. };
  5003. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5004. /**
  5005. * @author mrdoob / http://mrdoob.com/
  5006. * @author alteredq / http://alteredqualia.com/
  5007. */
  5008. THREE.DirectionalLight = function ( hex, intensity ) {
  5009. THREE.Light.call( this, hex );
  5010. this.position = new THREE.Vector3( 0, 1, 0 );
  5011. this.target = new THREE.Object3D();
  5012. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5013. this.castShadow = false;
  5014. this.onlyShadow = false;
  5015. //
  5016. this.shadowCameraNear = 50;
  5017. this.shadowCameraFar = 5000;
  5018. this.shadowCameraLeft = -500;
  5019. this.shadowCameraRight = 500;
  5020. this.shadowCameraTop = 500;
  5021. this.shadowCameraBottom = -500;
  5022. this.shadowCameraVisible = false;
  5023. this.shadowBias = 0;
  5024. this.shadowDarkness = 0.5;
  5025. this.shadowMapWidth = 512;
  5026. this.shadowMapHeight = 512;
  5027. //
  5028. this.shadowCascade = false;
  5029. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5030. this.shadowCascadeCount = 2;
  5031. this.shadowCascadeBias = [ 0, 0, 0 ];
  5032. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5033. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5034. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5035. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5036. this.shadowCascadeArray = [];
  5037. //
  5038. this.shadowMap = null;
  5039. this.shadowMapSize = null;
  5040. this.shadowCamera = null;
  5041. this.shadowMatrix = null;
  5042. };
  5043. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5044. /**
  5045. * @author alteredq / http://alteredqualia.com/
  5046. */
  5047. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5048. THREE.Light.call( this, skyColorHex );
  5049. this.groundColor = new THREE.Color( groundColorHex );
  5050. this.position = new THREE.Vector3( 0, 100, 0 );
  5051. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5052. };
  5053. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5054. /**
  5055. * @author mrdoob / http://mrdoob.com/
  5056. */
  5057. THREE.PointLight = function ( hex, intensity, distance ) {
  5058. THREE.Light.call( this, hex );
  5059. this.position = new THREE.Vector3( 0, 0, 0 );
  5060. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5061. this.distance = ( distance !== undefined ) ? distance : 0;
  5062. };
  5063. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5064. /**
  5065. * @author alteredq / http://alteredqualia.com/
  5066. */
  5067. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5068. THREE.Light.call( this, hex );
  5069. this.position = new THREE.Vector3( 0, 1, 0 );
  5070. this.target = new THREE.Object3D();
  5071. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5072. this.distance = ( distance !== undefined ) ? distance : 0;
  5073. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  5074. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5075. this.castShadow = false;
  5076. this.onlyShadow = false;
  5077. //
  5078. this.shadowCameraNear = 50;
  5079. this.shadowCameraFar = 5000;
  5080. this.shadowCameraFov = 50;
  5081. this.shadowCameraVisible = false;
  5082. this.shadowBias = 0;
  5083. this.shadowDarkness = 0.5;
  5084. this.shadowMapWidth = 512;
  5085. this.shadowMapHeight = 512;
  5086. //
  5087. this.shadowMap = null;
  5088. this.shadowMapSize = null;
  5089. this.shadowCamera = null;
  5090. this.shadowMatrix = null;
  5091. };
  5092. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5093. /**
  5094. * @author alteredq / http://alteredqualia.com/
  5095. */
  5096. THREE.Loader = function ( showStatus ) {
  5097. this.showStatus = showStatus;
  5098. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5099. this.onLoadStart = function () {};
  5100. this.onLoadProgress = function () {};
  5101. this.onLoadComplete = function () {};
  5102. };
  5103. THREE.Loader.prototype = {
  5104. constructor: THREE.Loader,
  5105. crossOrigin: 'anonymous',
  5106. addStatusElement: function () {
  5107. var e = document.createElement( "div" );
  5108. e.style.position = "absolute";
  5109. e.style.right = "0px";
  5110. e.style.top = "0px";
  5111. e.style.fontSize = "0.8em";
  5112. e.style.textAlign = "left";
  5113. e.style.background = "rgba(0,0,0,0.25)";
  5114. e.style.color = "#fff";
  5115. e.style.width = "120px";
  5116. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5117. e.style.zIndex = 1000;
  5118. e.innerHTML = "Loading ...";
  5119. return e;
  5120. },
  5121. updateProgress: function ( progress ) {
  5122. var message = "Loaded ";
  5123. if ( progress.total ) {
  5124. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5125. } else {
  5126. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5127. }
  5128. this.statusDomElement.innerHTML = message;
  5129. },
  5130. extractUrlBase: function ( url ) {
  5131. var parts = url.split( '/' );
  5132. parts.pop();
  5133. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5134. },
  5135. initMaterials: function ( materials, texturePath ) {
  5136. var array = [];
  5137. for ( var i = 0; i < materials.length; ++ i ) {
  5138. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5139. }
  5140. return array;
  5141. },
  5142. needsTangents: function ( materials ) {
  5143. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5144. var m = materials[ i ];
  5145. if ( m instanceof THREE.ShaderMaterial ) return true;
  5146. }
  5147. return false;
  5148. },
  5149. createMaterial: function ( m, texturePath ) {
  5150. var _this = this;
  5151. function is_pow2( n ) {
  5152. var l = Math.log( n ) / Math.LN2;
  5153. return Math.floor( l ) == l;
  5154. }
  5155. function nearest_pow2( n ) {
  5156. var l = Math.log( n ) / Math.LN2;
  5157. return Math.pow( 2, Math.round( l ) );
  5158. }
  5159. function load_image( where, url ) {
  5160. var image = new Image();
  5161. image.onload = function () {
  5162. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5163. var width = nearest_pow2( this.width );
  5164. var height = nearest_pow2( this.height );
  5165. where.image.width = width;
  5166. where.image.height = height;
  5167. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5168. } else {
  5169. where.image = this;
  5170. }
  5171. where.needsUpdate = true;
  5172. };
  5173. image.crossOrigin = _this.crossOrigin;
  5174. image.src = url;
  5175. }
  5176. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5177. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  5178. var fullPath = texturePath + "/" + sourceFile;
  5179. if ( isCompressed ) {
  5180. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5181. where[ name ] = texture;
  5182. } else {
  5183. var texture = document.createElement( 'canvas' );
  5184. where[ name ] = new THREE.Texture( texture );
  5185. }
  5186. where[ name ].sourceFile = sourceFile;
  5187. if( repeat ) {
  5188. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5189. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5190. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5191. }
  5192. if ( offset ) {
  5193. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5194. }
  5195. if ( wrap ) {
  5196. var wrapMap = {
  5197. "repeat": THREE.RepeatWrapping,
  5198. "mirror": THREE.MirroredRepeatWrapping
  5199. }
  5200. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5201. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5202. }
  5203. if ( anisotropy ) {
  5204. where[ name ].anisotropy = anisotropy;
  5205. }
  5206. if ( ! isCompressed ) {
  5207. load_image( where[ name ], fullPath );
  5208. }
  5209. }
  5210. function rgb2hex( rgb ) {
  5211. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5212. }
  5213. // defaults
  5214. var mtype = "MeshLambertMaterial";
  5215. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5216. // parameters from model file
  5217. if ( m.shading ) {
  5218. var shading = m.shading.toLowerCase();
  5219. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5220. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5221. }
  5222. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5223. mpars.blending = THREE[ m.blending ];
  5224. }
  5225. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5226. mpars.transparent = m.transparent;
  5227. }
  5228. if ( m.depthTest !== undefined ) {
  5229. mpars.depthTest = m.depthTest;
  5230. }
  5231. if ( m.depthWrite !== undefined ) {
  5232. mpars.depthWrite = m.depthWrite;
  5233. }
  5234. if ( m.visible !== undefined ) {
  5235. mpars.visible = m.visible;
  5236. }
  5237. if ( m.flipSided !== undefined ) {
  5238. mpars.side = THREE.BackSide;
  5239. }
  5240. if ( m.doubleSided !== undefined ) {
  5241. mpars.side = THREE.DoubleSide;
  5242. }
  5243. if ( m.wireframe !== undefined ) {
  5244. mpars.wireframe = m.wireframe;
  5245. }
  5246. if ( m.vertexColors !== undefined ) {
  5247. if ( m.vertexColors === "face" ) {
  5248. mpars.vertexColors = THREE.FaceColors;
  5249. } else if ( m.vertexColors ) {
  5250. mpars.vertexColors = THREE.VertexColors;
  5251. }
  5252. }
  5253. // colors
  5254. if ( m.colorDiffuse ) {
  5255. mpars.color = rgb2hex( m.colorDiffuse );
  5256. } else if ( m.DbgColor ) {
  5257. mpars.color = m.DbgColor;
  5258. }
  5259. if ( m.colorSpecular ) {
  5260. mpars.specular = rgb2hex( m.colorSpecular );
  5261. }
  5262. if ( m.colorAmbient ) {
  5263. mpars.ambient = rgb2hex( m.colorAmbient );
  5264. }
  5265. // modifiers
  5266. if ( m.transparency ) {
  5267. mpars.opacity = m.transparency;
  5268. }
  5269. if ( m.specularCoef ) {
  5270. mpars.shininess = m.specularCoef;
  5271. }
  5272. // textures
  5273. if ( m.mapDiffuse && texturePath ) {
  5274. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5275. }
  5276. if ( m.mapLight && texturePath ) {
  5277. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5278. }
  5279. if ( m.mapBump && texturePath ) {
  5280. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5281. }
  5282. if ( m.mapNormal && texturePath ) {
  5283. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5284. }
  5285. if ( m.mapSpecular && texturePath ) {
  5286. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5287. }
  5288. //
  5289. if ( m.mapBumpScale ) {
  5290. mpars.bumpScale = m.mapBumpScale;
  5291. }
  5292. // special case for normal mapped material
  5293. if ( m.mapNormal ) {
  5294. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5295. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5296. uniforms[ "tNormal" ].value = mpars.normalMap;
  5297. if ( m.mapNormalFactor ) {
  5298. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5299. }
  5300. if ( mpars.map ) {
  5301. uniforms[ "tDiffuse" ].value = mpars.map;
  5302. uniforms[ "enableDiffuse" ].value = true;
  5303. }
  5304. if ( mpars.specularMap ) {
  5305. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5306. uniforms[ "enableSpecular" ].value = true;
  5307. }
  5308. if ( mpars.lightMap ) {
  5309. uniforms[ "tAO" ].value = mpars.lightMap;
  5310. uniforms[ "enableAO" ].value = true;
  5311. }
  5312. // for the moment don't handle displacement texture
  5313. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5314. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5315. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5316. uniforms[ "uShininess" ].value = mpars.shininess;
  5317. if ( mpars.opacity !== undefined ) {
  5318. uniforms[ "uOpacity" ].value = mpars.opacity;
  5319. }
  5320. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5321. var material = new THREE.ShaderMaterial( parameters );
  5322. if ( mpars.transparent ) {
  5323. material.transparent = true;
  5324. }
  5325. } else {
  5326. var material = new THREE[ mtype ]( mpars );
  5327. }
  5328. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5329. return material;
  5330. }
  5331. };
  5332. /**
  5333. * @author alteredq / http://alteredqualia.com/
  5334. */
  5335. THREE.BinaryLoader = function ( showStatus ) {
  5336. THREE.Loader.call( this, showStatus );
  5337. };
  5338. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  5339. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  5340. // - binary models consist of two files: JS and BIN
  5341. // - parameters
  5342. // - url (required)
  5343. // - callback (required)
  5344. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  5345. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  5346. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  5347. // todo: unify load API to for easier SceneLoader use
  5348. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5349. binaryPath = binaryPath && ( typeof binaryPath === "string" ) ? binaryPath : this.extractUrlBase( url );
  5350. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  5351. this.onLoadStart();
  5352. // #1 load JS part via web worker
  5353. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  5354. };
  5355. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  5356. var xhr = new XMLHttpRequest();
  5357. xhr.onreadystatechange = function () {
  5358. if ( xhr.readyState == 4 ) {
  5359. if ( xhr.status == 200 || xhr.status == 0 ) {
  5360. var json = JSON.parse( xhr.responseText );
  5361. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  5362. } else {
  5363. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5364. }
  5365. }
  5366. };
  5367. xhr.open( "GET", url, true );
  5368. xhr.send( null );
  5369. };
  5370. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  5371. var xhr = new XMLHttpRequest(),
  5372. url = binaryPath + "/" + json.buffers;
  5373. var length = 0;
  5374. xhr.onreadystatechange = function () {
  5375. if ( xhr.readyState == 4 ) {
  5376. if ( xhr.status == 200 || xhr.status == 0 ) {
  5377. var buffer = xhr.response;
  5378. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  5379. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  5380. } else {
  5381. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5382. }
  5383. } else if ( xhr.readyState == 3 ) {
  5384. if ( callbackProgress ) {
  5385. if ( length == 0 ) {
  5386. length = xhr.getResponseHeader( "Content-Length" );
  5387. }
  5388. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5389. }
  5390. } else if ( xhr.readyState == 2 ) {
  5391. length = xhr.getResponseHeader( "Content-Length" );
  5392. }
  5393. };
  5394. xhr.open( "GET", url, true );
  5395. xhr.responseType = "arraybuffer";
  5396. xhr.send( null );
  5397. };
  5398. // Binary AJAX parser
  5399. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, jsonMaterials ) {
  5400. var Model = function ( texturePath ) {
  5401. var scope = this,
  5402. currentOffset = 0,
  5403. md,
  5404. normals = [],
  5405. uvs = [],
  5406. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  5407. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  5408. tri_size, quad_size,
  5409. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  5410. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  5411. THREE.Geometry.call( this );
  5412. md = parseMetaData( data, currentOffset );
  5413. currentOffset += md.header_bytes;
  5414. /*
  5415. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  5416. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  5417. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  5418. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  5419. */
  5420. // buffers sizes
  5421. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  5422. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  5423. len_tri_flat = md.ntri_flat * ( tri_size );
  5424. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  5425. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  5426. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  5427. len_quad_flat = md.nquad_flat * ( quad_size );
  5428. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  5429. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  5430. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  5431. // read buffers
  5432. currentOffset += init_vertices( currentOffset );
  5433. currentOffset += init_normals( currentOffset );
  5434. currentOffset += handlePadding( md.nnormals * 3 );
  5435. currentOffset += init_uvs( currentOffset );
  5436. start_tri_flat = currentOffset;
  5437. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  5438. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  5439. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  5440. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  5441. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  5442. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  5443. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  5444. // have to first process faces with uvs
  5445. // so that face and uv indices match
  5446. init_triangles_flat_uv( start_tri_flat_uv );
  5447. init_triangles_smooth_uv( start_tri_smooth_uv );
  5448. init_quads_flat_uv( start_quad_flat_uv );
  5449. init_quads_smooth_uv( start_quad_smooth_uv );
  5450. // now we can process untextured faces
  5451. init_triangles_flat( start_tri_flat );
  5452. init_triangles_smooth( start_tri_smooth );
  5453. init_quads_flat( start_quad_flat );
  5454. init_quads_smooth( start_quad_smooth );
  5455. this.computeCentroids();
  5456. this.computeFaceNormals();
  5457. function handlePadding( n ) {
  5458. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  5459. };
  5460. function parseMetaData( data, offset ) {
  5461. var metaData = {
  5462. 'signature' :parseString( data, offset, 12 ),
  5463. 'header_bytes' :parseUChar8( data, offset + 12 ),
  5464. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  5465. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  5466. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  5467. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  5468. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  5469. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  5470. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  5471. 'nvertices' :parseUInt32( data, offset + 20 ),
  5472. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  5473. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  5474. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  5475. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  5476. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  5477. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  5478. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  5479. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  5480. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  5481. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  5482. };
  5483. /*
  5484. console.log( "signature: " + metaData.signature );
  5485. console.log( "header_bytes: " + metaData.header_bytes );
  5486. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  5487. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  5488. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  5489. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  5490. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  5491. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  5492. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  5493. console.log( "nvertices: " + metaData.nvertices );
  5494. console.log( "nnormals: " + metaData.nnormals );
  5495. console.log( "nuvs: " + metaData.nuvs );
  5496. console.log( "ntri_flat: " + metaData.ntri_flat );
  5497. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  5498. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  5499. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  5500. console.log( "nquad_flat: " + metaData.nquad_flat );
  5501. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  5502. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  5503. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  5504. var total = metaData.header_bytes
  5505. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  5506. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  5507. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  5508. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  5509. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  5510. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  5511. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  5512. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  5513. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  5514. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  5515. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  5516. console.log( "total bytes: " + total );
  5517. */
  5518. return metaData;
  5519. };
  5520. function parseString( data, offset, length ) {
  5521. var charArray = new Uint8Array( data, offset, length );
  5522. var text = "";
  5523. for ( var i = 0; i < length; i ++ ) {
  5524. text += String.fromCharCode( charArray[ offset + i ] );
  5525. }
  5526. return text;
  5527. };
  5528. function parseUChar8( data, offset ) {
  5529. var charArray = new Uint8Array( data, offset, 1 );
  5530. return charArray[ 0 ];
  5531. };
  5532. function parseUInt32( data, offset ) {
  5533. var intArray = new Uint32Array( data, offset, 1 );
  5534. return intArray[ 0 ];
  5535. };
  5536. function init_vertices( start ) {
  5537. var nElements = md.nvertices;
  5538. var coordArray = new Float32Array( data, start, nElements * 3 );
  5539. var i, x, y, z;
  5540. for( i = 0; i < nElements; i ++ ) {
  5541. x = coordArray[ i * 3 ];
  5542. y = coordArray[ i * 3 + 1 ];
  5543. z = coordArray[ i * 3 + 2 ];
  5544. vertex( scope, x, y, z );
  5545. }
  5546. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  5547. };
  5548. function init_normals( start ) {
  5549. var nElements = md.nnormals;
  5550. if ( nElements ) {
  5551. var normalArray = new Int8Array( data, start, nElements * 3 );
  5552. var i, x, y, z;
  5553. for( i = 0; i < nElements; i ++ ) {
  5554. x = normalArray[ i * 3 ];
  5555. y = normalArray[ i * 3 + 1 ];
  5556. z = normalArray[ i * 3 + 2 ];
  5557. normals.push( x/127, y/127, z/127 );
  5558. }
  5559. }
  5560. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  5561. };
  5562. function init_uvs( start ) {
  5563. var nElements = md.nuvs;
  5564. if ( nElements ) {
  5565. var uvArray = new Float32Array( data, start, nElements * 2 );
  5566. var i, u, v;
  5567. for( i = 0; i < nElements; i ++ ) {
  5568. u = uvArray[ i * 2 ];
  5569. v = uvArray[ i * 2 + 1 ];
  5570. uvs.push( u, v );
  5571. }
  5572. }
  5573. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  5574. };
  5575. function init_uvs3( nElements, offset ) {
  5576. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  5577. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  5578. for( i = 0; i < nElements; i ++ ) {
  5579. uva = uvIndexBuffer[ i * 3 ];
  5580. uvb = uvIndexBuffer[ i * 3 + 1 ];
  5581. uvc = uvIndexBuffer[ i * 3 + 2 ];
  5582. u1 = uvs[ uva*2 ];
  5583. v1 = uvs[ uva*2 + 1 ];
  5584. u2 = uvs[ uvb*2 ];
  5585. v2 = uvs[ uvb*2 + 1 ];
  5586. u3 = uvs[ uvc*2 ];
  5587. v3 = uvs[ uvc*2 + 1 ];
  5588. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  5589. }
  5590. };
  5591. function init_uvs4( nElements, offset ) {
  5592. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  5593. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  5594. for( i = 0; i < nElements; i ++ ) {
  5595. uva = uvIndexBuffer[ i * 4 ];
  5596. uvb = uvIndexBuffer[ i * 4 + 1 ];
  5597. uvc = uvIndexBuffer[ i * 4 + 2 ];
  5598. uvd = uvIndexBuffer[ i * 4 + 3 ];
  5599. u1 = uvs[ uva*2 ];
  5600. v1 = uvs[ uva*2 + 1 ];
  5601. u2 = uvs[ uvb*2 ];
  5602. v2 = uvs[ uvb*2 + 1 ];
  5603. u3 = uvs[ uvc*2 ];
  5604. v3 = uvs[ uvc*2 + 1 ];
  5605. u4 = uvs[ uvd*2 ];
  5606. v4 = uvs[ uvd*2 + 1 ];
  5607. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  5608. }
  5609. };
  5610. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  5611. var i, a, b, c, m;
  5612. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  5613. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5614. for( i = 0; i < nElements; i ++ ) {
  5615. a = vertexIndexBuffer[ i * 3 ];
  5616. b = vertexIndexBuffer[ i * 3 + 1 ];
  5617. c = vertexIndexBuffer[ i * 3 + 2 ];
  5618. m = materialIndexBuffer[ i ];
  5619. f3( scope, a, b, c, m );
  5620. }
  5621. };
  5622. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  5623. var i, a, b, c, d, m;
  5624. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  5625. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5626. for( i = 0; i < nElements; i ++ ) {
  5627. a = vertexIndexBuffer[ i * 4 ];
  5628. b = vertexIndexBuffer[ i * 4 + 1 ];
  5629. c = vertexIndexBuffer[ i * 4 + 2 ];
  5630. d = vertexIndexBuffer[ i * 4 + 3 ];
  5631. m = materialIndexBuffer[ i ];
  5632. f4( scope, a, b, c, d, m );
  5633. }
  5634. };
  5635. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  5636. var i, a, b, c, m;
  5637. var na, nb, nc;
  5638. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  5639. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  5640. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5641. for( i = 0; i < nElements; i ++ ) {
  5642. a = vertexIndexBuffer[ i * 3 ];
  5643. b = vertexIndexBuffer[ i * 3 + 1 ];
  5644. c = vertexIndexBuffer[ i * 3 + 2 ];
  5645. na = normalIndexBuffer[ i * 3 ];
  5646. nb = normalIndexBuffer[ i * 3 + 1 ];
  5647. nc = normalIndexBuffer[ i * 3 + 2 ];
  5648. m = materialIndexBuffer[ i ];
  5649. f3n( scope, normals, a, b, c, m, na, nb, nc );
  5650. }
  5651. };
  5652. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  5653. var i, a, b, c, d, m;
  5654. var na, nb, nc, nd;
  5655. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  5656. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  5657. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5658. for( i = 0; i < nElements; i ++ ) {
  5659. a = vertexIndexBuffer[ i * 4 ];
  5660. b = vertexIndexBuffer[ i * 4 + 1 ];
  5661. c = vertexIndexBuffer[ i * 4 + 2 ];
  5662. d = vertexIndexBuffer[ i * 4 + 3 ];
  5663. na = normalIndexBuffer[ i * 4 ];
  5664. nb = normalIndexBuffer[ i * 4 + 1 ];
  5665. nc = normalIndexBuffer[ i * 4 + 2 ];
  5666. nd = normalIndexBuffer[ i * 4 + 3 ];
  5667. m = materialIndexBuffer[ i ];
  5668. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  5669. }
  5670. };
  5671. function init_triangles_flat( start ) {
  5672. var nElements = md.ntri_flat;
  5673. if ( nElements ) {
  5674. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5675. init_faces3_flat( nElements, start, offsetMaterials );
  5676. }
  5677. };
  5678. function init_triangles_flat_uv( start ) {
  5679. var nElements = md.ntri_flat_uv;
  5680. if ( nElements ) {
  5681. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5682. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5683. init_faces3_flat( nElements, start, offsetMaterials );
  5684. init_uvs3( nElements, offsetUvs );
  5685. }
  5686. };
  5687. function init_triangles_smooth( start ) {
  5688. var nElements = md.ntri_smooth;
  5689. if ( nElements ) {
  5690. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5691. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5692. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  5693. }
  5694. };
  5695. function init_triangles_smooth_uv( start ) {
  5696. var nElements = md.ntri_smooth_uv;
  5697. if ( nElements ) {
  5698. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5699. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5700. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5701. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  5702. init_uvs3( nElements, offsetUvs );
  5703. }
  5704. };
  5705. function init_quads_flat( start ) {
  5706. var nElements = md.nquad_flat;
  5707. if ( nElements ) {
  5708. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5709. init_faces4_flat( nElements, start, offsetMaterials );
  5710. }
  5711. };
  5712. function init_quads_flat_uv( start ) {
  5713. var nElements = md.nquad_flat_uv;
  5714. if ( nElements ) {
  5715. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5716. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5717. init_faces4_flat( nElements, start, offsetMaterials );
  5718. init_uvs4( nElements, offsetUvs );
  5719. }
  5720. };
  5721. function init_quads_smooth( start ) {
  5722. var nElements = md.nquad_smooth;
  5723. if ( nElements ) {
  5724. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5725. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5726. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  5727. }
  5728. };
  5729. function init_quads_smooth_uv( start ) {
  5730. var nElements = md.nquad_smooth_uv;
  5731. if ( nElements ) {
  5732. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5733. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5734. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5735. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  5736. init_uvs4( nElements, offsetUvs );
  5737. }
  5738. };
  5739. };
  5740. function vertex ( scope, x, y, z ) {
  5741. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  5742. };
  5743. function f3 ( scope, a, b, c, mi ) {
  5744. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  5745. };
  5746. function f4 ( scope, a, b, c, d, mi ) {
  5747. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  5748. };
  5749. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  5750. var nax = normals[ na*3 ],
  5751. nay = normals[ na*3 + 1 ],
  5752. naz = normals[ na*3 + 2 ],
  5753. nbx = normals[ nb*3 ],
  5754. nby = normals[ nb*3 + 1 ],
  5755. nbz = normals[ nb*3 + 2 ],
  5756. ncx = normals[ nc*3 ],
  5757. ncy = normals[ nc*3 + 1 ],
  5758. ncz = normals[ nc*3 + 2 ];
  5759. scope.faces.push( new THREE.Face3( a, b, c,
  5760. [new THREE.Vector3( nax, nay, naz ),
  5761. new THREE.Vector3( nbx, nby, nbz ),
  5762. new THREE.Vector3( ncx, ncy, ncz )],
  5763. null,
  5764. mi ) );
  5765. };
  5766. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  5767. var nax = normals[ na*3 ],
  5768. nay = normals[ na*3 + 1 ],
  5769. naz = normals[ na*3 + 2 ],
  5770. nbx = normals[ nb*3 ],
  5771. nby = normals[ nb*3 + 1 ],
  5772. nbz = normals[ nb*3 + 2 ],
  5773. ncx = normals[ nc*3 ],
  5774. ncy = normals[ nc*3 + 1 ],
  5775. ncz = normals[ nc*3 + 2 ],
  5776. ndx = normals[ nd*3 ],
  5777. ndy = normals[ nd*3 + 1 ],
  5778. ndz = normals[ nd*3 + 2 ];
  5779. scope.faces.push( new THREE.Face4( a, b, c, d,
  5780. [new THREE.Vector3( nax, nay, naz ),
  5781. new THREE.Vector3( nbx, nby, nbz ),
  5782. new THREE.Vector3( ncx, ncy, ncz ),
  5783. new THREE.Vector3( ndx, ndy, ndz )],
  5784. null,
  5785. mi ) );
  5786. };
  5787. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  5788. where.push( [
  5789. new THREE.Vector2( u1, v1 ),
  5790. new THREE.Vector2( u2, v2 ),
  5791. new THREE.Vector2( u3, v3 )
  5792. ] );
  5793. };
  5794. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  5795. where.push( [
  5796. new THREE.Vector2( u1, v1 ),
  5797. new THREE.Vector2( u2, v2 ),
  5798. new THREE.Vector2( u3, v3 ),
  5799. new THREE.Vector2( u4, v4 )
  5800. ] );
  5801. };
  5802. Model.prototype = Object.create( THREE.Geometry.prototype );
  5803. var geometry = new Model( texturePath );
  5804. var materials = this.initMaterials( jsonMaterials, texturePath );
  5805. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5806. callback( geometry, materials );
  5807. };
  5808. /**
  5809. * @author mrdoob / http://mrdoob.com/
  5810. */
  5811. THREE.ImageLoader = function () {
  5812. THREE.EventDispatcher.call( this );
  5813. this.crossOrigin = null;
  5814. };
  5815. THREE.ImageLoader.prototype = {
  5816. constructor: THREE.ImageLoader,
  5817. load: function ( url, image ) {
  5818. var scope = this;
  5819. if ( image === undefined ) image = new Image();
  5820. image.addEventListener( 'load', function () {
  5821. scope.dispatchEvent( { type: 'load', content: image } );
  5822. }, false );
  5823. image.addEventListener( 'error', function () {
  5824. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5825. }, false );
  5826. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5827. image.src = url;
  5828. }
  5829. }
  5830. /**
  5831. * @author mrdoob / http://mrdoob.com/
  5832. * @author alteredq / http://alteredqualia.com/
  5833. */
  5834. THREE.JSONLoader = function ( showStatus ) {
  5835. THREE.Loader.call( this, showStatus );
  5836. this.withCredentials = false;
  5837. };
  5838. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5839. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5840. var scope = this;
  5841. // todo: unify load API to for easier SceneLoader use
  5842. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5843. this.onLoadStart();
  5844. this.loadAjaxJSON( this, url, callback, texturePath );
  5845. };
  5846. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5847. var xhr = new XMLHttpRequest();
  5848. var length = 0;
  5849. xhr.withCredentials = this.withCredentials;
  5850. xhr.onreadystatechange = function () {
  5851. if ( xhr.readyState === xhr.DONE ) {
  5852. if ( xhr.status === 200 || xhr.status === 0 ) {
  5853. if ( xhr.responseText ) {
  5854. var json = JSON.parse( xhr.responseText );
  5855. context.createModel( json, callback, texturePath );
  5856. } else {
  5857. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5858. }
  5859. // in context of more complex asset initialization
  5860. // do not block on single failed file
  5861. // maybe should go even one more level up
  5862. context.onLoadComplete();
  5863. } else {
  5864. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5865. }
  5866. } else if ( xhr.readyState === xhr.LOADING ) {
  5867. if ( callbackProgress ) {
  5868. if ( length === 0 ) {
  5869. length = xhr.getResponseHeader( "Content-Length" );
  5870. }
  5871. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5872. }
  5873. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5874. length = xhr.getResponseHeader( "Content-Length" );
  5875. }
  5876. };
  5877. xhr.open( "GET", url, true );
  5878. xhr.send( null );
  5879. };
  5880. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  5881. var scope = this,
  5882. geometry = new THREE.Geometry(),
  5883. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5884. parseModel( scale );
  5885. parseSkin();
  5886. parseMorphing( scale );
  5887. geometry.computeCentroids();
  5888. geometry.computeFaceNormals();
  5889. function parseModel( scale ) {
  5890. function isBitSet( value, position ) {
  5891. return value & ( 1 << position );
  5892. }
  5893. var i, j, fi,
  5894. offset, zLength, nVertices,
  5895. colorIndex, normalIndex, uvIndex, materialIndex,
  5896. type,
  5897. isQuad,
  5898. hasMaterial,
  5899. hasFaceUv, hasFaceVertexUv,
  5900. hasFaceNormal, hasFaceVertexNormal,
  5901. hasFaceColor, hasFaceVertexColor,
  5902. vertex, face, color, normal,
  5903. uvLayer, uvs, u, v,
  5904. faces = json.faces,
  5905. vertices = json.vertices,
  5906. normals = json.normals,
  5907. colors = json.colors,
  5908. nUvLayers = 0;
  5909. // disregard empty arrays
  5910. for ( i = 0; i < json.uvs.length; i++ ) {
  5911. if ( json.uvs[ i ].length ) nUvLayers ++;
  5912. }
  5913. for ( i = 0; i < nUvLayers; i++ ) {
  5914. geometry.faceUvs[ i ] = [];
  5915. geometry.faceVertexUvs[ i ] = [];
  5916. }
  5917. offset = 0;
  5918. zLength = vertices.length;
  5919. while ( offset < zLength ) {
  5920. vertex = new THREE.Vector3();
  5921. vertex.x = vertices[ offset ++ ] * scale;
  5922. vertex.y = vertices[ offset ++ ] * scale;
  5923. vertex.z = vertices[ offset ++ ] * scale;
  5924. geometry.vertices.push( vertex );
  5925. }
  5926. offset = 0;
  5927. zLength = faces.length;
  5928. while ( offset < zLength ) {
  5929. type = faces[ offset ++ ];
  5930. isQuad = isBitSet( type, 0 );
  5931. hasMaterial = isBitSet( type, 1 );
  5932. hasFaceUv = isBitSet( type, 2 );
  5933. hasFaceVertexUv = isBitSet( type, 3 );
  5934. hasFaceNormal = isBitSet( type, 4 );
  5935. hasFaceVertexNormal = isBitSet( type, 5 );
  5936. hasFaceColor = isBitSet( type, 6 );
  5937. hasFaceVertexColor = isBitSet( type, 7 );
  5938. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5939. if ( isQuad ) {
  5940. face = new THREE.Face4();
  5941. face.a = faces[ offset ++ ];
  5942. face.b = faces[ offset ++ ];
  5943. face.c = faces[ offset ++ ];
  5944. face.d = faces[ offset ++ ];
  5945. nVertices = 4;
  5946. } else {
  5947. face = new THREE.Face3();
  5948. face.a = faces[ offset ++ ];
  5949. face.b = faces[ offset ++ ];
  5950. face.c = faces[ offset ++ ];
  5951. nVertices = 3;
  5952. }
  5953. if ( hasMaterial ) {
  5954. materialIndex = faces[ offset ++ ];
  5955. face.materialIndex = materialIndex;
  5956. }
  5957. // to get face <=> uv index correspondence
  5958. fi = geometry.faces.length;
  5959. if ( hasFaceUv ) {
  5960. for ( i = 0; i < nUvLayers; i++ ) {
  5961. uvLayer = json.uvs[ i ];
  5962. uvIndex = faces[ offset ++ ];
  5963. u = uvLayer[ uvIndex * 2 ];
  5964. v = uvLayer[ uvIndex * 2 + 1 ];
  5965. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  5966. }
  5967. }
  5968. if ( hasFaceVertexUv ) {
  5969. for ( i = 0; i < nUvLayers; i++ ) {
  5970. uvLayer = json.uvs[ i ];
  5971. uvs = [];
  5972. for ( j = 0; j < nVertices; j ++ ) {
  5973. uvIndex = faces[ offset ++ ];
  5974. u = uvLayer[ uvIndex * 2 ];
  5975. v = uvLayer[ uvIndex * 2 + 1 ];
  5976. uvs[ j ] = new THREE.Vector2( u, v );
  5977. }
  5978. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5979. }
  5980. }
  5981. if ( hasFaceNormal ) {
  5982. normalIndex = faces[ offset ++ ] * 3;
  5983. normal = new THREE.Vector3();
  5984. normal.x = normals[ normalIndex ++ ];
  5985. normal.y = normals[ normalIndex ++ ];
  5986. normal.z = normals[ normalIndex ];
  5987. face.normal = normal;
  5988. }
  5989. if ( hasFaceVertexNormal ) {
  5990. for ( i = 0; i < nVertices; i++ ) {
  5991. normalIndex = faces[ offset ++ ] * 3;
  5992. normal = new THREE.Vector3();
  5993. normal.x = normals[ normalIndex ++ ];
  5994. normal.y = normals[ normalIndex ++ ];
  5995. normal.z = normals[ normalIndex ];
  5996. face.vertexNormals.push( normal );
  5997. }
  5998. }
  5999. if ( hasFaceColor ) {
  6000. colorIndex = faces[ offset ++ ];
  6001. color = new THREE.Color( colors[ colorIndex ] );
  6002. face.color = color;
  6003. }
  6004. if ( hasFaceVertexColor ) {
  6005. for ( i = 0; i < nVertices; i++ ) {
  6006. colorIndex = faces[ offset ++ ];
  6007. color = new THREE.Color( colors[ colorIndex ] );
  6008. face.vertexColors.push( color );
  6009. }
  6010. }
  6011. geometry.faces.push( face );
  6012. }
  6013. };
  6014. function parseSkin() {
  6015. var i, l, x, y, z, w, a, b, c, d;
  6016. if ( json.skinWeights ) {
  6017. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6018. x = json.skinWeights[ i ];
  6019. y = json.skinWeights[ i + 1 ];
  6020. z = 0;
  6021. w = 0;
  6022. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6023. }
  6024. }
  6025. if ( json.skinIndices ) {
  6026. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6027. a = json.skinIndices[ i ];
  6028. b = json.skinIndices[ i + 1 ];
  6029. c = 0;
  6030. d = 0;
  6031. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6032. }
  6033. }
  6034. geometry.bones = json.bones;
  6035. geometry.animation = json.animation;
  6036. };
  6037. function parseMorphing( scale ) {
  6038. if ( json.morphTargets !== undefined ) {
  6039. var i, l, v, vl, dstVertices, srcVertices;
  6040. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6041. geometry.morphTargets[ i ] = {};
  6042. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6043. geometry.morphTargets[ i ].vertices = [];
  6044. dstVertices = geometry.morphTargets[ i ].vertices;
  6045. srcVertices = json.morphTargets [ i ].vertices;
  6046. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6047. var vertex = new THREE.Vector3();
  6048. vertex.x = srcVertices[ v ] * scale;
  6049. vertex.y = srcVertices[ v + 1 ] * scale;
  6050. vertex.z = srcVertices[ v + 2 ] * scale;
  6051. dstVertices.push( vertex );
  6052. }
  6053. }
  6054. }
  6055. if ( json.morphColors !== undefined ) {
  6056. var i, l, c, cl, dstColors, srcColors, color;
  6057. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6058. geometry.morphColors[ i ] = {};
  6059. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6060. geometry.morphColors[ i ].colors = [];
  6061. dstColors = geometry.morphColors[ i ].colors;
  6062. srcColors = json.morphColors [ i ].colors;
  6063. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6064. color = new THREE.Color( 0xffaa00 );
  6065. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6066. dstColors.push( color );
  6067. }
  6068. }
  6069. }
  6070. };
  6071. var materials = this.initMaterials( json.materials, texturePath );
  6072. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  6073. callback( geometry, materials );
  6074. };
  6075. /**
  6076. * @author mrdoob / http://mrdoob.com/
  6077. */
  6078. THREE.LoadingMonitor = function () {
  6079. THREE.EventDispatcher.call( this );
  6080. var scope = this;
  6081. var loaded = 0;
  6082. var total = 0;
  6083. var onLoad = function ( event ) {
  6084. loaded ++;
  6085. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  6086. if ( loaded === total ) {
  6087. scope.dispatchEvent( { type: 'load' } );
  6088. }
  6089. };
  6090. this.add = function ( loader ) {
  6091. total ++;
  6092. loader.addEventListener( 'load', onLoad, false );
  6093. };
  6094. };
  6095. /**
  6096. * @author alteredq / http://alteredqualia.com/
  6097. */
  6098. THREE.SceneLoader = function () {
  6099. this.onLoadStart = function () {};
  6100. this.onLoadProgress = function() {};
  6101. this.onLoadComplete = function () {};
  6102. this.callbackSync = function () {};
  6103. this.callbackProgress = function () {};
  6104. this.geometryHandlerMap = {};
  6105. this.hierarchyHandlerMap = {};
  6106. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6107. this.addGeometryHandler( "binary", THREE.BinaryLoader );
  6108. };
  6109. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  6110. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  6111. var scope = this;
  6112. var xhr = new XMLHttpRequest();
  6113. xhr.onreadystatechange = function () {
  6114. if ( xhr.readyState === 4 ) {
  6115. if ( xhr.status === 200 || xhr.status === 0 ) {
  6116. var json = JSON.parse( xhr.responseText );
  6117. scope.parse( json, callbackFinished, url );
  6118. } else {
  6119. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6120. }
  6121. }
  6122. };
  6123. xhr.open( "GET", url, true );
  6124. xhr.send( null );
  6125. };
  6126. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  6127. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  6128. };
  6129. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  6130. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  6131. };
  6132. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  6133. var scope = this;
  6134. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  6135. var geometry, material, camera, fog,
  6136. texture, images, color,
  6137. light, hex, intensity,
  6138. counter_models, counter_textures,
  6139. total_models, total_textures,
  6140. result;
  6141. var target_array = [];
  6142. var data = json;
  6143. // async geometry loaders
  6144. for ( var typeID in this.geometryHandlerMap ) {
  6145. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  6146. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  6147. }
  6148. // async hierachy loaders
  6149. for ( var typeID in this.hierarchyHandlerMap ) {
  6150. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  6151. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  6152. }
  6153. counter_models = 0;
  6154. counter_textures = 0;
  6155. result = {
  6156. scene: new THREE.Scene(),
  6157. geometries: {},
  6158. face_materials: {},
  6159. materials: {},
  6160. textures: {},
  6161. objects: {},
  6162. cameras: {},
  6163. lights: {},
  6164. fogs: {},
  6165. empties: {}
  6166. };
  6167. if ( data.transform ) {
  6168. var position = data.transform.position,
  6169. rotation = data.transform.rotation,
  6170. scale = data.transform.scale;
  6171. if ( position )
  6172. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  6173. if ( rotation )
  6174. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  6175. if ( scale )
  6176. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  6177. if ( position || rotation || scale ) {
  6178. result.scene.updateMatrix();
  6179. result.scene.updateMatrixWorld();
  6180. }
  6181. }
  6182. function get_url( source_url, url_type ) {
  6183. if ( url_type == "relativeToHTML" ) {
  6184. return source_url;
  6185. } else {
  6186. return urlBase + "/" + source_url;
  6187. }
  6188. };
  6189. // toplevel loader function, delegates to handle_children
  6190. function handle_objects() {
  6191. handle_children( result.scene, data.objects );
  6192. }
  6193. // handle all the children from the loaded json and attach them to given parent
  6194. function handle_children( parent, children ) {
  6195. var mat, dst, pos, rot, scl, quat;
  6196. for ( var objID in children ) {
  6197. // check by id if child has already been handled,
  6198. // if not, create new object
  6199. if ( result.objects[ objID ] === undefined ) {
  6200. var objJSON = children[ objID ];
  6201. var object = null;
  6202. // meshes
  6203. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {
  6204. if ( objJSON.loading === undefined ) {
  6205. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  6206. "position": 1, "rotation": 1, "scale" : 1,
  6207. "visible": 1, "children": 1, "properties": 1,
  6208. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  6209. var loaderParameters = {};
  6210. for ( var parType in objJSON ) {
  6211. if ( ! ( parType in reservedTypes ) ) {
  6212. loaderParameters[ parType ] = objJSON[ parType ];
  6213. }
  6214. }
  6215. material = result.materials[ objJSON.material ];
  6216. objJSON.loading = true;
  6217. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  6218. // ColladaLoader
  6219. if ( loader.options ) {
  6220. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6221. // UTF8Loader
  6222. // OBJLoader
  6223. } else {
  6224. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6225. }
  6226. }
  6227. } else if ( objJSON.geometry !== undefined ) {
  6228. geometry = result.geometries[ objJSON.geometry ];
  6229. // geometry already loaded
  6230. if ( geometry ) {
  6231. var needsTangents = false;
  6232. material = result.materials[ objJSON.material ];
  6233. needsTangents = material instanceof THREE.ShaderMaterial;
  6234. pos = objJSON.position;
  6235. rot = objJSON.rotation;
  6236. scl = objJSON.scale;
  6237. mat = objJSON.matrix;
  6238. quat = objJSON.quaternion;
  6239. // use materials from the model file
  6240. // if there is no material specified in the object
  6241. if ( ! objJSON.material ) {
  6242. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6243. }
  6244. // use materials from the model file
  6245. // if there is just empty face material
  6246. // (must create new material as each model has its own face material)
  6247. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6248. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6249. }
  6250. if ( material instanceof THREE.MeshFaceMaterial ) {
  6251. for ( var i = 0; i < material.materials.length; i ++ ) {
  6252. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6253. }
  6254. }
  6255. if ( needsTangents ) {
  6256. geometry.computeTangents();
  6257. }
  6258. if ( objJSON.skin ) {
  6259. object = new THREE.SkinnedMesh( geometry, material );
  6260. } else if ( objJSON.morph ) {
  6261. object = new THREE.MorphAnimMesh( geometry, material );
  6262. if ( objJSON.duration !== undefined ) {
  6263. object.duration = objJSON.duration;
  6264. }
  6265. if ( objJSON.time !== undefined ) {
  6266. object.time = objJSON.time;
  6267. }
  6268. if ( objJSON.mirroredLoop !== undefined ) {
  6269. object.mirroredLoop = objJSON.mirroredLoop;
  6270. }
  6271. if ( material.morphNormals ) {
  6272. geometry.computeMorphNormals();
  6273. }
  6274. } else {
  6275. object = new THREE.Mesh( geometry, material );
  6276. }
  6277. object.name = objID;
  6278. if ( mat ) {
  6279. object.matrixAutoUpdate = false;
  6280. object.matrix.set(
  6281. mat[0], mat[1], mat[2], mat[3],
  6282. mat[4], mat[5], mat[6], mat[7],
  6283. mat[8], mat[9], mat[10], mat[11],
  6284. mat[12], mat[13], mat[14], mat[15]
  6285. );
  6286. } else {
  6287. object.position.set( pos[0], pos[1], pos[2] );
  6288. if ( quat ) {
  6289. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6290. object.useQuaternion = true;
  6291. } else {
  6292. object.rotation.set( rot[0], rot[1], rot[2] );
  6293. }
  6294. object.scale.set( scl[0], scl[1], scl[2] );
  6295. }
  6296. object.visible = objJSON.visible;
  6297. object.castShadow = objJSON.castShadow;
  6298. object.receiveShadow = objJSON.receiveShadow;
  6299. parent.add( object );
  6300. result.objects[ objID ] = object;
  6301. }
  6302. // lights
  6303. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6304. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6305. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6306. if ( objJSON.type === "DirectionalLight" ) {
  6307. pos = objJSON.direction;
  6308. light = new THREE.DirectionalLight( hex, intensity );
  6309. light.position.set( pos[0], pos[1], pos[2] );
  6310. if ( objJSON.target ) {
  6311. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6312. // kill existing default target
  6313. // otherwise it gets added to scene when parent gets added
  6314. light.target = null;
  6315. }
  6316. } else if ( objJSON.type === "PointLight" ) {
  6317. pos = objJSON.position;
  6318. dst = objJSON.distance;
  6319. light = new THREE.PointLight( hex, intensity, dst );
  6320. light.position.set( pos[0], pos[1], pos[2] );
  6321. } else if ( objJSON.type === "AmbientLight" ) {
  6322. light = new THREE.AmbientLight( hex );
  6323. }
  6324. parent.add( light );
  6325. light.name = objID;
  6326. result.lights[ objID ] = light;
  6327. result.objects[ objID ] = light;
  6328. // cameras
  6329. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6330. if ( objJSON.type === "PerspectiveCamera" ) {
  6331. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6332. } else if ( objJSON.type === "OrthographicCamera" ) {
  6333. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6334. }
  6335. pos = objJSON.position;
  6336. camera.position.set( pos[0], pos[1], pos[2] );
  6337. parent.add( camera );
  6338. camera.name = objID;
  6339. result.cameras[ objID ] = camera;
  6340. result.objects[ objID ] = camera;
  6341. // pure Object3D
  6342. } else {
  6343. pos = objJSON.position;
  6344. rot = objJSON.rotation;
  6345. scl = objJSON.scale;
  6346. quat = objJSON.quaternion;
  6347. object = new THREE.Object3D();
  6348. object.name = objID;
  6349. object.position.set( pos[0], pos[1], pos[2] );
  6350. if ( quat ) {
  6351. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6352. object.useQuaternion = true;
  6353. } else {
  6354. object.rotation.set( rot[0], rot[1], rot[2] );
  6355. }
  6356. object.scale.set( scl[0], scl[1], scl[2] );
  6357. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6358. parent.add( object );
  6359. result.objects[ objID ] = object;
  6360. result.empties[ objID ] = object;
  6361. }
  6362. if ( object ) {
  6363. if ( objJSON.properties !== undefined ) {
  6364. for ( var key in objJSON.properties ) {
  6365. var value = objJSON.properties[ key ];
  6366. object.properties[ key ] = value;
  6367. }
  6368. }
  6369. if ( objJSON.children !== undefined ) {
  6370. handle_children( object, objJSON.children );
  6371. }
  6372. }
  6373. }
  6374. }
  6375. };
  6376. function handle_mesh( geo, mat, id ) {
  6377. result.geometries[ id ] = geo;
  6378. result.face_materials[ id ] = mat;
  6379. handle_objects();
  6380. };
  6381. function handle_hierarchy( node, id, parent, material, obj ) {
  6382. var p = obj.position;
  6383. var r = obj.rotation;
  6384. var q = obj.quaternion;
  6385. var s = obj.scale;
  6386. node.position.set( p[0], p[1], p[2] );
  6387. if ( q ) {
  6388. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6389. node.useQuaternion = true;
  6390. } else {
  6391. node.rotation.set( r[0], r[1], r[2] );
  6392. }
  6393. node.scale.set( s[0], s[1], s[2] );
  6394. // override children materials
  6395. // if object material was specified in JSON explicitly
  6396. if ( material ) {
  6397. node.traverse( function ( child ) {
  6398. child.material = material;
  6399. } );
  6400. }
  6401. // override children visibility
  6402. // with root node visibility as specified in JSON
  6403. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6404. node.traverse( function ( child ) {
  6405. child.visible = visible;
  6406. } );
  6407. parent.add( node );
  6408. node.name = id;
  6409. result.objects[ id ] = node;
  6410. handle_objects();
  6411. };
  6412. function create_callback_geometry( id ) {
  6413. return function( geo, mat ) {
  6414. handle_mesh( geo, mat, id );
  6415. counter_models -= 1;
  6416. scope.onLoadComplete();
  6417. async_callback_gate();
  6418. }
  6419. };
  6420. function create_callback_hierachy( id, parent, material, obj ) {
  6421. return function( event ) {
  6422. var result;
  6423. // loaders which use EventDispatcher
  6424. if ( event.content ) {
  6425. result = event.content;
  6426. // ColladaLoader
  6427. } else if ( event.dae ) {
  6428. result = event.scene;
  6429. // UTF8Loader
  6430. } else {
  6431. result = event;
  6432. }
  6433. handle_hierarchy( result, id, parent, material, obj );
  6434. counter_models -= 1;
  6435. scope.onLoadComplete();
  6436. async_callback_gate();
  6437. }
  6438. };
  6439. function create_callback_embed( id ) {
  6440. return function( geo, mat ) {
  6441. result.geometries[ id ] = geo;
  6442. result.face_materials[ id ] = mat;
  6443. }
  6444. };
  6445. function async_callback_gate() {
  6446. var progress = {
  6447. totalModels : total_models,
  6448. totalTextures : total_textures,
  6449. loadedModels : total_models - counter_models,
  6450. loadedTextures : total_textures - counter_textures
  6451. };
  6452. scope.callbackProgress( progress, result );
  6453. scope.onLoadProgress();
  6454. if ( counter_models === 0 && counter_textures === 0 ) {
  6455. finalize();
  6456. callbackFinished( result );
  6457. }
  6458. };
  6459. function finalize() {
  6460. // take care of targets which could be asynchronously loaded objects
  6461. for ( var i = 0; i < target_array.length; i ++ ) {
  6462. var ta = target_array[ i ];
  6463. var target = result.objects[ ta.targetName ];
  6464. if ( target ) {
  6465. ta.object.target = target;
  6466. } else {
  6467. // if there was error and target of specified name doesn't exist in the scene file
  6468. // create instead dummy target
  6469. // (target must be added to scene explicitly as parent is already added)
  6470. ta.object.target = new THREE.Object3D();
  6471. result.scene.add( ta.object.target );
  6472. }
  6473. ta.object.target.properties.targetInverse = ta.object;
  6474. }
  6475. };
  6476. var callbackTexture = function ( count ) {
  6477. counter_textures -= count;
  6478. async_callback_gate();
  6479. scope.onLoadComplete();
  6480. };
  6481. // must use this instead of just directly calling callbackTexture
  6482. // because of closure in the calling context loop
  6483. var generateTextureCallback = function ( count ) {
  6484. return function() {
  6485. callbackTexture( count );
  6486. };
  6487. };
  6488. // first go synchronous elements
  6489. // fogs
  6490. var fogID, fogJSON;
  6491. for ( fogID in data.fogs ) {
  6492. fogJSON = data.fogs[ fogID ];
  6493. if ( fogJSON.type === "linear" ) {
  6494. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6495. } else if ( fogJSON.type === "exp2" ) {
  6496. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6497. }
  6498. color = fogJSON.color;
  6499. fog.color.setRGB( color[0], color[1], color[2] );
  6500. result.fogs[ fogID ] = fog;
  6501. }
  6502. // now come potentially asynchronous elements
  6503. // geometries
  6504. // count how many geometries will be loaded asynchronously
  6505. var geoID, geoJSON;
  6506. for ( geoID in data.geometries ) {
  6507. geoJSON = data.geometries[ geoID ];
  6508. if ( geoJSON.type in this.geometryHandlerMap ) {
  6509. counter_models += 1;
  6510. scope.onLoadStart();
  6511. }
  6512. }
  6513. // count how many hierarchies will be loaded asynchronously
  6514. var objID, objJSON;
  6515. for ( objID in data.objects ) {
  6516. objJSON = data.objects[ objID ];
  6517. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6518. counter_models += 1;
  6519. scope.onLoadStart();
  6520. }
  6521. }
  6522. total_models = counter_models;
  6523. for ( geoID in data.geometries ) {
  6524. geoJSON = data.geometries[ geoID ];
  6525. if ( geoJSON.type === "cube" ) {
  6526. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6527. result.geometries[ geoID ] = geometry;
  6528. } else if ( geoJSON.type === "plane" ) {
  6529. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6530. result.geometries[ geoID ] = geometry;
  6531. } else if ( geoJSON.type === "sphere" ) {
  6532. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6533. result.geometries[ geoID ] = geometry;
  6534. } else if ( geoJSON.type === "cylinder" ) {
  6535. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6536. result.geometries[ geoID ] = geometry;
  6537. } else if ( geoJSON.type === "torus" ) {
  6538. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6539. result.geometries[ geoID ] = geometry;
  6540. } else if ( geoJSON.type === "icosahedron" ) {
  6541. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6542. result.geometries[ geoID ] = geometry;
  6543. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6544. var loaderParameters = {};
  6545. for ( var parType in geoJSON ) {
  6546. if ( parType !== "type" && parType !== "url" ) {
  6547. loaderParameters[ parType ] = geoJSON[ parType ];
  6548. }
  6549. }
  6550. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6551. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6552. } else if ( geoJSON.type === "embedded" ) {
  6553. var modelJson = data.embeds[ geoJSON.id ],
  6554. texture_path = "";
  6555. // pass metadata along to jsonLoader so it knows the format version
  6556. modelJson.metadata = data.metadata;
  6557. if ( modelJson ) {
  6558. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6559. jsonLoader.createModel( modelJson, create_callback_embed( geoID ), texture_path );
  6560. }
  6561. }
  6562. }
  6563. // textures
  6564. // count how many textures will be loaded asynchronously
  6565. var textureID, textureJSON;
  6566. for ( textureID in data.textures ) {
  6567. textureJSON = data.textures[ textureID ];
  6568. if ( textureJSON.url instanceof Array ) {
  6569. counter_textures += textureJSON.url.length;
  6570. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6571. scope.onLoadStart();
  6572. }
  6573. } else {
  6574. counter_textures += 1;
  6575. scope.onLoadStart();
  6576. }
  6577. }
  6578. total_textures = counter_textures;
  6579. for ( textureID in data.textures ) {
  6580. textureJSON = data.textures[ textureID ];
  6581. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6582. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6583. }
  6584. if ( textureJSON.url instanceof Array ) {
  6585. var count = textureJSON.url.length;
  6586. var url_array = [];
  6587. for( var i = 0; i < count; i ++ ) {
  6588. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6589. }
  6590. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  6591. if ( isCompressed ) {
  6592. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6593. } else {
  6594. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6595. }
  6596. } else {
  6597. var isCompressed = textureJSON.url.toLowerCase().endsWith( ".dds" );
  6598. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6599. var textureCallback = generateTextureCallback( 1 );
  6600. if ( isCompressed ) {
  6601. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6602. } else {
  6603. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6604. }
  6605. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6606. texture.minFilter = THREE[ textureJSON.minFilter ];
  6607. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6608. texture.magFilter = THREE[ textureJSON.magFilter ];
  6609. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6610. if ( textureJSON.repeat ) {
  6611. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6612. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6613. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6614. }
  6615. if ( textureJSON.offset ) {
  6616. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6617. }
  6618. // handle wrap after repeat so that default repeat can be overriden
  6619. if ( textureJSON.wrap ) {
  6620. var wrapMap = {
  6621. "repeat" : THREE.RepeatWrapping,
  6622. "mirror" : THREE.MirroredRepeatWrapping
  6623. }
  6624. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6625. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6626. }
  6627. }
  6628. result.textures[ textureID ] = texture;
  6629. }
  6630. // materials
  6631. var matID, matJSON;
  6632. var parID;
  6633. for ( matID in data.materials ) {
  6634. matJSON = data.materials[ matID ];
  6635. for ( parID in matJSON.parameters ) {
  6636. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6637. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6638. } else if ( parID === "shading" ) {
  6639. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6640. } else if ( parID === "side" ) {
  6641. if ( matJSON.parameters[ parID ] == "double" ) {
  6642. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6643. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6644. matJSON.parameters[ parID ] = THREE.BackSide;
  6645. } else {
  6646. matJSON.parameters[ parID ] = THREE.FrontSide;
  6647. }
  6648. } else if ( parID === "blending" ) {
  6649. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6650. } else if ( parID === "combine" ) {
  6651. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  6652. } else if ( parID === "vertexColors" ) {
  6653. if ( matJSON.parameters[ parID ] == "face" ) {
  6654. matJSON.parameters[ parID ] = THREE.FaceColors;
  6655. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6656. } else if ( matJSON.parameters[ parID ] ) {
  6657. matJSON.parameters[ parID ] = THREE.VertexColors;
  6658. }
  6659. } else if ( parID === "wrapRGB" ) {
  6660. var v3 = matJSON.parameters[ parID ];
  6661. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6662. }
  6663. }
  6664. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6665. matJSON.parameters.transparent = true;
  6666. }
  6667. if ( matJSON.parameters.normalMap ) {
  6668. var shader = THREE.ShaderUtils.lib[ "normal" ];
  6669. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6670. var diffuse = matJSON.parameters.color;
  6671. var specular = matJSON.parameters.specular;
  6672. var ambient = matJSON.parameters.ambient;
  6673. var shininess = matJSON.parameters.shininess;
  6674. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6675. if ( matJSON.parameters.normalScale ) {
  6676. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6677. }
  6678. if ( matJSON.parameters.map ) {
  6679. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6680. uniforms[ "enableDiffuse" ].value = true;
  6681. }
  6682. if ( matJSON.parameters.envMap ) {
  6683. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6684. uniforms[ "enableReflection" ].value = true;
  6685. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6686. }
  6687. if ( matJSON.parameters.lightMap ) {
  6688. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6689. uniforms[ "enableAO" ].value = true;
  6690. }
  6691. if ( matJSON.parameters.specularMap ) {
  6692. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6693. uniforms[ "enableSpecular" ].value = true;
  6694. }
  6695. if ( matJSON.parameters.displacementMap ) {
  6696. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6697. uniforms[ "enableDisplacement" ].value = true;
  6698. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6699. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6700. }
  6701. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6702. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6703. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6704. uniforms[ "uShininess" ].value = shininess;
  6705. if ( matJSON.parameters.opacity ) {
  6706. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6707. }
  6708. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6709. material = new THREE.ShaderMaterial( parameters );
  6710. } else {
  6711. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6712. }
  6713. result.materials[ matID ] = material;
  6714. }
  6715. // second pass through all materials to initialize MeshFaceMaterials
  6716. // that could be referring to other materials out of order
  6717. for ( matID in data.materials ) {
  6718. matJSON = data.materials[ matID ];
  6719. if ( matJSON.parameters.materials ) {
  6720. var materialArray = [];
  6721. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6722. var label = matJSON.parameters.materials[ i ];
  6723. materialArray.push( result.materials[ label ] );
  6724. }
  6725. result.materials[ matID ].materials = materialArray;
  6726. }
  6727. }
  6728. // objects ( synchronous init of procedural primitives )
  6729. handle_objects();
  6730. // defaults
  6731. if ( result.cameras && data.defaults.camera ) {
  6732. result.currentCamera = result.cameras[ data.defaults.camera ];
  6733. }
  6734. if ( result.fogs && data.defaults.fog ) {
  6735. result.scene.fog = result.fogs[ data.defaults.fog ];
  6736. }
  6737. color = data.defaults.bgcolor;
  6738. result.bgColor = new THREE.Color();
  6739. result.bgColor.setRGB( color[0], color[1], color[2] );
  6740. result.bgColorAlpha = data.defaults.bgalpha;
  6741. // synchronous callback
  6742. scope.callbackSync( result );
  6743. // just in case there are no async elements
  6744. async_callback_gate();
  6745. };
  6746. /**
  6747. * @author mrdoob / http://mrdoob.com/
  6748. */
  6749. THREE.TextureLoader = function () {
  6750. THREE.EventDispatcher.call( this );
  6751. this.crossOrigin = null;
  6752. };
  6753. THREE.TextureLoader.prototype = {
  6754. constructor: THREE.TextureLoader,
  6755. load: function ( url ) {
  6756. var scope = this;
  6757. var image = new Image();
  6758. image.addEventListener( 'load', function () {
  6759. var texture = new THREE.Texture( image );
  6760. texture.needsUpdate = true;
  6761. scope.dispatchEvent( { type: 'load', content: texture } );
  6762. }, false );
  6763. image.addEventListener( 'error', function () {
  6764. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6765. }, false );
  6766. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6767. image.src = url;
  6768. }
  6769. }
  6770. /**
  6771. * @author mrdoob / http://mrdoob.com/
  6772. * @author alteredq / http://alteredqualia.com/
  6773. */
  6774. THREE.Material = function () {
  6775. THREE.EventDispatcher.call( this );
  6776. this.id = THREE.MaterialIdCount ++;
  6777. this.name = '';
  6778. this.side = THREE.FrontSide;
  6779. this.opacity = 1;
  6780. this.transparent = false;
  6781. this.blending = THREE.NormalBlending;
  6782. this.blendSrc = THREE.SrcAlphaFactor;
  6783. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6784. this.blendEquation = THREE.AddEquation;
  6785. this.depthTest = true;
  6786. this.depthWrite = true;
  6787. this.polygonOffset = false;
  6788. this.polygonOffsetFactor = 0;
  6789. this.polygonOffsetUnits = 0;
  6790. this.alphaTest = 0;
  6791. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6792. this.visible = true;
  6793. this.needsUpdate = true;
  6794. };
  6795. THREE.Material.prototype.setValues = function ( values ) {
  6796. if ( values === undefined ) return;
  6797. for ( var key in values ) {
  6798. var newValue = values[ key ];
  6799. if ( newValue === undefined ) {
  6800. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6801. continue;
  6802. }
  6803. if ( key in this ) {
  6804. var currentValue = this[ key ];
  6805. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  6806. currentValue.copy( newValue );
  6807. } else if ( currentValue instanceof THREE.Color ) {
  6808. currentValue.set( newValue );
  6809. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6810. currentValue.copy( newValue );
  6811. } else {
  6812. this[ key ] = newValue;
  6813. }
  6814. }
  6815. }
  6816. };
  6817. THREE.Material.prototype.clone = function ( material ) {
  6818. if ( material === undefined ) material = new THREE.Material();
  6819. material.name = this.name;
  6820. material.side = this.side;
  6821. material.opacity = this.opacity;
  6822. material.transparent = this.transparent;
  6823. material.blending = this.blending;
  6824. material.blendSrc = this.blendSrc;
  6825. material.blendDst = this.blendDst;
  6826. material.blendEquation = this.blendEquation;
  6827. material.depthTest = this.depthTest;
  6828. material.depthWrite = this.depthWrite;
  6829. material.polygonOffset = this.polygonOffset;
  6830. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6831. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6832. material.alphaTest = this.alphaTest;
  6833. material.overdraw = this.overdraw;
  6834. material.visible = this.visible;
  6835. return material;
  6836. };
  6837. THREE.Material.prototype.dispose = function () {
  6838. this.dispatchEvent( { type: 'dispose' } );
  6839. };
  6840. THREE.MaterialIdCount = 0;
  6841. /**
  6842. * @author mrdoob / http://mrdoob.com/
  6843. * @author alteredq / http://alteredqualia.com/
  6844. *
  6845. * parameters = {
  6846. * color: <hex>,
  6847. * opacity: <float>,
  6848. *
  6849. * blending: THREE.NormalBlending,
  6850. * depthTest: <bool>,
  6851. * depthWrite: <bool>,
  6852. *
  6853. * linewidth: <float>,
  6854. * linecap: "round",
  6855. * linejoin: "round",
  6856. *
  6857. * vertexColors: <bool>
  6858. *
  6859. * fog: <bool>
  6860. * }
  6861. */
  6862. THREE.LineBasicMaterial = function ( parameters ) {
  6863. THREE.Material.call( this );
  6864. this.color = new THREE.Color( 0xffffff );
  6865. this.linewidth = 1;
  6866. this.linecap = 'round';
  6867. this.linejoin = 'round';
  6868. this.vertexColors = false;
  6869. this.fog = true;
  6870. this.setValues( parameters );
  6871. };
  6872. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6873. THREE.LineBasicMaterial.prototype.clone = function () {
  6874. var material = new THREE.LineBasicMaterial();
  6875. THREE.Material.prototype.clone.call( this, material );
  6876. material.color.copy( this.color );
  6877. material.linewidth = this.linewidth;
  6878. material.linecap = this.linecap;
  6879. material.linejoin = this.linejoin;
  6880. material.vertexColors = this.vertexColors;
  6881. material.fog = this.fog;
  6882. return material;
  6883. };
  6884. /**
  6885. * @author alteredq / http://alteredqualia.com/
  6886. *
  6887. * parameters = {
  6888. * color: <hex>,
  6889. * opacity: <float>,
  6890. *
  6891. * blending: THREE.NormalBlending,
  6892. * depthTest: <bool>,
  6893. * depthWrite: <bool>,
  6894. *
  6895. * linewidth: <float>,
  6896. *
  6897. * scale: <float>,
  6898. * dashSize: <float>,
  6899. * gapSize: <float>,
  6900. *
  6901. * vertexColors: <bool>
  6902. *
  6903. * fog: <bool>
  6904. * }
  6905. */
  6906. THREE.LineDashedMaterial = function ( parameters ) {
  6907. THREE.Material.call( this );
  6908. this.color = new THREE.Color( 0xffffff );
  6909. this.linewidth = 1;
  6910. this.scale = 1;
  6911. this.dashSize = 3;
  6912. this.gapSize = 1;
  6913. this.vertexColors = false;
  6914. this.fog = true;
  6915. this.setValues( parameters );
  6916. };
  6917. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6918. THREE.LineDashedMaterial.prototype.clone = function () {
  6919. var material = new THREE.LineDashedMaterial();
  6920. THREE.Material.prototype.clone.call( this, material );
  6921. material.color.copy( this.color );
  6922. material.linewidth = this.linewidth;
  6923. material.scale = this.scale;
  6924. material.dashSize = this.dashSize;
  6925. material.gapSize = this.gapSize;
  6926. material.vertexColors = this.vertexColors;
  6927. material.fog = this.fog;
  6928. return material;
  6929. };
  6930. /**
  6931. * @author mrdoob / http://mrdoob.com/
  6932. * @author alteredq / http://alteredqualia.com/
  6933. *
  6934. * parameters = {
  6935. * color: <hex>,
  6936. * opacity: <float>,
  6937. * map: new THREE.Texture( <Image> ),
  6938. *
  6939. * lightMap: new THREE.Texture( <Image> ),
  6940. *
  6941. * specularMap: new THREE.Texture( <Image> ),
  6942. *
  6943. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6944. * combine: THREE.Multiply,
  6945. * reflectivity: <float>,
  6946. * refractionRatio: <float>,
  6947. *
  6948. * shading: THREE.SmoothShading,
  6949. * blending: THREE.NormalBlending,
  6950. * depthTest: <bool>,
  6951. * depthWrite: <bool>,
  6952. *
  6953. * wireframe: <boolean>,
  6954. * wireframeLinewidth: <float>,
  6955. *
  6956. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6957. *
  6958. * skinning: <bool>,
  6959. * morphTargets: <bool>,
  6960. *
  6961. * fog: <bool>
  6962. * }
  6963. */
  6964. THREE.MeshBasicMaterial = function ( parameters ) {
  6965. THREE.Material.call( this );
  6966. this.color = new THREE.Color( 0xffffff ); // emissive
  6967. this.map = null;
  6968. this.lightMap = null;
  6969. this.specularMap = null;
  6970. this.envMap = null;
  6971. this.combine = THREE.MultiplyOperation;
  6972. this.reflectivity = 1;
  6973. this.refractionRatio = 0.98;
  6974. this.fog = true;
  6975. this.shading = THREE.SmoothShading;
  6976. this.wireframe = false;
  6977. this.wireframeLinewidth = 1;
  6978. this.wireframeLinecap = 'round';
  6979. this.wireframeLinejoin = 'round';
  6980. this.vertexColors = THREE.NoColors;
  6981. this.skinning = false;
  6982. this.morphTargets = false;
  6983. this.setValues( parameters );
  6984. };
  6985. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6986. THREE.MeshBasicMaterial.prototype.clone = function () {
  6987. var material = new THREE.MeshBasicMaterial();
  6988. THREE.Material.prototype.clone.call( this, material );
  6989. material.color.copy( this.color );
  6990. material.map = this.map;
  6991. material.lightMap = this.lightMap;
  6992. material.specularMap = this.specularMap;
  6993. material.envMap = this.envMap;
  6994. material.combine = this.combine;
  6995. material.reflectivity = this.reflectivity;
  6996. material.refractionRatio = this.refractionRatio;
  6997. material.fog = this.fog;
  6998. material.shading = this.shading;
  6999. material.wireframe = this.wireframe;
  7000. material.wireframeLinewidth = this.wireframeLinewidth;
  7001. material.wireframeLinecap = this.wireframeLinecap;
  7002. material.wireframeLinejoin = this.wireframeLinejoin;
  7003. material.vertexColors = this.vertexColors;
  7004. material.skinning = this.skinning;
  7005. material.morphTargets = this.morphTargets;
  7006. return material;
  7007. };
  7008. /**
  7009. * @author mrdoob / http://mrdoob.com/
  7010. * @author alteredq / http://alteredqualia.com/
  7011. *
  7012. * parameters = {
  7013. * color: <hex>,
  7014. * ambient: <hex>,
  7015. * emissive: <hex>,
  7016. * opacity: <float>,
  7017. *
  7018. * map: new THREE.Texture( <Image> ),
  7019. *
  7020. * lightMap: new THREE.Texture( <Image> ),
  7021. *
  7022. * specularMap: new THREE.Texture( <Image> ),
  7023. *
  7024. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7025. * combine: THREE.Multiply,
  7026. * reflectivity: <float>,
  7027. * refractionRatio: <float>,
  7028. *
  7029. * shading: THREE.SmoothShading,
  7030. * blending: THREE.NormalBlending,
  7031. * depthTest: <bool>,
  7032. * depthWrite: <bool>,
  7033. *
  7034. * wireframe: <boolean>,
  7035. * wireframeLinewidth: <float>,
  7036. *
  7037. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7038. *
  7039. * skinning: <bool>,
  7040. * morphTargets: <bool>,
  7041. * morphNormals: <bool>,
  7042. *
  7043. * fog: <bool>
  7044. * }
  7045. */
  7046. THREE.MeshLambertMaterial = function ( parameters ) {
  7047. THREE.Material.call( this );
  7048. this.color = new THREE.Color( 0xffffff ); // diffuse
  7049. this.ambient = new THREE.Color( 0xffffff );
  7050. this.emissive = new THREE.Color( 0x000000 );
  7051. this.wrapAround = false;
  7052. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7053. this.map = null;
  7054. this.lightMap = null;
  7055. this.specularMap = null;
  7056. this.envMap = null;
  7057. this.combine = THREE.MultiplyOperation;
  7058. this.reflectivity = 1;
  7059. this.refractionRatio = 0.98;
  7060. this.fog = true;
  7061. this.shading = THREE.SmoothShading;
  7062. this.wireframe = false;
  7063. this.wireframeLinewidth = 1;
  7064. this.wireframeLinecap = 'round';
  7065. this.wireframeLinejoin = 'round';
  7066. this.vertexColors = THREE.NoColors;
  7067. this.skinning = false;
  7068. this.morphTargets = false;
  7069. this.morphNormals = false;
  7070. this.setValues( parameters );
  7071. };
  7072. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7073. THREE.MeshLambertMaterial.prototype.clone = function () {
  7074. var material = new THREE.MeshLambertMaterial();
  7075. THREE.Material.prototype.clone.call( this, material );
  7076. material.color.copy( this.color );
  7077. material.ambient.copy( this.ambient );
  7078. material.emissive.copy( this.emissive );
  7079. material.wrapAround = this.wrapAround;
  7080. material.wrapRGB.copy( this.wrapRGB );
  7081. material.map = this.map;
  7082. material.lightMap = this.lightMap;
  7083. material.specularMap = this.specularMap;
  7084. material.envMap = this.envMap;
  7085. material.combine = this.combine;
  7086. material.reflectivity = this.reflectivity;
  7087. material.refractionRatio = this.refractionRatio;
  7088. material.fog = this.fog;
  7089. material.shading = this.shading;
  7090. material.wireframe = this.wireframe;
  7091. material.wireframeLinewidth = this.wireframeLinewidth;
  7092. material.wireframeLinecap = this.wireframeLinecap;
  7093. material.wireframeLinejoin = this.wireframeLinejoin;
  7094. material.vertexColors = this.vertexColors;
  7095. material.skinning = this.skinning;
  7096. material.morphTargets = this.morphTargets;
  7097. material.morphNormals = this.morphNormals;
  7098. return material;
  7099. };
  7100. /**
  7101. * @author mrdoob / http://mrdoob.com/
  7102. * @author alteredq / http://alteredqualia.com/
  7103. *
  7104. * parameters = {
  7105. * color: <hex>,
  7106. * ambient: <hex>,
  7107. * emissive: <hex>,
  7108. * specular: <hex>,
  7109. * shininess: <float>,
  7110. * opacity: <float>,
  7111. *
  7112. * map: new THREE.Texture( <Image> ),
  7113. *
  7114. * lightMap: new THREE.Texture( <Image> ),
  7115. *
  7116. * bumpMap: new THREE.Texture( <Image> ),
  7117. * bumpScale: <float>,
  7118. *
  7119. * normalMap: new THREE.Texture( <Image> ),
  7120. * normalScale: <Vector2>,
  7121. *
  7122. * specularMap: new THREE.Texture( <Image> ),
  7123. *
  7124. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7125. * combine: THREE.Multiply,
  7126. * reflectivity: <float>,
  7127. * refractionRatio: <float>,
  7128. *
  7129. * shading: THREE.SmoothShading,
  7130. * blending: THREE.NormalBlending,
  7131. * depthTest: <bool>,
  7132. * depthWrite: <bool>,
  7133. *
  7134. * wireframe: <boolean>,
  7135. * wireframeLinewidth: <float>,
  7136. *
  7137. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7138. *
  7139. * skinning: <bool>,
  7140. * morphTargets: <bool>,
  7141. * morphNormals: <bool>,
  7142. *
  7143. * fog: <bool>
  7144. * }
  7145. */
  7146. THREE.MeshPhongMaterial = function ( parameters ) {
  7147. THREE.Material.call( this );
  7148. this.color = new THREE.Color( 0xffffff ); // diffuse
  7149. this.ambient = new THREE.Color( 0xffffff );
  7150. this.emissive = new THREE.Color( 0x000000 );
  7151. this.specular = new THREE.Color( 0x111111 );
  7152. this.shininess = 30;
  7153. this.metal = false;
  7154. this.perPixel = true;
  7155. this.wrapAround = false;
  7156. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7157. this.map = null;
  7158. this.lightMap = null;
  7159. this.bumpMap = null;
  7160. this.bumpScale = 1;
  7161. this.normalMap = null;
  7162. this.normalScale = new THREE.Vector2( 1, 1 );
  7163. this.specularMap = null;
  7164. this.envMap = null;
  7165. this.combine = THREE.MultiplyOperation;
  7166. this.reflectivity = 1;
  7167. this.refractionRatio = 0.98;
  7168. this.fog = true;
  7169. this.shading = THREE.SmoothShading;
  7170. this.wireframe = false;
  7171. this.wireframeLinewidth = 1;
  7172. this.wireframeLinecap = 'round';
  7173. this.wireframeLinejoin = 'round';
  7174. this.vertexColors = THREE.NoColors;
  7175. this.skinning = false;
  7176. this.morphTargets = false;
  7177. this.morphNormals = false;
  7178. this.setValues( parameters );
  7179. };
  7180. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7181. THREE.MeshPhongMaterial.prototype.clone = function () {
  7182. var material = new THREE.MeshPhongMaterial();
  7183. THREE.Material.prototype.clone.call( this, material );
  7184. material.color.copy( this.color );
  7185. material.ambient.copy( this.ambient );
  7186. material.emissive.copy( this.emissive );
  7187. material.specular.copy( this.specular );
  7188. material.shininess = this.shininess;
  7189. material.metal = this.metal;
  7190. material.perPixel = this.perPixel;
  7191. material.wrapAround = this.wrapAround;
  7192. material.wrapRGB.copy( this.wrapRGB );
  7193. material.map = this.map;
  7194. material.lightMap = this.lightMap;
  7195. material.bumpMap = this.bumpMap;
  7196. material.bumpScale = this.bumpScale;
  7197. material.normalMap = this.normalMap;
  7198. material.normalScale.copy( this.normalScale );
  7199. material.specularMap = this.specularMap;
  7200. material.envMap = this.envMap;
  7201. material.combine = this.combine;
  7202. material.reflectivity = this.reflectivity;
  7203. material.refractionRatio = this.refractionRatio;
  7204. material.fog = this.fog;
  7205. material.shading = this.shading;
  7206. material.wireframe = this.wireframe;
  7207. material.wireframeLinewidth = this.wireframeLinewidth;
  7208. material.wireframeLinecap = this.wireframeLinecap;
  7209. material.wireframeLinejoin = this.wireframeLinejoin;
  7210. material.vertexColors = this.vertexColors;
  7211. material.skinning = this.skinning;
  7212. material.morphTargets = this.morphTargets;
  7213. material.morphNormals = this.morphNormals;
  7214. return material;
  7215. };
  7216. /**
  7217. * @author mrdoob / http://mrdoob.com/
  7218. * @author alteredq / http://alteredqualia.com/
  7219. *
  7220. * parameters = {
  7221. * opacity: <float>,
  7222. *
  7223. * blending: THREE.NormalBlending,
  7224. * depthTest: <bool>,
  7225. * depthWrite: <bool>,
  7226. *
  7227. * wireframe: <boolean>,
  7228. * wireframeLinewidth: <float>
  7229. * }
  7230. */
  7231. THREE.MeshDepthMaterial = function ( parameters ) {
  7232. THREE.Material.call( this );
  7233. this.wireframe = false;
  7234. this.wireframeLinewidth = 1;
  7235. this.setValues( parameters );
  7236. };
  7237. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7238. THREE.MeshDepthMaterial.prototype.clone = function () {
  7239. var material = new THREE.LineBasicMaterial();
  7240. THREE.Material.prototype.clone.call( this, material );
  7241. material.wireframe = this.wireframe;
  7242. material.wireframeLinewidth = this.wireframeLinewidth;
  7243. return material;
  7244. };
  7245. /**
  7246. * @author mrdoob / http://mrdoob.com/
  7247. *
  7248. * parameters = {
  7249. * opacity: <float>,
  7250. *
  7251. * shading: THREE.FlatShading,
  7252. * blending: THREE.NormalBlending,
  7253. * depthTest: <bool>,
  7254. * depthWrite: <bool>,
  7255. *
  7256. * wireframe: <boolean>,
  7257. * wireframeLinewidth: <float>
  7258. * }
  7259. */
  7260. THREE.MeshNormalMaterial = function ( parameters ) {
  7261. THREE.Material.call( this, parameters );
  7262. this.shading = THREE.FlatShading;
  7263. this.wireframe = false;
  7264. this.wireframeLinewidth = 1;
  7265. this.setValues( parameters );
  7266. };
  7267. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7268. THREE.MeshNormalMaterial.prototype.clone = function () {
  7269. var material = new THREE.MeshNormalMaterial();
  7270. THREE.Material.prototype.clone.call( this, material );
  7271. material.shading = this.shading;
  7272. material.wireframe = this.wireframe;
  7273. material.wireframeLinewidth = this.wireframeLinewidth;
  7274. return material;
  7275. };
  7276. /**
  7277. * @author mrdoob / http://mrdoob.com/
  7278. */
  7279. THREE.MeshFaceMaterial = function ( materials ) {
  7280. this.materials = materials instanceof Array ? materials : [];
  7281. };
  7282. THREE.MeshFaceMaterial.prototype.clone = function () {
  7283. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7284. };
  7285. /**
  7286. * @author mrdoob / http://mrdoob.com/
  7287. * @author alteredq / http://alteredqualia.com/
  7288. *
  7289. * parameters = {
  7290. * color: <hex>,
  7291. * opacity: <float>,
  7292. * map: new THREE.Texture( <Image> ),
  7293. *
  7294. * size: <float>,
  7295. *
  7296. * blending: THREE.NormalBlending,
  7297. * depthTest: <bool>,
  7298. * depthWrite: <bool>,
  7299. *
  7300. * vertexColors: <bool>,
  7301. *
  7302. * fog: <bool>
  7303. * }
  7304. */
  7305. THREE.ParticleBasicMaterial = function ( parameters ) {
  7306. THREE.Material.call( this );
  7307. this.color = new THREE.Color( 0xffffff );
  7308. this.map = null;
  7309. this.size = 1;
  7310. this.sizeAttenuation = true;
  7311. this.vertexColors = false;
  7312. this.fog = true;
  7313. this.setValues( parameters );
  7314. };
  7315. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7316. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7317. var material = new THREE.ParticleBasicMaterial();
  7318. THREE.Material.prototype.clone.call( this, material );
  7319. material.color.copy( this.color );
  7320. material.map = this.map;
  7321. material.size = this.size;
  7322. material.sizeAttenuation = this.sizeAttenuation;
  7323. material.vertexColors = this.vertexColors;
  7324. material.fog = this.fog;
  7325. return material;
  7326. };
  7327. /**
  7328. * @author mrdoob / http://mrdoob.com/
  7329. *
  7330. * parameters = {
  7331. * color: <hex>,
  7332. * program: <function>,
  7333. * opacity: <float>,
  7334. * blending: THREE.NormalBlending
  7335. * }
  7336. */
  7337. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7338. THREE.Material.call( this );
  7339. this.color = new THREE.Color( 0xffffff );
  7340. this.program = function ( context, color ) {};
  7341. this.setValues( parameters );
  7342. };
  7343. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7344. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7345. var material = new THREE.ParticleCanvasMaterial();
  7346. THREE.Material.prototype.clone.call( this, material );
  7347. material.color.copy( this.color );
  7348. material.program = this.program;
  7349. return material;
  7350. };
  7351. /**
  7352. * @author alteredq / http://alteredqualia.com/
  7353. *
  7354. * parameters = {
  7355. * fragmentShader: <string>,
  7356. * vertexShader: <string>,
  7357. *
  7358. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7359. *
  7360. * defines: { "label" : "value" },
  7361. *
  7362. * shading: THREE.SmoothShading,
  7363. * blending: THREE.NormalBlending,
  7364. * depthTest: <bool>,
  7365. * depthWrite: <bool>,
  7366. *
  7367. * wireframe: <boolean>,
  7368. * wireframeLinewidth: <float>,
  7369. *
  7370. * lights: <bool>,
  7371. *
  7372. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7373. *
  7374. * skinning: <bool>,
  7375. * morphTargets: <bool>,
  7376. * morphNormals: <bool>,
  7377. *
  7378. * fog: <bool>
  7379. * }
  7380. */
  7381. THREE.ShaderMaterial = function ( parameters ) {
  7382. THREE.Material.call( this );
  7383. this.fragmentShader = "void main() {}";
  7384. this.vertexShader = "void main() {}";
  7385. this.uniforms = {};
  7386. this.defines = {};
  7387. this.attributes = null;
  7388. this.shading = THREE.SmoothShading;
  7389. this.wireframe = false;
  7390. this.wireframeLinewidth = 1;
  7391. this.fog = false; // set to use scene fog
  7392. this.lights = false; // set to use scene lights
  7393. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7394. this.skinning = false; // set to use skinning attribute streams
  7395. this.morphTargets = false; // set to use morph targets
  7396. this.morphNormals = false; // set to use morph normals
  7397. this.setValues( parameters );
  7398. };
  7399. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7400. THREE.ShaderMaterial.prototype.clone = function () {
  7401. var material = new THREE.ShaderMaterial();
  7402. THREE.Material.prototype.clone.call( this, material );
  7403. material.fragmentShader = this.fragmentShader;
  7404. material.vertexShader = this.vertexShader;
  7405. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7406. material.attributes = this.attributes;
  7407. material.defines = this.defines;
  7408. material.shading = this.shading;
  7409. material.wireframe = this.wireframe;
  7410. material.wireframeLinewidth = this.wireframeLinewidth;
  7411. material.fog = this.fog;
  7412. material.lights = this.lights;
  7413. material.vertexColors = this.vertexColors;
  7414. material.skinning = this.skinning;
  7415. material.morphTargets = this.morphTargets;
  7416. material.morphNormals = this.morphNormals;
  7417. return material;
  7418. };
  7419. /**
  7420. * @author alteredq / http://alteredqualia.com/
  7421. *
  7422. * parameters = {
  7423. * color: <hex>,
  7424. * opacity: <float>,
  7425. * map: new THREE.Texture( <Image> ),
  7426. *
  7427. * blending: THREE.NormalBlending,
  7428. * depthTest: <bool>,
  7429. * depthWrite: <bool>,
  7430. *
  7431. * useScreenCoordinates: <bool>,
  7432. * sizeAttenuation: <bool>,
  7433. * scaleByViewport: <bool>,
  7434. * alignment: THREE.SpriteAlignment.center,
  7435. *
  7436. * uvOffset: new THREE.Vector2(),
  7437. * uvScale: new THREE.Vector2(),
  7438. *
  7439. * fog: <bool>
  7440. * }
  7441. */
  7442. THREE.SpriteMaterial = function ( parameters ) {
  7443. THREE.Material.call( this );
  7444. // defaults
  7445. this.color = new THREE.Color( 0xffffff );
  7446. this.map = new THREE.Texture();
  7447. this.useScreenCoordinates = true;
  7448. this.depthTest = !this.useScreenCoordinates;
  7449. this.sizeAttenuation = !this.useScreenCoordinates;
  7450. this.scaleByViewport = !this.sizeAttenuation;
  7451. this.alignment = THREE.SpriteAlignment.center.clone();
  7452. this.fog = false;
  7453. this.uvOffset = new THREE.Vector2( 0, 0 );
  7454. this.uvScale = new THREE.Vector2( 1, 1 );
  7455. // set parameters
  7456. this.setValues( parameters );
  7457. // override coupled defaults if not specified explicitly by parameters
  7458. parameters = parameters || {};
  7459. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7460. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7461. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7462. };
  7463. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7464. THREE.SpriteMaterial.prototype.clone = function () {
  7465. var material = new THREE.SpriteMaterial();
  7466. THREE.Material.prototype.clone.call( this, material );
  7467. material.color.copy( this.color );
  7468. material.map = this.map;
  7469. material.useScreenCoordinates = this.useScreenCoordinates;
  7470. material.sizeAttenuation = this.sizeAttenuation;
  7471. material.scaleByViewport = this.scaleByViewport;
  7472. material.alignment.copy( this.alignment );
  7473. material.uvOffset.copy( this.uvOffset );
  7474. material.uvScale.copy( this.uvScale );
  7475. material.fog = this.fog;
  7476. return material;
  7477. };
  7478. // Alignment enums
  7479. THREE.SpriteAlignment = {};
  7480. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7481. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7482. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7483. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7484. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7485. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7486. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7487. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7488. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7489. /**
  7490. * @author mrdoob / http://mrdoob.com/
  7491. * @author alteredq / http://alteredqualia.com/
  7492. * @author szimek / https://github.com/szimek/
  7493. */
  7494. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7495. THREE.EventDispatcher.call( this );
  7496. this.id = THREE.TextureIdCount ++;
  7497. this.name = '';
  7498. this.image = image;
  7499. this.mipmaps = [];
  7500. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7501. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7502. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7503. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7504. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7505. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7506. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7507. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7508. this.offset = new THREE.Vector2( 0, 0 );
  7509. this.repeat = new THREE.Vector2( 1, 1 );
  7510. this.generateMipmaps = true;
  7511. this.premultiplyAlpha = false;
  7512. this.flipY = true;
  7513. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7514. this.needsUpdate = false;
  7515. this.onUpdate = null;
  7516. };
  7517. THREE.Texture.prototype = {
  7518. constructor: THREE.Texture,
  7519. clone: function ( texture ) {
  7520. if ( texture === undefined ) texture = new THREE.Texture();
  7521. texture.image = this.image;
  7522. texture.mipmaps = this.mipmaps.slice(0);
  7523. texture.mapping = this.mapping;
  7524. texture.wrapS = this.wrapS;
  7525. texture.wrapT = this.wrapT;
  7526. texture.magFilter = this.magFilter;
  7527. texture.minFilter = this.minFilter;
  7528. texture.anisotropy = this.anisotropy;
  7529. texture.format = this.format;
  7530. texture.type = this.type;
  7531. texture.offset.copy( this.offset );
  7532. texture.repeat.copy( this.repeat );
  7533. texture.generateMipmaps = this.generateMipmaps;
  7534. texture.premultiplyAlpha = this.premultiplyAlpha;
  7535. texture.flipY = this.flipY;
  7536. texture.unpackAlignment = this.unpackAlignment;
  7537. return texture;
  7538. },
  7539. dispose: function () {
  7540. this.dispatchEvent( { type: 'dispose' } );
  7541. }
  7542. };
  7543. THREE.TextureIdCount = 0;
  7544. /**
  7545. * @author alteredq / http://alteredqualia.com/
  7546. */
  7547. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7548. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7549. this.image = { width: width, height: height };
  7550. this.mipmaps = mipmaps;
  7551. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7552. };
  7553. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7554. THREE.CompressedTexture.prototype.clone = function () {
  7555. var texture = new THREE.CompressedTexture();
  7556. THREE.Texture.prototype.clone.call( this, texture );
  7557. return texture;
  7558. };
  7559. /**
  7560. * @author alteredq / http://alteredqualia.com/
  7561. */
  7562. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7563. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7564. this.image = { data: data, width: width, height: height };
  7565. };
  7566. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7567. THREE.DataTexture.prototype.clone = function () {
  7568. var texture = new THREE.DataTexture();
  7569. THREE.Texture.prototype.clone.call( this, texture );
  7570. return texture;
  7571. };
  7572. /**
  7573. * @author mrdoob / http://mrdoob.com/
  7574. */
  7575. THREE.Particle = function ( material ) {
  7576. THREE.Object3D.call( this );
  7577. this.material = material;
  7578. };
  7579. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7580. THREE.Particle.prototype.clone = function ( object ) {
  7581. if ( object === undefined ) object = new THREE.Particle( this.material );
  7582. THREE.Object3D.prototype.clone.call( this, object );
  7583. return object;
  7584. };
  7585. /**
  7586. * @author alteredq / http://alteredqualia.com/
  7587. */
  7588. THREE.ParticleSystem = function ( geometry, material ) {
  7589. THREE.Object3D.call( this );
  7590. this.geometry = geometry;
  7591. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7592. this.sortParticles = false;
  7593. if ( this.geometry ) {
  7594. // calc bound radius
  7595. if( this.geometry.boundingSphere === null ) {
  7596. this.geometry.computeBoundingSphere();
  7597. }
  7598. }
  7599. this.frustumCulled = false;
  7600. };
  7601. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7602. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7603. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7604. object.sortParticles = this.sortParticles;
  7605. THREE.Object3D.prototype.clone.call( this, object );
  7606. return object;
  7607. };
  7608. /**
  7609. * @author mrdoob / http://mrdoob.com/
  7610. */
  7611. THREE.Line = function ( geometry, material, type ) {
  7612. THREE.Object3D.call( this );
  7613. this.geometry = geometry;
  7614. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7615. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7616. if ( this.geometry ) {
  7617. if ( ! this.geometry.boundingSphere ) {
  7618. this.geometry.computeBoundingSphere();
  7619. }
  7620. }
  7621. };
  7622. THREE.LineStrip = 0;
  7623. THREE.LinePieces = 1;
  7624. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7625. THREE.Line.prototype.clone = function ( object ) {
  7626. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7627. THREE.Object3D.prototype.clone.call( this, object );
  7628. return object;
  7629. };
  7630. /**
  7631. * @author mrdoob / http://mrdoob.com/
  7632. * @author alteredq / http://alteredqualia.com/
  7633. * @author mikael emtinger / http://gomo.se/
  7634. */
  7635. THREE.Mesh = function ( geometry, material ) {
  7636. THREE.Object3D.call( this );
  7637. this.geometry = geometry;
  7638. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7639. if ( this.geometry ) {
  7640. // calc bound radius
  7641. if ( this.geometry.boundingSphere === null ) {
  7642. this.geometry.computeBoundingSphere();
  7643. }
  7644. // setup morph targets
  7645. if ( this.geometry.morphTargets.length ) {
  7646. this.morphTargetBase = -1;
  7647. this.morphTargetForcedOrder = [];
  7648. this.morphTargetInfluences = [];
  7649. this.morphTargetDictionary = {};
  7650. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  7651. this.morphTargetInfluences.push( 0 );
  7652. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7653. }
  7654. }
  7655. }
  7656. }
  7657. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7658. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7659. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7660. return this.morphTargetDictionary[ name ];
  7661. }
  7662. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7663. return 0;
  7664. };
  7665. THREE.Mesh.prototype.clone = function ( object ) {
  7666. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7667. THREE.Object3D.prototype.clone.call( this, object );
  7668. return object;
  7669. };
  7670. /**
  7671. * @author mikael emtinger / http://gomo.se/
  7672. * @author alteredq / http://alteredqualia.com/
  7673. */
  7674. THREE.Bone = function( belongsToSkin ) {
  7675. THREE.Object3D.call( this );
  7676. this.skin = belongsToSkin;
  7677. this.skinMatrix = new THREE.Matrix4();
  7678. };
  7679. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7680. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  7681. // update local
  7682. if ( this.matrixAutoUpdate ) {
  7683. forceUpdate |= this.updateMatrix();
  7684. }
  7685. // update skin matrix
  7686. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7687. if( parentSkinMatrix ) {
  7688. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  7689. } else {
  7690. this.skinMatrix.copy( this.matrix );
  7691. }
  7692. this.matrixWorldNeedsUpdate = false;
  7693. forceUpdate = true;
  7694. }
  7695. // update children
  7696. var child, i, l = this.children.length;
  7697. for ( i = 0; i < l; i ++ ) {
  7698. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7699. }
  7700. };
  7701. /**
  7702. * @author mikael emtinger / http://gomo.se/
  7703. * @author alteredq / http://alteredqualia.com/
  7704. */
  7705. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7706. THREE.Mesh.call( this, geometry, material );
  7707. //
  7708. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7709. // init bones
  7710. this.identityMatrix = new THREE.Matrix4();
  7711. this.bones = [];
  7712. this.boneMatrices = [];
  7713. var b, bone, gbone, p, q, s;
  7714. if ( this.geometry && this.geometry.bones !== undefined ) {
  7715. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7716. gbone = this.geometry.bones[ b ];
  7717. p = gbone.pos;
  7718. q = gbone.rotq;
  7719. s = gbone.scl;
  7720. bone = this.addBone();
  7721. bone.name = gbone.name;
  7722. bone.position.set( p[0], p[1], p[2] );
  7723. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7724. bone.useQuaternion = true;
  7725. if ( s !== undefined ) {
  7726. bone.scale.set( s[0], s[1], s[2] );
  7727. } else {
  7728. bone.scale.set( 1, 1, 1 );
  7729. }
  7730. }
  7731. for ( b = 0; b < this.bones.length; b ++ ) {
  7732. gbone = this.geometry.bones[ b ];
  7733. bone = this.bones[ b ];
  7734. if ( gbone.parent === -1 ) {
  7735. this.add( bone );
  7736. } else {
  7737. this.bones[ gbone.parent ].add( bone );
  7738. }
  7739. }
  7740. //
  7741. var nBones = this.bones.length;
  7742. if ( this.useVertexTexture ) {
  7743. // layout (1 matrix = 4 pixels)
  7744. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7745. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7746. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7747. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7748. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7749. var size;
  7750. if ( nBones > 256 )
  7751. size = 64;
  7752. else if ( nBones > 64 )
  7753. size = 32;
  7754. else if ( nBones > 16 )
  7755. size = 16;
  7756. else
  7757. size = 8;
  7758. this.boneTextureWidth = size;
  7759. this.boneTextureHeight = size;
  7760. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7761. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7762. this.boneTexture.minFilter = THREE.NearestFilter;
  7763. this.boneTexture.magFilter = THREE.NearestFilter;
  7764. this.boneTexture.generateMipmaps = false;
  7765. this.boneTexture.flipY = false;
  7766. } else {
  7767. this.boneMatrices = new Float32Array( 16 * nBones );
  7768. }
  7769. this.pose();
  7770. }
  7771. };
  7772. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7773. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7774. if ( bone === undefined ) {
  7775. bone = new THREE.Bone( this );
  7776. }
  7777. this.bones.push( bone );
  7778. return bone;
  7779. };
  7780. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7781. this.matrixAutoUpdate && this.updateMatrix();
  7782. // update matrixWorld
  7783. if ( this.matrixWorldNeedsUpdate || force ) {
  7784. if ( this.parent ) {
  7785. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  7786. } else {
  7787. this.matrixWorld.copy( this.matrix );
  7788. }
  7789. this.matrixWorldNeedsUpdate = false;
  7790. force = true;
  7791. }
  7792. // update children
  7793. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7794. var child = this.children[ i ];
  7795. if ( child instanceof THREE.Bone ) {
  7796. child.update( this.identityMatrix, false );
  7797. } else {
  7798. child.updateMatrixWorld( true );
  7799. }
  7800. }
  7801. // make a snapshot of the bones' rest position
  7802. if ( this.boneInverses == undefined ) {
  7803. this.boneInverses = [];
  7804. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7805. var inverse = new THREE.Matrix4();
  7806. inverse.getInverse( this.bones[ b ].skinMatrix );
  7807. this.boneInverses.push( inverse );
  7808. }
  7809. }
  7810. // flatten bone matrices to array
  7811. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7812. // compute the offset between the current and the original transform;
  7813. //TODO: we could get rid of this multiplication step if the skinMatrix
  7814. // was already representing the offset; however, this requires some
  7815. // major changes to the animation system
  7816. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7817. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7818. }
  7819. if ( this.useVertexTexture ) {
  7820. this.boneTexture.needsUpdate = true;
  7821. }
  7822. };
  7823. THREE.SkinnedMesh.prototype.pose = function() {
  7824. this.updateMatrixWorld( true );
  7825. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7826. // normalize weights
  7827. var sw = this.geometry.skinWeights[ i ];
  7828. var scale = 1.0 / sw.lengthManhattan();
  7829. if ( scale !== Infinity ) {
  7830. sw.multiplyScalar( scale );
  7831. } else {
  7832. sw.set( 1 ); // this will be normalized by the shader anyway
  7833. }
  7834. }
  7835. };
  7836. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7837. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7838. THREE.Mesh.prototype.clone.call( this, object );
  7839. return object;
  7840. };
  7841. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7842. /**
  7843. * @author alteredq / http://alteredqualia.com/
  7844. */
  7845. THREE.MorphAnimMesh = function ( geometry, material ) {
  7846. THREE.Mesh.call( this, geometry, material );
  7847. // API
  7848. this.duration = 1000; // milliseconds
  7849. this.mirroredLoop = false;
  7850. this.time = 0;
  7851. // internals
  7852. this.lastKeyframe = 0;
  7853. this.currentKeyframe = 0;
  7854. this.direction = 1;
  7855. this.directionBackwards = false;
  7856. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7857. };
  7858. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7859. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7860. this.startKeyframe = start;
  7861. this.endKeyframe = end;
  7862. this.length = this.endKeyframe - this.startKeyframe + 1;
  7863. };
  7864. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7865. this.direction = 1;
  7866. this.directionBackwards = false;
  7867. };
  7868. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7869. this.direction = -1;
  7870. this.directionBackwards = true;
  7871. };
  7872. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7873. var geometry = this.geometry;
  7874. if ( ! geometry.animations ) geometry.animations = {};
  7875. var firstAnimation, animations = geometry.animations;
  7876. var pattern = /([a-z]+)(\d+)/;
  7877. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7878. var morph = geometry.morphTargets[ i ];
  7879. var parts = morph.name.match( pattern );
  7880. if ( parts && parts.length > 1 ) {
  7881. var label = parts[ 1 ];
  7882. var num = parts[ 2 ];
  7883. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7884. var animation = animations[ label ];
  7885. if ( i < animation.start ) animation.start = i;
  7886. if ( i > animation.end ) animation.end = i;
  7887. if ( ! firstAnimation ) firstAnimation = label;
  7888. }
  7889. }
  7890. geometry.firstAnimation = firstAnimation;
  7891. };
  7892. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7893. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7894. this.geometry.animations[ label ] = { start: start, end: end };
  7895. };
  7896. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7897. var animation = this.geometry.animations[ label ];
  7898. if ( animation ) {
  7899. this.setFrameRange( animation.start, animation.end );
  7900. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7901. this.time = 0;
  7902. } else {
  7903. console.warn( "animation[" + label + "] undefined" );
  7904. }
  7905. };
  7906. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7907. var frameTime = this.duration / this.length;
  7908. this.time += this.direction * delta;
  7909. if ( this.mirroredLoop ) {
  7910. if ( this.time > this.duration || this.time < 0 ) {
  7911. this.direction *= -1;
  7912. if ( this.time > this.duration ) {
  7913. this.time = this.duration;
  7914. this.directionBackwards = true;
  7915. }
  7916. if ( this.time < 0 ) {
  7917. this.time = 0;
  7918. this.directionBackwards = false;
  7919. }
  7920. }
  7921. } else {
  7922. this.time = this.time % this.duration;
  7923. if ( this.time < 0 ) this.time += this.duration;
  7924. }
  7925. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7926. if ( keyframe !== this.currentKeyframe ) {
  7927. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7928. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7929. this.morphTargetInfluences[ keyframe ] = 0;
  7930. this.lastKeyframe = this.currentKeyframe;
  7931. this.currentKeyframe = keyframe;
  7932. }
  7933. var mix = ( this.time % frameTime ) / frameTime;
  7934. if ( this.directionBackwards ) {
  7935. mix = 1 - mix;
  7936. }
  7937. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7938. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7939. };
  7940. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7941. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7942. object.duration = this.duration;
  7943. object.mirroredLoop = this.mirroredLoop;
  7944. object.time = this.time;
  7945. object.lastKeyframe = this.lastKeyframe;
  7946. object.currentKeyframe = this.currentKeyframe;
  7947. object.direction = this.direction;
  7948. object.directionBackwards = this.directionBackwards;
  7949. THREE.Mesh.prototype.clone.call( this, object );
  7950. return object;
  7951. };
  7952. /**
  7953. * @author alteredq / http://alteredqualia.com/
  7954. */
  7955. THREE.Ribbon = function ( geometry, material ) {
  7956. THREE.Object3D.call( this );
  7957. this.geometry = geometry;
  7958. this.material = material;
  7959. };
  7960. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7961. THREE.Ribbon.prototype.clone = function ( object ) {
  7962. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7963. THREE.Object3D.prototype.clone.call( this, object );
  7964. return object;
  7965. };
  7966. /**
  7967. * @author mikael emtinger / http://gomo.se/
  7968. * @author alteredq / http://alteredqualia.com/
  7969. * @author mrdoob / http://mrdoob.com/
  7970. */
  7971. THREE.LOD = function () {
  7972. THREE.Object3D.call( this );
  7973. this.LODs = [];
  7974. };
  7975. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7976. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7977. if ( visibleAtDistance === undefined ) {
  7978. visibleAtDistance = 0;
  7979. }
  7980. visibleAtDistance = Math.abs( visibleAtDistance );
  7981. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7982. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7983. break;
  7984. }
  7985. }
  7986. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7987. this.add( object3D );
  7988. };
  7989. THREE.LOD.prototype.update = function ( camera ) {
  7990. if ( this.LODs.length > 1 ) {
  7991. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7992. var inverse = camera.matrixWorldInverse;
  7993. 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] );
  7994. this.LODs[ 0 ].object3D.visible = true;
  7995. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7996. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7997. this.LODs[ l - 1 ].object3D.visible = false;
  7998. this.LODs[ l ].object3D.visible = true;
  7999. } else {
  8000. break;
  8001. }
  8002. }
  8003. for( ; l < this.LODs.length; l ++ ) {
  8004. this.LODs[ l ].object3D.visible = false;
  8005. }
  8006. }
  8007. };
  8008. THREE.LOD.prototype.clone = function () {
  8009. // TODO
  8010. };
  8011. /**
  8012. * @author mikael emtinger / http://gomo.se/
  8013. * @author alteredq / http://alteredqualia.com/
  8014. */
  8015. THREE.Sprite = function ( material ) {
  8016. THREE.Object3D.call( this );
  8017. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8018. this.rotation3d = this.rotation;
  8019. this.rotation = 0;
  8020. };
  8021. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8022. /*
  8023. * Custom update matrix
  8024. */
  8025. THREE.Sprite.prototype.updateMatrix = function () {
  8026. this.matrix.setPosition( this.position );
  8027. this.rotation3d.set( 0, 0, this.rotation );
  8028. this.matrix.setRotationFromEuler( this.rotation3d );
  8029. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  8030. this.matrix.scale( this.scale );
  8031. }
  8032. this.matrixWorldNeedsUpdate = true;
  8033. };
  8034. THREE.Sprite.prototype.clone = function ( object ) {
  8035. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8036. THREE.Object3D.prototype.clone.call( this, object );
  8037. return object;
  8038. };
  8039. /**
  8040. * @author mrdoob / http://mrdoob.com/
  8041. */
  8042. THREE.Scene = function () {
  8043. THREE.Object3D.call( this );
  8044. this.fog = null;
  8045. this.overrideMaterial = null;
  8046. this.matrixAutoUpdate = false;
  8047. this.__objects = [];
  8048. this.__lights = [];
  8049. this.__objectsAdded = [];
  8050. this.__objectsRemoved = [];
  8051. };
  8052. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8053. THREE.Scene.prototype.__addObject = function ( object ) {
  8054. if ( object instanceof THREE.Light ) {
  8055. if ( this.__lights.indexOf( object ) === - 1 ) {
  8056. this.__lights.push( object );
  8057. }
  8058. if ( object.target && object.target.parent === undefined ) {
  8059. this.add( object.target );
  8060. }
  8061. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8062. if ( this.__objects.indexOf( object ) === - 1 ) {
  8063. this.__objects.push( object );
  8064. this.__objectsAdded.push( object );
  8065. // check if previously removed
  8066. var i = this.__objectsRemoved.indexOf( object );
  8067. if ( i !== -1 ) {
  8068. this.__objectsRemoved.splice( i, 1 );
  8069. }
  8070. }
  8071. }
  8072. for ( var c = 0; c < object.children.length; c ++ ) {
  8073. this.__addObject( object.children[ c ] );
  8074. }
  8075. };
  8076. THREE.Scene.prototype.__removeObject = function ( object ) {
  8077. if ( object instanceof THREE.Light ) {
  8078. var i = this.__lights.indexOf( object );
  8079. if ( i !== -1 ) {
  8080. this.__lights.splice( i, 1 );
  8081. }
  8082. } else if ( !( object instanceof THREE.Camera ) ) {
  8083. var i = this.__objects.indexOf( object );
  8084. if( i !== -1 ) {
  8085. this.__objects.splice( i, 1 );
  8086. this.__objectsRemoved.push( object );
  8087. // check if previously added
  8088. var ai = this.__objectsAdded.indexOf( object );
  8089. if ( ai !== -1 ) {
  8090. this.__objectsAdded.splice( ai, 1 );
  8091. }
  8092. }
  8093. }
  8094. for ( var c = 0; c < object.children.length; c ++ ) {
  8095. this.__removeObject( object.children[ c ] );
  8096. }
  8097. };
  8098. /**
  8099. * @author mrdoob / http://mrdoob.com/
  8100. * @author alteredq / http://alteredqualia.com/
  8101. */
  8102. THREE.Fog = function ( hex, near, far ) {
  8103. this.name = '';
  8104. this.color = new THREE.Color( hex );
  8105. this.near = ( near !== undefined ) ? near : 1;
  8106. this.far = ( far !== undefined ) ? far : 1000;
  8107. };
  8108. THREE.Fog.prototype.clone = function () {
  8109. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  8110. };
  8111. /**
  8112. * @author mrdoob / http://mrdoob.com/
  8113. * @author alteredq / http://alteredqualia.com/
  8114. */
  8115. THREE.FogExp2 = function ( hex, density ) {
  8116. this.name = '';
  8117. this.color = new THREE.Color( hex );
  8118. this.density = ( density !== undefined ) ? density : 0.00025;
  8119. };
  8120. THREE.FogExp2.prototype.clone = function () {
  8121. return new THREE.FogExp2( this.color.getHex(), this.density );
  8122. };
  8123. /**
  8124. * @author mrdoob / http://mrdoob.com/
  8125. */
  8126. THREE.CanvasRenderer = function ( parameters ) {
  8127. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  8128. parameters = parameters || {};
  8129. var _this = this,
  8130. _renderData, _elements, _lights,
  8131. _projector = new THREE.Projector(),
  8132. _canvas = parameters.canvas !== undefined
  8133. ? parameters.canvas
  8134. : document.createElement( 'canvas' ),
  8135. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  8136. _context = _canvas.getContext( '2d' ),
  8137. _clearColor = new THREE.Color( 0x000000 ),
  8138. _clearOpacity = 0,
  8139. _contextGlobalAlpha = 1,
  8140. _contextGlobalCompositeOperation = 0,
  8141. _contextStrokeStyle = null,
  8142. _contextFillStyle = null,
  8143. _contextLineWidth = null,
  8144. _contextLineCap = null,
  8145. _contextLineJoin = null,
  8146. _v1, _v2, _v3, _v4,
  8147. _v5 = new THREE.RenderableVertex(),
  8148. _v6 = new THREE.RenderableVertex(),
  8149. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  8150. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  8151. _color = new THREE.Color(),
  8152. _color1 = new THREE.Color(),
  8153. _color2 = new THREE.Color(),
  8154. _color3 = new THREE.Color(),
  8155. _color4 = new THREE.Color(),
  8156. _diffuseColor = new THREE.Color(),
  8157. _emissiveColor = new THREE.Color(),
  8158. _patterns = {}, _imagedatas = {},
  8159. _near, _far,
  8160. _image, _uvs,
  8161. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  8162. _clipBox = new THREE.Box2(),
  8163. _clearBox = new THREE.Box2(),
  8164. _elemBox = new THREE.Box2(),
  8165. _enableLighting = false,
  8166. _ambientLight = new THREE.Color(),
  8167. _directionalLights = new THREE.Color(),
  8168. _pointLights = new THREE.Color(),
  8169. _pi2 = Math.PI * 2,
  8170. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8171. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8172. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8173. _pixelMap = document.createElement( 'canvas' );
  8174. _pixelMap.width = _pixelMap.height = 2;
  8175. _pixelMapContext = _pixelMap.getContext( '2d' );
  8176. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8177. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8178. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8179. _pixelMapData = _pixelMapImage.data;
  8180. _gradientMap = document.createElement( 'canvas' );
  8181. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8182. _gradientMapContext = _gradientMap.getContext( '2d' );
  8183. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8184. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8185. _gradientMapQuality --; // Fix UVs
  8186. this.domElement = _canvas;
  8187. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  8188. ? parameters.devicePixelRatio
  8189. : window.devicePixelRatio !== undefined
  8190. ? window.devicePixelRatio
  8191. : 1;
  8192. this.autoClear = true;
  8193. this.sortObjects = true;
  8194. this.sortElements = true;
  8195. this.info = {
  8196. render: {
  8197. vertices: 0,
  8198. faces: 0
  8199. }
  8200. }
  8201. this.setSize = function ( width, height ) {
  8202. _canvasWidth = width * this.devicePixelRatio;
  8203. _canvasHeight = height * this.devicePixelRatio;
  8204. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8205. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8206. _canvas.width = _canvasWidth;
  8207. _canvas.height = _canvasHeight;
  8208. _canvas.style.width = width + 'px';
  8209. _canvas.style.height = height + 'px';
  8210. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8211. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8212. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8213. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8214. _contextGlobalAlpha = 1;
  8215. _contextGlobalCompositeOperation = 0;
  8216. _contextStrokeStyle = null;
  8217. _contextFillStyle = null;
  8218. _contextLineWidth = null;
  8219. _contextLineCap = null;
  8220. _contextLineJoin = null;
  8221. };
  8222. this.setClearColor = function ( color, opacity ) {
  8223. _clearColor.copy( color );
  8224. _clearOpacity = opacity !== undefined ? opacity : 1;
  8225. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8226. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8227. };
  8228. this.setClearColorHex = function ( hex, opacity ) {
  8229. _clearColor.setHex( hex );
  8230. _clearOpacity = opacity !== undefined ? opacity : 1;
  8231. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8232. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8233. };
  8234. this.getMaxAnisotropy = function () {
  8235. return 0;
  8236. };
  8237. this.clear = function () {
  8238. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8239. if ( _clearBox.empty() === false ) {
  8240. _clearBox.intersect( _clipBox );
  8241. _clearBox.expandByScalar( 2 );
  8242. if ( _clearOpacity < 1 ) {
  8243. _context.clearRect( _clearBox.min.x | 0, _clearBox.min.y | 0, ( _clearBox.max.x - _clearBox.min.x ) | 0, ( _clearBox.max.y - _clearBox.min.y ) | 0 );
  8244. }
  8245. if ( _clearOpacity > 0 ) {
  8246. setBlending( THREE.NormalBlending );
  8247. setOpacity( 1 );
  8248. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  8249. _context.fillRect( _clearBox.min.x | 0, _clearBox.min.y | 0, ( _clearBox.max.x - _clearBox.min.x ) | 0, ( _clearBox.max.y - _clearBox.min.y ) | 0 );
  8250. }
  8251. _clearBox.makeEmpty();
  8252. }
  8253. };
  8254. this.render = function ( scene, camera ) {
  8255. if ( camera instanceof THREE.Camera === false ) {
  8256. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8257. return;
  8258. }
  8259. if ( this.autoClear === true ) {
  8260. this.clear();
  8261. }
  8262. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8263. _this.info.render.vertices = 0;
  8264. _this.info.render.faces = 0;
  8265. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8266. _elements = _renderData.elements;
  8267. _lights = _renderData.lights;
  8268. /* DEBUG
  8269. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  8270. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8271. */
  8272. _enableLighting = _lights.length > 0;
  8273. if ( _enableLighting === true ) {
  8274. calculateLights();
  8275. }
  8276. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  8277. var element = _elements[ e ];
  8278. var material = element.material;
  8279. if ( material === undefined || material.visible === false ) continue;
  8280. _elemBox.makeEmpty();
  8281. if ( element instanceof THREE.RenderableParticle ) {
  8282. _v1 = element;
  8283. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8284. renderParticle( _v1, element, material, scene );
  8285. } else if ( element instanceof THREE.RenderableLine ) {
  8286. _v1 = element.v1; _v2 = element.v2;
  8287. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8288. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8289. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] );
  8290. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8291. renderLine( _v1, _v2, element, material, scene );
  8292. }
  8293. } else if ( element instanceof THREE.RenderableFace3 ) {
  8294. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8295. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8296. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8297. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8298. if ( material.overdraw === true ) {
  8299. expand( _v1.positionScreen, _v2.positionScreen );
  8300. expand( _v2.positionScreen, _v3.positionScreen );
  8301. expand( _v3.positionScreen, _v1.positionScreen );
  8302. }
  8303. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen ] );
  8304. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8305. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  8306. }
  8307. } else if ( element instanceof THREE.RenderableFace4 ) {
  8308. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8309. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8310. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8311. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8312. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8313. _v5.positionScreen.copy( _v2.positionScreen );
  8314. _v6.positionScreen.copy( _v4.positionScreen );
  8315. if ( material.overdraw === true ) {
  8316. expand( _v1.positionScreen, _v2.positionScreen );
  8317. expand( _v2.positionScreen, _v4.positionScreen );
  8318. expand( _v4.positionScreen, _v1.positionScreen );
  8319. expand( _v3.positionScreen, _v5.positionScreen );
  8320. expand( _v3.positionScreen, _v6.positionScreen );
  8321. }
  8322. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen, _v4.positionScreen ] );
  8323. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8324. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  8325. }
  8326. }
  8327. /* DEBUG
  8328. _context.lineWidth = 1;
  8329. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  8330. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8331. */
  8332. _clearBox.union( _elemBox );
  8333. }
  8334. /* DEBUG
  8335. _context.lineWidth = 1;
  8336. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  8337. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8338. */
  8339. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8340. //
  8341. function calculateLights() {
  8342. _ambientLight.setRGB( 0, 0, 0 );
  8343. _directionalLights.setRGB( 0, 0, 0 );
  8344. _pointLights.setRGB( 0, 0, 0 );
  8345. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8346. var light = _lights[ l ];
  8347. var lightColor = light.color;
  8348. if ( light instanceof THREE.AmbientLight ) {
  8349. _ambientLight.r += lightColor.r;
  8350. _ambientLight.g += lightColor.g;
  8351. _ambientLight.b += lightColor.b;
  8352. } else if ( light instanceof THREE.DirectionalLight ) {
  8353. // for particles
  8354. _directionalLights.r += lightColor.r;
  8355. _directionalLights.g += lightColor.g;
  8356. _directionalLights.b += lightColor.b;
  8357. } else if ( light instanceof THREE.PointLight ) {
  8358. // for particles
  8359. _pointLights.r += lightColor.r;
  8360. _pointLights.g += lightColor.g;
  8361. _pointLights.b += lightColor.b;
  8362. }
  8363. }
  8364. }
  8365. function calculateLight( position, normal, color ) {
  8366. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8367. var light = _lights[ l ];
  8368. var lightColor = light.color;
  8369. if ( light instanceof THREE.DirectionalLight ) {
  8370. var lightPosition = light.matrixWorld.getPosition().normalize();
  8371. var amount = normal.dot( lightPosition );
  8372. if ( amount <= 0 ) continue;
  8373. amount *= light.intensity;
  8374. color.r += lightColor.r * amount;
  8375. color.g += lightColor.g * amount;
  8376. color.b += lightColor.b * amount;
  8377. } else if ( light instanceof THREE.PointLight ) {
  8378. var lightPosition = light.matrixWorld.getPosition();
  8379. var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  8380. if ( amount <= 0 ) continue;
  8381. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8382. if ( amount == 0 ) continue;
  8383. amount *= light.intensity;
  8384. color.r += lightColor.r * amount;
  8385. color.g += lightColor.g * amount;
  8386. color.b += lightColor.b * amount;
  8387. }
  8388. }
  8389. }
  8390. function renderParticle( v1, element, material, scene ) {
  8391. setOpacity( material.opacity );
  8392. setBlending( material.blending );
  8393. var width, height, scaleX, scaleY,
  8394. bitmap, bitmapWidth, bitmapHeight;
  8395. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8396. if ( material.map === null ) {
  8397. scaleX = element.object.scale.x;
  8398. scaleY = element.object.scale.y;
  8399. // TODO: Be able to disable this
  8400. scaleX *= element.scale.x * _canvasWidthHalf;
  8401. scaleY *= element.scale.y * _canvasHeightHalf;
  8402. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8403. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8404. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8405. return;
  8406. }
  8407. setFillStyle( material.color.getStyle() );
  8408. _context.save();
  8409. _context.translate( v1.x, v1.y );
  8410. _context.rotate( - element.rotation );
  8411. _context.scale( scaleX, scaleY );
  8412. _context.fillRect( -1, -1, 2, 2 );
  8413. _context.restore();
  8414. } else {
  8415. bitmap = material.map.image;
  8416. bitmapWidth = bitmap.width >> 1;
  8417. bitmapHeight = bitmap.height >> 1;
  8418. scaleX = element.scale.x * _canvasWidthHalf;
  8419. scaleY = element.scale.y * _canvasHeightHalf;
  8420. width = scaleX * bitmapWidth;
  8421. height = scaleY * bitmapHeight;
  8422. // TODO: Rotations break this...
  8423. _elemBox.min.set( v1.x - width, v1.y - height );
  8424. _elemBox.max.set( v1.x + width, v1.y + height );
  8425. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8426. return;
  8427. }
  8428. _context.save();
  8429. _context.translate( v1.x, v1.y );
  8430. _context.rotate( - element.rotation );
  8431. _context.scale( scaleX, - scaleY );
  8432. _context.translate( - bitmapWidth, - bitmapHeight );
  8433. _context.drawImage( bitmap, 0, 0 );
  8434. _context.restore();
  8435. }
  8436. /* DEBUG
  8437. setStrokeStyle( 'rgb(255,255,0)' );
  8438. _context.beginPath();
  8439. _context.moveTo( v1.x - 10, v1.y );
  8440. _context.lineTo( v1.x + 10, v1.y );
  8441. _context.moveTo( v1.x, v1.y - 10 );
  8442. _context.lineTo( v1.x, v1.y + 10 );
  8443. _context.stroke();
  8444. */
  8445. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8446. width = element.scale.x * _canvasWidthHalf;
  8447. height = element.scale.y * _canvasHeightHalf;
  8448. _elemBox.min.set( v1.x - width, v1.y - height );
  8449. _elemBox.max.set( v1.x + width, v1.y + height );
  8450. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8451. return;
  8452. }
  8453. setStrokeStyle( material.color.getStyle() );
  8454. setFillStyle( material.color.getStyle() );
  8455. _context.save();
  8456. _context.translate( v1.x, v1.y );
  8457. _context.rotate( - element.rotation );
  8458. _context.scale( width, height );
  8459. material.program( _context );
  8460. _context.restore();
  8461. }
  8462. }
  8463. function renderLine( v1, v2, element, material, scene ) {
  8464. setOpacity( material.opacity );
  8465. setBlending( material.blending );
  8466. _context.beginPath();
  8467. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8468. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8469. if ( material instanceof THREE.LineBasicMaterial ) {
  8470. setLineWidth( material.linewidth );
  8471. setLineCap( material.linecap );
  8472. setLineJoin( material.linejoin );
  8473. setStrokeStyle( material.color.getStyle() );
  8474. _context.stroke();
  8475. _elemBox.expandByScalar( material.linewidth * 2 );
  8476. }
  8477. }
  8478. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  8479. _this.info.render.vertices += 3;
  8480. _this.info.render.faces ++;
  8481. setOpacity( material.opacity );
  8482. setBlending( material.blending );
  8483. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8484. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8485. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8486. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8487. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  8488. _diffuseColor.copy( material.color );
  8489. _emissiveColor.copy( material.emissive );
  8490. if ( material.vertexColors === THREE.FaceColors ) {
  8491. _diffuseColor.r *= element.color.r;
  8492. _diffuseColor.g *= element.color.g;
  8493. _diffuseColor.b *= element.color.b;
  8494. }
  8495. if ( _enableLighting === true ) {
  8496. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8497. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  8498. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  8499. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  8500. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8501. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8502. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  8503. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  8504. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  8505. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  8506. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  8507. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  8508. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  8509. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  8510. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  8511. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  8512. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  8513. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  8514. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  8515. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8516. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8517. } else {
  8518. _color.r = _ambientLight.r;
  8519. _color.g = _ambientLight.g;
  8520. _color.b = _ambientLight.b;
  8521. calculateLight( element.centroidModel, element.normalModel, _color );
  8522. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  8523. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  8524. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  8525. material.wireframe === true
  8526. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8527. : fillPath( _color );
  8528. }
  8529. } else {
  8530. material.wireframe === true
  8531. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8532. : fillPath( material.color );
  8533. }
  8534. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8535. if ( material.map !== null ) {
  8536. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8537. _uvs = element.uvs[ 0 ];
  8538. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].x, _uvs[ uv1 ].y, _uvs[ uv2 ].x, _uvs[ uv2 ].y, _uvs[ uv3 ].x, _uvs[ uv3 ].y, material.map );
  8539. }
  8540. } else if ( material.envMap !== null ) {
  8541. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8542. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  8543. _uv1x = 0.5 * _vector3.x + 0.5;
  8544. _uv1y = 0.5 * _vector3.y + 0.5;
  8545. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  8546. _uv2x = 0.5 * _vector3.x + 0.5;
  8547. _uv2y = 0.5 * _vector3.y + 0.5;
  8548. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  8549. _uv3x = 0.5 * _vector3.x + 0.5;
  8550. _uv3y = 0.5 * _vector3.y + 0.5;
  8551. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8552. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8553. }*/
  8554. } else {
  8555. _color.copy( material.color );
  8556. if ( material.vertexColors === THREE.FaceColors ) {
  8557. _color.r *= element.color.r;
  8558. _color.g *= element.color.g;
  8559. _color.b *= element.color.b;
  8560. }
  8561. material.wireframe === true
  8562. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8563. : fillPath( _color );
  8564. }
  8565. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8566. _near = camera.near;
  8567. _far = camera.far;
  8568. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8569. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  8570. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8571. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  8572. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  8573. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  8574. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8575. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8576. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8577. if ( material.shading == THREE.FlatShading ) {
  8578. _color.r = 0.5 * element.normalModelView.x + 0.5;
  8579. _color.g = 0.5 * element.normalModelView.y + 0.5;
  8580. _color.b = 0.5 * element.normalModelView.z + 0.5;
  8581. material.wireframe === true
  8582. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8583. : fillPath( _color );
  8584. } else if ( material.shading == THREE.SmoothShading ) {
  8585. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  8586. _color1.r = 0.5 * _vector3.x + 0.5;
  8587. _color1.g = 0.5 * _vector3.y + 0.5;
  8588. _color1.b = 0.5 * _vector3.z + 0.5;
  8589. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  8590. _color2.r = 0.5 * _vector3.x + 0.5;
  8591. _color2.g = 0.5 * _vector3.y + 0.5;
  8592. _color2.b = 0.5 * _vector3.z + 0.5;
  8593. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  8594. _color3.r = 0.5 * _vector3.x + 0.5;
  8595. _color3.g = 0.5 * _vector3.y + 0.5;
  8596. _color3.b = 0.5 * _vector3.z + 0.5;
  8597. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  8598. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  8599. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  8600. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8601. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8602. }
  8603. }
  8604. }
  8605. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  8606. _this.info.render.vertices += 4;
  8607. _this.info.render.faces ++;
  8608. setOpacity( material.opacity );
  8609. setBlending( material.blending );
  8610. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8611. // Let renderFace3() handle this
  8612. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  8613. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  8614. return;
  8615. }
  8616. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8617. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8618. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8619. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8620. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8621. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8622. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8623. _diffuseColor.copy( material.color );
  8624. _emissiveColor.copy( material.emissive );
  8625. if ( material.vertexColors === THREE.FaceColors ) {
  8626. _diffuseColor.r *= element.color.r;
  8627. _diffuseColor.g *= element.color.g;
  8628. _diffuseColor.b *= element.color.b;
  8629. }
  8630. if ( _enableLighting === true ) {
  8631. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8632. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  8633. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  8634. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  8635. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8636. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8637. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  8638. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  8639. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  8640. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  8641. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  8642. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  8643. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  8644. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  8645. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  8646. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  8647. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  8648. _color4.r = _color4.r * _diffuseColor.r + _emissiveColor.r;
  8649. _color4.g = _color4.g * _diffuseColor.g + _emissiveColor.g;
  8650. _color4.b = _color4.b * _diffuseColor.b + _emissiveColor.b;
  8651. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8652. // TODO: UVs are incorrect, v4->v3?
  8653. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8654. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8655. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8656. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8657. } else {
  8658. _color.r = _ambientLight.r;
  8659. _color.g = _ambientLight.g;
  8660. _color.b = _ambientLight.b;
  8661. calculateLight( element.centroidModel, element.normalModel, _color );
  8662. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  8663. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  8664. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  8665. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8666. material.wireframe === true
  8667. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8668. : fillPath( _color );
  8669. }
  8670. } else {
  8671. _color.r = _diffuseColor.r + _emissiveColor.r;
  8672. _color.g = _diffuseColor.g + _emissiveColor.g;
  8673. _color.b = _diffuseColor.b + _emissiveColor.b;
  8674. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8675. material.wireframe === true
  8676. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8677. : fillPath( _color );
  8678. }
  8679. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8680. _color.copy( material.color );
  8681. if ( material.vertexColors === THREE.FaceColors ) {
  8682. _color.r *= element.color.r;
  8683. _color.g *= element.color.g;
  8684. _color.b *= element.color.b;
  8685. }
  8686. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8687. material.wireframe === true
  8688. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8689. : fillPath( _color );
  8690. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8691. if ( material.shading == THREE.FlatShading ) {
  8692. _color.r = 0.5 * element.normalModelView.x + 0.5;
  8693. _color.g = 0.5 * element.normalModelView.y + 0.5;
  8694. _color.b = 0.5 * element.normalModelView.z + 0.5;
  8695. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8696. material.wireframe === true
  8697. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8698. : fillPath( _color );
  8699. } else if ( material.shading == THREE.SmoothShading ) {
  8700. _vector3.copy( element.vertexNormalsModelView[ 0 ] );
  8701. _color1.r = 0.5 * _vector3.x + 0.5;
  8702. _color1.g = 0.5 * _vector3.y + 0.5;
  8703. _color1.b = 0.5 * _vector3.z + 0.5;
  8704. _vector3.copy( element.vertexNormalsModelView[ 1 ] );
  8705. _color2.r = 0.5 * _vector3.x + 0.5;
  8706. _color2.g = 0.5 * _vector3.y + 0.5;
  8707. _color2.b = 0.5 * _vector3.z + 0.5;
  8708. _vector3.copy( element.vertexNormalsModelView[ 3 ] );
  8709. _color3.r = 0.5 * _vector3.x + 0.5;
  8710. _color3.g = 0.5 * _vector3.y + 0.5;
  8711. _color3.b = 0.5 * _vector3.z + 0.5;
  8712. _vector3.copy( element.vertexNormalsModelView[ 2 ] );
  8713. _color4.r = 0.5 * _vector3.x + 0.5;
  8714. _color4.g = 0.5 * _vector3.y + 0.5;
  8715. _color4.b = 0.5 * _vector3.z + 0.5;
  8716. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8717. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8718. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8719. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8720. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8721. }
  8722. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8723. _near = camera.near;
  8724. _far = camera.far;
  8725. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8726. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  8727. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  8728. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8729. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8730. // TODO: UVs are incorrect, v4->v3?
  8731. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8732. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8733. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8734. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8735. }
  8736. }
  8737. //
  8738. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8739. _context.beginPath();
  8740. _context.moveTo( x0, y0 );
  8741. _context.lineTo( x1, y1 );
  8742. _context.lineTo( x2, y2 );
  8743. _context.closePath();
  8744. }
  8745. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8746. _context.beginPath();
  8747. _context.moveTo( x0, y0 );
  8748. _context.lineTo( x1, y1 );
  8749. _context.lineTo( x2, y2 );
  8750. _context.lineTo( x3, y3 );
  8751. _context.closePath();
  8752. }
  8753. function strokePath( color, linewidth, linecap, linejoin ) {
  8754. setLineWidth( linewidth );
  8755. setLineCap( linecap );
  8756. setLineJoin( linejoin );
  8757. setStrokeStyle( color.getStyle() );
  8758. _context.stroke();
  8759. _elemBox.expandByScalar( linewidth * 2 );
  8760. }
  8761. function fillPath( color ) {
  8762. setFillStyle( color.getStyle() );
  8763. _context.fill();
  8764. }
  8765. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8766. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8767. if ( texture.needsUpdate === true ) {
  8768. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8769. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8770. _patterns[ texture.id ] = _context.createPattern(
  8771. texture.image, repeatX === true && repeatY === true
  8772. ? 'repeat'
  8773. : repeatX === true && repeatY === false
  8774. ? 'repeat-x'
  8775. : repeatX === false && repeatY === true
  8776. ? 'repeat-y'
  8777. : 'no-repeat'
  8778. );
  8779. texture.needsUpdate = false;
  8780. }
  8781. _patterns[ texture.id ] === undefined
  8782. ? setFillStyle( 'rgba(0,0,0,1)' )
  8783. : setFillStyle( _patterns[ texture.id ] );
  8784. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8785. var a, b, c, d, e, f, det, idet,
  8786. offsetX = texture.offset.x / texture.repeat.x,
  8787. offsetY = texture.offset.y / texture.repeat.y,
  8788. width = texture.image.width * texture.repeat.x,
  8789. height = texture.image.height * texture.repeat.y;
  8790. u0 = ( u0 + offsetX ) * width;
  8791. v0 = ( 1.0 - v0 + offsetY ) * height;
  8792. u1 = ( u1 + offsetX ) * width;
  8793. v1 = ( 1.0 - v1 + offsetY ) * height;
  8794. u2 = ( u2 + offsetX ) * width;
  8795. v2 = ( 1.0 - v2 + offsetY ) * height;
  8796. x1 -= x0; y1 -= y0;
  8797. x2 -= x0; y2 -= y0;
  8798. u1 -= u0; v1 -= v0;
  8799. u2 -= u0; v2 -= v0;
  8800. det = u1 * v2 - u2 * v1;
  8801. if ( det === 0 ) {
  8802. if ( _imagedatas[ texture.id ] === undefined ) {
  8803. var canvas = document.createElement( 'canvas' )
  8804. canvas.width = texture.image.width;
  8805. canvas.height = texture.image.height;
  8806. var context = canvas.getContext( '2d' );
  8807. context.drawImage( texture.image, 0, 0 );
  8808. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8809. }
  8810. var data = _imagedatas[ texture.id ];
  8811. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8812. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8813. fillPath( _color );
  8814. return;
  8815. }
  8816. idet = 1 / det;
  8817. a = ( v2 * x1 - v1 * x2 ) * idet;
  8818. b = ( v2 * y1 - v1 * y2 ) * idet;
  8819. c = ( u1 * x2 - u2 * x1 ) * idet;
  8820. d = ( u1 * y2 - u2 * y1 ) * idet;
  8821. e = x0 - a * u0 - c * v0;
  8822. f = y0 - b * u0 - d * v0;
  8823. _context.save();
  8824. _context.transform( a, b, c, d, e, f );
  8825. _context.fill();
  8826. _context.restore();
  8827. }
  8828. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8829. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8830. var a, b, c, d, e, f, det, idet,
  8831. width = image.width - 1,
  8832. height = image.height - 1;
  8833. u0 *= width; v0 *= height;
  8834. u1 *= width; v1 *= height;
  8835. u2 *= width; v2 *= height;
  8836. x1 -= x0; y1 -= y0;
  8837. x2 -= x0; y2 -= y0;
  8838. u1 -= u0; v1 -= v0;
  8839. u2 -= u0; v2 -= v0;
  8840. det = u1 * v2 - u2 * v1;
  8841. idet = 1 / det;
  8842. a = ( v2 * x1 - v1 * x2 ) * idet;
  8843. b = ( v2 * y1 - v1 * y2 ) * idet;
  8844. c = ( u1 * x2 - u2 * x1 ) * idet;
  8845. d = ( u1 * y2 - u2 * y1 ) * idet;
  8846. e = x0 - a * u0 - c * v0;
  8847. f = y0 - b * u0 - d * v0;
  8848. _context.save();
  8849. _context.transform( a, b, c, d, e, f );
  8850. _context.clip();
  8851. _context.drawImage( image, 0, 0 );
  8852. _context.restore();
  8853. }
  8854. function getGradientTexture( color1, color2, color3, color4 ) {
  8855. // http://mrdoob.com/blog/post/710
  8856. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  8857. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  8858. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  8859. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  8860. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  8861. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  8862. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  8863. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  8864. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  8865. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  8866. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  8867. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  8868. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  8869. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  8870. return _gradientMap;
  8871. }
  8872. function smoothstep( value, min, max ) {
  8873. var x = ( value - min ) / ( max - min );
  8874. return x * x * ( 3 - 2 * x );
  8875. }
  8876. // Hide anti-alias gaps
  8877. function expand( v1, v2 ) {
  8878. var x = v2.x - v1.x, y = v2.y - v1.y,
  8879. det = x * x + y * y, idet;
  8880. if ( det === 0 ) return;
  8881. idet = 1 / Math.sqrt( det );
  8882. x *= idet; y *= idet;
  8883. v2.x += x; v2.y += y;
  8884. v1.x -= x; v1.y -= y;
  8885. }
  8886. };
  8887. // Context cached methods.
  8888. function setOpacity( value ) {
  8889. if ( _contextGlobalAlpha !== value ) {
  8890. _context.globalAlpha = value;
  8891. _contextGlobalAlpha = value;
  8892. }
  8893. }
  8894. function setBlending( value ) {
  8895. if ( _contextGlobalCompositeOperation !== value ) {
  8896. if ( value === THREE.NormalBlending ) {
  8897. _context.globalCompositeOperation = 'source-over';
  8898. } else if ( value === THREE.AdditiveBlending ) {
  8899. _context.globalCompositeOperation = 'lighter';
  8900. } else if ( value === THREE.SubtractiveBlending ) {
  8901. _context.globalCompositeOperation = 'darker';
  8902. }
  8903. _contextGlobalCompositeOperation = value;
  8904. }
  8905. }
  8906. function setLineWidth( value ) {
  8907. if ( _contextLineWidth !== value ) {
  8908. _context.lineWidth = value;
  8909. _contextLineWidth = value;
  8910. }
  8911. }
  8912. function setLineCap( value ) {
  8913. // "butt", "round", "square"
  8914. if ( _contextLineCap !== value ) {
  8915. _context.lineCap = value;
  8916. _contextLineCap = value;
  8917. }
  8918. }
  8919. function setLineJoin( value ) {
  8920. // "round", "bevel", "miter"
  8921. if ( _contextLineJoin !== value ) {
  8922. _context.lineJoin = value;
  8923. _contextLineJoin = value;
  8924. }
  8925. }
  8926. function setStrokeStyle( value ) {
  8927. if ( _contextStrokeStyle !== value ) {
  8928. _context.strokeStyle = value;
  8929. _contextStrokeStyle = value;
  8930. }
  8931. }
  8932. function setFillStyle( value ) {
  8933. if ( _contextFillStyle !== value ) {
  8934. _context.fillStyle = value;
  8935. _contextFillStyle = value;
  8936. }
  8937. }
  8938. };
  8939. /**
  8940. * @author alteredq / http://alteredqualia.com/
  8941. * @author mrdoob / http://mrdoob.com/
  8942. * @author mikael emtinger / http://gomo.se/
  8943. */
  8944. THREE.ShaderChunk = {
  8945. // FOG
  8946. fog_pars_fragment: [
  8947. "#ifdef USE_FOG",
  8948. "uniform vec3 fogColor;",
  8949. "#ifdef FOG_EXP2",
  8950. "uniform float fogDensity;",
  8951. "#else",
  8952. "uniform float fogNear;",
  8953. "uniform float fogFar;",
  8954. "#endif",
  8955. "#endif"
  8956. ].join("\n"),
  8957. fog_fragment: [
  8958. "#ifdef USE_FOG",
  8959. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8960. "#ifdef FOG_EXP2",
  8961. "const float LOG2 = 1.442695;",
  8962. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8963. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8964. "#else",
  8965. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8966. "#endif",
  8967. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8968. "#endif"
  8969. ].join("\n"),
  8970. // ENVIRONMENT MAP
  8971. envmap_pars_fragment: [
  8972. "#ifdef USE_ENVMAP",
  8973. "uniform float reflectivity;",
  8974. "uniform samplerCube envMap;",
  8975. "uniform float flipEnvMap;",
  8976. "uniform int combine;",
  8977. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8978. "uniform bool useRefract;",
  8979. "uniform float refractionRatio;",
  8980. "#else",
  8981. "varying vec3 vReflect;",
  8982. "#endif",
  8983. "#endif"
  8984. ].join("\n"),
  8985. envmap_fragment: [
  8986. "#ifdef USE_ENVMAP",
  8987. "vec3 reflectVec;",
  8988. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8989. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8990. "if ( useRefract ) {",
  8991. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8992. "} else { ",
  8993. "reflectVec = reflect( cameraToVertex, normal );",
  8994. "}",
  8995. "#else",
  8996. "reflectVec = vReflect;",
  8997. "#endif",
  8998. "#ifdef DOUBLE_SIDED",
  8999. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9000. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9001. "#else",
  9002. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9003. "#endif",
  9004. "#ifdef GAMMA_INPUT",
  9005. "cubeColor.xyz *= cubeColor.xyz;",
  9006. "#endif",
  9007. "if ( combine == 1 ) {",
  9008. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9009. "} else if ( combine == 2 ) {",
  9010. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9011. "} else {",
  9012. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9013. "}",
  9014. "#endif"
  9015. ].join("\n"),
  9016. envmap_pars_vertex: [
  9017. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9018. "varying vec3 vReflect;",
  9019. "uniform float refractionRatio;",
  9020. "uniform bool useRefract;",
  9021. "#endif"
  9022. ].join("\n"),
  9023. worldpos_vertex : [
  9024. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9025. "#ifdef USE_SKINNING",
  9026. "vec4 worldPosition = modelMatrix * skinned;",
  9027. "#endif",
  9028. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9029. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9030. "#endif",
  9031. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9032. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9033. "#endif",
  9034. "#endif"
  9035. ].join("\n"),
  9036. envmap_vertex : [
  9037. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9038. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9039. "worldNormal = normalize( worldNormal );",
  9040. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9041. "if ( useRefract ) {",
  9042. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9043. "} else {",
  9044. "vReflect = reflect( cameraToVertex, worldNormal );",
  9045. "}",
  9046. "#endif"
  9047. ].join("\n"),
  9048. // COLOR MAP (particles)
  9049. map_particle_pars_fragment: [
  9050. "#ifdef USE_MAP",
  9051. "uniform sampler2D map;",
  9052. "#endif"
  9053. ].join("\n"),
  9054. map_particle_fragment: [
  9055. "#ifdef USE_MAP",
  9056. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9057. "#endif"
  9058. ].join("\n"),
  9059. // COLOR MAP (triangles)
  9060. map_pars_vertex: [
  9061. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9062. "varying vec2 vUv;",
  9063. "uniform vec4 offsetRepeat;",
  9064. "#endif"
  9065. ].join("\n"),
  9066. map_pars_fragment: [
  9067. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9068. "varying vec2 vUv;",
  9069. "#endif",
  9070. "#ifdef USE_MAP",
  9071. "uniform sampler2D map;",
  9072. "#endif"
  9073. ].join("\n"),
  9074. map_vertex: [
  9075. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9076. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9077. "#endif"
  9078. ].join("\n"),
  9079. map_fragment: [
  9080. "#ifdef USE_MAP",
  9081. "vec4 texelColor = texture2D( map, vUv );",
  9082. "#ifdef GAMMA_INPUT",
  9083. "texelColor.xyz *= texelColor.xyz;",
  9084. "#endif",
  9085. "gl_FragColor = gl_FragColor * texelColor;",
  9086. "#endif"
  9087. ].join("\n"),
  9088. // LIGHT MAP
  9089. lightmap_pars_fragment: [
  9090. "#ifdef USE_LIGHTMAP",
  9091. "varying vec2 vUv2;",
  9092. "uniform sampler2D lightMap;",
  9093. "#endif"
  9094. ].join("\n"),
  9095. lightmap_pars_vertex: [
  9096. "#ifdef USE_LIGHTMAP",
  9097. "varying vec2 vUv2;",
  9098. "#endif"
  9099. ].join("\n"),
  9100. lightmap_fragment: [
  9101. "#ifdef USE_LIGHTMAP",
  9102. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9103. "#endif"
  9104. ].join("\n"),
  9105. lightmap_vertex: [
  9106. "#ifdef USE_LIGHTMAP",
  9107. "vUv2 = uv2;",
  9108. "#endif"
  9109. ].join("\n"),
  9110. // BUMP MAP
  9111. bumpmap_pars_fragment: [
  9112. "#ifdef USE_BUMPMAP",
  9113. "uniform sampler2D bumpMap;",
  9114. "uniform float bumpScale;",
  9115. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9116. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9117. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9118. "vec2 dHdxy_fwd() {",
  9119. "vec2 dSTdx = dFdx( vUv );",
  9120. "vec2 dSTdy = dFdy( vUv );",
  9121. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9122. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9123. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9124. "return vec2( dBx, dBy );",
  9125. "}",
  9126. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9127. "vec3 vSigmaX = dFdx( surf_pos );",
  9128. "vec3 vSigmaY = dFdy( surf_pos );",
  9129. "vec3 vN = surf_norm;", // normalized
  9130. "vec3 R1 = cross( vSigmaY, vN );",
  9131. "vec3 R2 = cross( vN, vSigmaX );",
  9132. "float fDet = dot( vSigmaX, R1 );",
  9133. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9134. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9135. "}",
  9136. "#endif"
  9137. ].join("\n"),
  9138. // NORMAL MAP
  9139. normalmap_pars_fragment: [
  9140. "#ifdef USE_NORMALMAP",
  9141. "uniform sampler2D normalMap;",
  9142. "uniform vec2 normalScale;",
  9143. // Per-Pixel Tangent Space Normal Mapping
  9144. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9145. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9146. "vec3 q0 = dFdx( eye_pos.xyz );",
  9147. "vec3 q1 = dFdy( eye_pos.xyz );",
  9148. "vec2 st0 = dFdx( vUv.st );",
  9149. "vec2 st1 = dFdy( vUv.st );",
  9150. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9151. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9152. "vec3 N = normalize( surf_norm );",
  9153. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9154. "mapN.xy = normalScale * mapN.xy;",
  9155. "mat3 tsn = mat3( S, T, N );",
  9156. "return normalize( tsn * mapN );",
  9157. "}",
  9158. "#endif"
  9159. ].join("\n"),
  9160. // SPECULAR MAP
  9161. specularmap_pars_fragment: [
  9162. "#ifdef USE_SPECULARMAP",
  9163. "uniform sampler2D specularMap;",
  9164. "#endif"
  9165. ].join("\n"),
  9166. specularmap_fragment: [
  9167. "float specularStrength;",
  9168. "#ifdef USE_SPECULARMAP",
  9169. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9170. "specularStrength = texelSpecular.r;",
  9171. "#else",
  9172. "specularStrength = 1.0;",
  9173. "#endif"
  9174. ].join("\n"),
  9175. // LIGHTS LAMBERT
  9176. lights_lambert_pars_vertex: [
  9177. "uniform vec3 ambient;",
  9178. "uniform vec3 diffuse;",
  9179. "uniform vec3 emissive;",
  9180. "uniform vec3 ambientLightColor;",
  9181. "#if MAX_DIR_LIGHTS > 0",
  9182. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9183. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9184. "#endif",
  9185. "#if MAX_HEMI_LIGHTS > 0",
  9186. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9187. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9188. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9189. "#endif",
  9190. "#if MAX_POINT_LIGHTS > 0",
  9191. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9192. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9193. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9194. "#endif",
  9195. "#if MAX_SPOT_LIGHTS > 0",
  9196. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9197. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9198. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9199. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9200. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9201. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9202. "#endif",
  9203. "#ifdef WRAP_AROUND",
  9204. "uniform vec3 wrapRGB;",
  9205. "#endif"
  9206. ].join("\n"),
  9207. lights_lambert_vertex: [
  9208. "vLightFront = vec3( 0.0 );",
  9209. "#ifdef DOUBLE_SIDED",
  9210. "vLightBack = vec3( 0.0 );",
  9211. "#endif",
  9212. "transformedNormal = normalize( transformedNormal );",
  9213. "#if MAX_DIR_LIGHTS > 0",
  9214. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9215. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9216. "vec3 dirVector = normalize( lDirection.xyz );",
  9217. "float dotProduct = dot( transformedNormal, dirVector );",
  9218. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9219. "#ifdef DOUBLE_SIDED",
  9220. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9221. "#ifdef WRAP_AROUND",
  9222. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9223. "#endif",
  9224. "#endif",
  9225. "#ifdef WRAP_AROUND",
  9226. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9227. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9228. "#ifdef DOUBLE_SIDED",
  9229. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9230. "#endif",
  9231. "#endif",
  9232. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9233. "#ifdef DOUBLE_SIDED",
  9234. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9235. "#endif",
  9236. "}",
  9237. "#endif",
  9238. "#if MAX_POINT_LIGHTS > 0",
  9239. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9240. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9241. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9242. "float lDistance = 1.0;",
  9243. "if ( pointLightDistance[ i ] > 0.0 )",
  9244. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9245. "lVector = normalize( lVector );",
  9246. "float dotProduct = dot( transformedNormal, lVector );",
  9247. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9248. "#ifdef DOUBLE_SIDED",
  9249. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9250. "#ifdef WRAP_AROUND",
  9251. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9252. "#endif",
  9253. "#endif",
  9254. "#ifdef WRAP_AROUND",
  9255. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9256. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9257. "#ifdef DOUBLE_SIDED",
  9258. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9259. "#endif",
  9260. "#endif",
  9261. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9262. "#ifdef DOUBLE_SIDED",
  9263. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9264. "#endif",
  9265. "}",
  9266. "#endif",
  9267. "#if MAX_SPOT_LIGHTS > 0",
  9268. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9269. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9270. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9271. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9272. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9273. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9274. "float lDistance = 1.0;",
  9275. "if ( spotLightDistance[ i ] > 0.0 )",
  9276. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9277. "lVector = normalize( lVector );",
  9278. "float dotProduct = dot( transformedNormal, lVector );",
  9279. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9280. "#ifdef DOUBLE_SIDED",
  9281. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9282. "#ifdef WRAP_AROUND",
  9283. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9284. "#endif",
  9285. "#endif",
  9286. "#ifdef WRAP_AROUND",
  9287. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9288. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9289. "#ifdef DOUBLE_SIDED",
  9290. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9291. "#endif",
  9292. "#endif",
  9293. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9294. "#ifdef DOUBLE_SIDED",
  9295. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9296. "#endif",
  9297. "}",
  9298. "}",
  9299. "#endif",
  9300. "#if MAX_HEMI_LIGHTS > 0",
  9301. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9302. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9303. "vec3 lVector = normalize( lDirection.xyz );",
  9304. "float dotProduct = dot( transformedNormal, lVector );",
  9305. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9306. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9307. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9308. "#ifdef DOUBLE_SIDED",
  9309. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9310. "#endif",
  9311. "}",
  9312. "#endif",
  9313. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9314. "#ifdef DOUBLE_SIDED",
  9315. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9316. "#endif"
  9317. ].join("\n"),
  9318. // LIGHTS PHONG
  9319. lights_phong_pars_vertex: [
  9320. "#ifndef PHONG_PER_PIXEL",
  9321. "#if MAX_POINT_LIGHTS > 0",
  9322. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9323. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9324. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9325. "#endif",
  9326. "#if MAX_SPOT_LIGHTS > 0",
  9327. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9328. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9329. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9330. "#endif",
  9331. "#endif",
  9332. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9333. "varying vec3 vWorldPosition;",
  9334. "#endif"
  9335. ].join("\n"),
  9336. lights_phong_vertex: [
  9337. "#ifndef PHONG_PER_PIXEL",
  9338. "#if MAX_POINT_LIGHTS > 0",
  9339. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9340. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9341. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9342. "float lDistance = 1.0;",
  9343. "if ( pointLightDistance[ i ] > 0.0 )",
  9344. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9345. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9346. "}",
  9347. "#endif",
  9348. "#if MAX_SPOT_LIGHTS > 0",
  9349. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9350. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9351. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9352. "float lDistance = 1.0;",
  9353. "if ( spotLightDistance[ i ] > 0.0 )",
  9354. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9355. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9356. "}",
  9357. "#endif",
  9358. "#endif",
  9359. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9360. "vWorldPosition = worldPosition.xyz;",
  9361. "#endif"
  9362. ].join("\n"),
  9363. lights_phong_pars_fragment: [
  9364. "uniform vec3 ambientLightColor;",
  9365. "#if MAX_DIR_LIGHTS > 0",
  9366. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9367. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9368. "#endif",
  9369. "#if MAX_HEMI_LIGHTS > 0",
  9370. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9371. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9372. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9373. "#endif",
  9374. "#if MAX_POINT_LIGHTS > 0",
  9375. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9376. "#ifdef PHONG_PER_PIXEL",
  9377. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9378. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9379. "#else",
  9380. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9381. "#endif",
  9382. "#endif",
  9383. "#if MAX_SPOT_LIGHTS > 0",
  9384. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9385. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9386. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9387. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9388. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9389. "#ifdef PHONG_PER_PIXEL",
  9390. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9391. "#else",
  9392. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9393. "#endif",
  9394. "#endif",
  9395. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9396. "varying vec3 vWorldPosition;",
  9397. "#endif",
  9398. "#ifdef WRAP_AROUND",
  9399. "uniform vec3 wrapRGB;",
  9400. "#endif",
  9401. "varying vec3 vViewPosition;",
  9402. "varying vec3 vNormal;"
  9403. ].join("\n"),
  9404. lights_phong_fragment: [
  9405. "vec3 normal = normalize( vNormal );",
  9406. "vec3 viewPosition = normalize( vViewPosition );",
  9407. "#ifdef DOUBLE_SIDED",
  9408. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9409. "#endif",
  9410. "#ifdef USE_NORMALMAP",
  9411. "normal = perturbNormal2Arb( -viewPosition, normal );",
  9412. "#elif defined( USE_BUMPMAP )",
  9413. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9414. "#endif",
  9415. "#if MAX_POINT_LIGHTS > 0",
  9416. "vec3 pointDiffuse = vec3( 0.0 );",
  9417. "vec3 pointSpecular = vec3( 0.0 );",
  9418. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9419. "#ifdef PHONG_PER_PIXEL",
  9420. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9421. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9422. "float lDistance = 1.0;",
  9423. "if ( pointLightDistance[ i ] > 0.0 )",
  9424. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9425. "lVector = normalize( lVector );",
  9426. "#else",
  9427. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9428. "float lDistance = vPointLight[ i ].w;",
  9429. "#endif",
  9430. // diffuse
  9431. "float dotProduct = dot( normal, lVector );",
  9432. "#ifdef WRAP_AROUND",
  9433. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9434. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9435. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9436. "#else",
  9437. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9438. "#endif",
  9439. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9440. // specular
  9441. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9442. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9443. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9444. "#ifdef PHYSICALLY_BASED_SHADING",
  9445. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9446. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9447. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9448. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9449. "#else",
  9450. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9451. "#endif",
  9452. "}",
  9453. "#endif",
  9454. "#if MAX_SPOT_LIGHTS > 0",
  9455. "vec3 spotDiffuse = vec3( 0.0 );",
  9456. "vec3 spotSpecular = vec3( 0.0 );",
  9457. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9458. "#ifdef PHONG_PER_PIXEL",
  9459. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9460. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9461. "float lDistance = 1.0;",
  9462. "if ( spotLightDistance[ i ] > 0.0 )",
  9463. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9464. "lVector = normalize( lVector );",
  9465. "#else",
  9466. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9467. "float lDistance = vSpotLight[ i ].w;",
  9468. "#endif",
  9469. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9470. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9471. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9472. // diffuse
  9473. "float dotProduct = dot( normal, lVector );",
  9474. "#ifdef WRAP_AROUND",
  9475. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9476. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9477. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9478. "#else",
  9479. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9480. "#endif",
  9481. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9482. // specular
  9483. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9484. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9485. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9486. "#ifdef PHYSICALLY_BASED_SHADING",
  9487. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9488. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9489. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9490. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9491. "#else",
  9492. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9493. "#endif",
  9494. "}",
  9495. "}",
  9496. "#endif",
  9497. "#if MAX_DIR_LIGHTS > 0",
  9498. "vec3 dirDiffuse = vec3( 0.0 );",
  9499. "vec3 dirSpecular = vec3( 0.0 );" ,
  9500. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9501. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9502. "vec3 dirVector = normalize( lDirection.xyz );",
  9503. // diffuse
  9504. "float dotProduct = dot( normal, dirVector );",
  9505. "#ifdef WRAP_AROUND",
  9506. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9507. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9508. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9509. "#else",
  9510. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9511. "#endif",
  9512. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9513. // specular
  9514. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9515. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9516. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9517. "#ifdef PHYSICALLY_BASED_SHADING",
  9518. /*
  9519. // fresnel term from skin shader
  9520. "const float F0 = 0.128;",
  9521. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9522. "float exponential = pow( base, 5.0 );",
  9523. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9524. */
  9525. /*
  9526. // fresnel term from fresnel shader
  9527. "const float mFresnelBias = 0.08;",
  9528. "const float mFresnelScale = 0.3;",
  9529. "const float mFresnelPower = 5.0;",
  9530. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9531. */
  9532. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9533. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9534. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9535. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9536. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9537. "#else",
  9538. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9539. "#endif",
  9540. "}",
  9541. "#endif",
  9542. "#if MAX_HEMI_LIGHTS > 0",
  9543. "vec3 hemiDiffuse = vec3( 0.0 );",
  9544. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9545. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9546. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9547. "vec3 lVector = normalize( lDirection.xyz );",
  9548. // diffuse
  9549. "float dotProduct = dot( normal, lVector );",
  9550. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9551. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9552. "hemiDiffuse += diffuse * hemiColor;",
  9553. // specular (sky light)
  9554. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9555. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9556. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9557. // specular (ground light)
  9558. "vec3 lVectorGround = -lVector;",
  9559. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9560. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9561. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9562. "#ifdef PHYSICALLY_BASED_SHADING",
  9563. "float dotProductGround = dot( normal, lVectorGround );",
  9564. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9565. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9566. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9567. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9568. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9569. "#else",
  9570. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9571. "#endif",
  9572. "}",
  9573. "#endif",
  9574. "vec3 totalDiffuse = vec3( 0.0 );",
  9575. "vec3 totalSpecular = vec3( 0.0 );",
  9576. "#if MAX_DIR_LIGHTS > 0",
  9577. "totalDiffuse += dirDiffuse;",
  9578. "totalSpecular += dirSpecular;",
  9579. "#endif",
  9580. "#if MAX_HEMI_LIGHTS > 0",
  9581. "totalDiffuse += hemiDiffuse;",
  9582. "totalSpecular += hemiSpecular;",
  9583. "#endif",
  9584. "#if MAX_POINT_LIGHTS > 0",
  9585. "totalDiffuse += pointDiffuse;",
  9586. "totalSpecular += pointSpecular;",
  9587. "#endif",
  9588. "#if MAX_SPOT_LIGHTS > 0",
  9589. "totalDiffuse += spotDiffuse;",
  9590. "totalSpecular += spotSpecular;",
  9591. "#endif",
  9592. "#ifdef METAL",
  9593. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9594. "#else",
  9595. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9596. "#endif"
  9597. ].join("\n"),
  9598. // VERTEX COLORS
  9599. color_pars_fragment: [
  9600. "#ifdef USE_COLOR",
  9601. "varying vec3 vColor;",
  9602. "#endif"
  9603. ].join("\n"),
  9604. color_fragment: [
  9605. "#ifdef USE_COLOR",
  9606. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9607. "#endif"
  9608. ].join("\n"),
  9609. color_pars_vertex: [
  9610. "#ifdef USE_COLOR",
  9611. "varying vec3 vColor;",
  9612. "#endif"
  9613. ].join("\n"),
  9614. color_vertex: [
  9615. "#ifdef USE_COLOR",
  9616. "#ifdef GAMMA_INPUT",
  9617. "vColor = color * color;",
  9618. "#else",
  9619. "vColor = color;",
  9620. "#endif",
  9621. "#endif"
  9622. ].join("\n"),
  9623. // SKINNING
  9624. skinning_pars_vertex: [
  9625. "#ifdef USE_SKINNING",
  9626. "#ifdef BONE_TEXTURE",
  9627. "uniform sampler2D boneTexture;",
  9628. "mat4 getBoneMatrix( const in float i ) {",
  9629. "float j = i * 4.0;",
  9630. "float x = mod( j, N_BONE_PIXEL_X );",
  9631. "float y = floor( j / N_BONE_PIXEL_X );",
  9632. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9633. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9634. "y = dy * ( y + 0.5 );",
  9635. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9636. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9637. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9638. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9639. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9640. "return bone;",
  9641. "}",
  9642. "#else",
  9643. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9644. "mat4 getBoneMatrix( const in float i ) {",
  9645. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9646. "return bone;",
  9647. "}",
  9648. "#endif",
  9649. "#endif"
  9650. ].join("\n"),
  9651. skinbase_vertex: [
  9652. "#ifdef USE_SKINNING",
  9653. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9654. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9655. "#endif"
  9656. ].join("\n"),
  9657. skinning_vertex: [
  9658. "#ifdef USE_SKINNING",
  9659. "#ifdef USE_MORPHTARGETS",
  9660. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9661. "#else",
  9662. "vec4 skinVertex = vec4( position, 1.0 );",
  9663. "#endif",
  9664. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9665. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9666. "#endif"
  9667. ].join("\n"),
  9668. // MORPHING
  9669. morphtarget_pars_vertex: [
  9670. "#ifdef USE_MORPHTARGETS",
  9671. "#ifndef USE_MORPHNORMALS",
  9672. "uniform float morphTargetInfluences[ 8 ];",
  9673. "#else",
  9674. "uniform float morphTargetInfluences[ 4 ];",
  9675. "#endif",
  9676. "#endif"
  9677. ].join("\n"),
  9678. morphtarget_vertex: [
  9679. "#ifdef USE_MORPHTARGETS",
  9680. "vec3 morphed = vec3( 0.0 );",
  9681. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9682. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9683. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9684. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9685. "#ifndef USE_MORPHNORMALS",
  9686. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9687. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9688. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9689. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9690. "#endif",
  9691. "morphed += position;",
  9692. "#endif"
  9693. ].join("\n"),
  9694. default_vertex : [
  9695. "vec4 mvPosition;",
  9696. "#ifdef USE_SKINNING",
  9697. "mvPosition = modelViewMatrix * skinned;",
  9698. "#endif",
  9699. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9700. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9701. "#endif",
  9702. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9703. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9704. "#endif",
  9705. "gl_Position = projectionMatrix * mvPosition;"
  9706. ].join("\n"),
  9707. morphnormal_vertex: [
  9708. "#ifdef USE_MORPHNORMALS",
  9709. "vec3 morphedNormal = vec3( 0.0 );",
  9710. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9711. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9712. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9713. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9714. "morphedNormal += normal;",
  9715. "#endif"
  9716. ].join("\n"),
  9717. skinnormal_vertex: [
  9718. "#ifdef USE_SKINNING",
  9719. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9720. "skinMatrix += skinWeight.y * boneMatY;",
  9721. "#ifdef USE_MORPHNORMALS",
  9722. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9723. "#else",
  9724. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9725. "#endif",
  9726. "#endif"
  9727. ].join("\n"),
  9728. defaultnormal_vertex: [
  9729. "vec3 objectNormal;",
  9730. "#ifdef USE_SKINNING",
  9731. "objectNormal = skinnedNormal.xyz;",
  9732. "#endif",
  9733. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9734. "objectNormal = morphedNormal;",
  9735. "#endif",
  9736. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9737. "objectNormal = normal;",
  9738. "#endif",
  9739. "#ifdef FLIP_SIDED",
  9740. "objectNormal = -objectNormal;",
  9741. "#endif",
  9742. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9743. ].join("\n"),
  9744. // SHADOW MAP
  9745. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9746. // http://spidergl.org/example.php?id=6
  9747. // http://fabiensanglard.net/shadowmapping
  9748. shadowmap_pars_fragment: [
  9749. "#ifdef USE_SHADOWMAP",
  9750. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9751. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9752. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9753. "uniform float shadowBias[ MAX_SHADOWS ];",
  9754. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9755. "float unpackDepth( const in vec4 rgba_depth ) {",
  9756. "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 );",
  9757. "float depth = dot( rgba_depth, bit_shift );",
  9758. "return depth;",
  9759. "}",
  9760. "#endif"
  9761. ].join("\n"),
  9762. shadowmap_fragment: [
  9763. "#ifdef USE_SHADOWMAP",
  9764. "#ifdef SHADOWMAP_DEBUG",
  9765. "vec3 frustumColors[3];",
  9766. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9767. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9768. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9769. "#endif",
  9770. "#ifdef SHADOWMAP_CASCADE",
  9771. "int inFrustumCount = 0;",
  9772. "#endif",
  9773. "float fDepth;",
  9774. "vec3 shadowColor = vec3( 1.0 );",
  9775. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9776. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9777. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9778. // "if ( all( something, something ) )" using this instead
  9779. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9780. "bool inFrustum = all( inFrustumVec );",
  9781. // don't shadow pixels outside of light frustum
  9782. // use just first frustum (for cascades)
  9783. // don't shadow pixels behind far plane of light frustum
  9784. "#ifdef SHADOWMAP_CASCADE",
  9785. "inFrustumCount += int( inFrustum );",
  9786. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9787. "#else",
  9788. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9789. "#endif",
  9790. "bool frustumTest = all( frustumTestVec );",
  9791. "if ( frustumTest ) {",
  9792. "shadowCoord.z += shadowBias[ i ];",
  9793. "#if defined( SHADOWMAP_TYPE_PCF )",
  9794. // Percentage-close filtering
  9795. // (9 pixel kernel)
  9796. // http://fabiensanglard.net/shadowmappingPCF/
  9797. "float shadow = 0.0;",
  9798. /*
  9799. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9800. // must enroll loop manually
  9801. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9802. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9803. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9804. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9805. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9806. "float fDepth = unpackDepth( rgbaDepth );",
  9807. "if ( fDepth < shadowCoord.z )",
  9808. "shadow += 1.0;",
  9809. "}",
  9810. "shadow /= 9.0;",
  9811. */
  9812. "const float shadowDelta = 1.0 / 9.0;",
  9813. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9814. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9815. "float dx0 = -1.25 * xPixelOffset;",
  9816. "float dy0 = -1.25 * yPixelOffset;",
  9817. "float dx1 = 1.25 * xPixelOffset;",
  9818. "float dy1 = 1.25 * yPixelOffset;",
  9819. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9820. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9821. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9822. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9823. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9824. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9825. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9826. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9827. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9828. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9829. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9830. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9831. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9832. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9833. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9834. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9835. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9836. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9837. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9838. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  9839. // Percentage-close filtering
  9840. // (9 pixel kernel)
  9841. // http://fabiensanglard.net/shadowmappingPCF/
  9842. "float shadow = 0.0;",
  9843. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9844. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9845. "float dx0 = -1.0 * xPixelOffset;",
  9846. "float dy0 = -1.0 * yPixelOffset;",
  9847. "float dx1 = 1.0 * xPixelOffset;",
  9848. "float dy1 = 1.0 * yPixelOffset;",
  9849. "mat3 shadowKernel;",
  9850. "mat3 depthKernel;",
  9851. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9852. "if ( depthKernel[0][0] < shadowCoord.z ) shadowKernel[0][0] = 0.25;",
  9853. "else shadowKernel[0][0] = 0.0;",
  9854. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9855. "if ( depthKernel[0][1] < shadowCoord.z ) shadowKernel[0][1] = 0.25;",
  9856. "else shadowKernel[0][1] = 0.0;",
  9857. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9858. "if ( depthKernel[0][2] < shadowCoord.z ) shadowKernel[0][2] = 0.25;",
  9859. "else shadowKernel[0][2] = 0.0;",
  9860. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9861. "if ( depthKernel[1][0] < shadowCoord.z ) shadowKernel[1][0] = 0.25;",
  9862. "else shadowKernel[1][0] = 0.0;",
  9863. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9864. "if ( depthKernel[1][1] < shadowCoord.z ) shadowKernel[1][1] = 0.25;",
  9865. "else shadowKernel[1][1] = 0.0;",
  9866. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9867. "if ( depthKernel[1][2] < shadowCoord.z ) shadowKernel[1][2] = 0.25;",
  9868. "else shadowKernel[1][2] = 0.0;",
  9869. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9870. "if ( depthKernel[2][0] < shadowCoord.z ) shadowKernel[2][0] = 0.25;",
  9871. "else shadowKernel[2][0] = 0.0;",
  9872. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9873. "if ( depthKernel[2][1] < shadowCoord.z ) shadowKernel[2][1] = 0.25;",
  9874. "else shadowKernel[2][1] = 0.0;",
  9875. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9876. "if ( depthKernel[2][2] < shadowCoord.z ) shadowKernel[2][2] = 0.25;",
  9877. "else shadowKernel[2][2] = 0.0;",
  9878. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  9879. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  9880. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  9881. "vec4 shadowValues;",
  9882. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  9883. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  9884. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  9885. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  9886. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  9887. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9888. "#else",
  9889. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  9890. "float fDepth = unpackDepth( rgbaDepth );",
  9891. "if ( fDepth < shadowCoord.z )",
  9892. // spot with multiple shadows is darker
  9893. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  9894. // spot with multiple shadows has the same color as single shadow spot
  9895. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  9896. "#endif",
  9897. "}",
  9898. "#ifdef SHADOWMAP_DEBUG",
  9899. "#ifdef SHADOWMAP_CASCADE",
  9900. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  9901. "#else",
  9902. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  9903. "#endif",
  9904. "#endif",
  9905. "}",
  9906. "#ifdef GAMMA_OUTPUT",
  9907. "shadowColor *= shadowColor;",
  9908. "#endif",
  9909. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  9910. "#endif"
  9911. ].join("\n"),
  9912. shadowmap_pars_vertex: [
  9913. "#ifdef USE_SHADOWMAP",
  9914. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9915. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  9916. "#endif"
  9917. ].join("\n"),
  9918. shadowmap_vertex: [
  9919. "#ifdef USE_SHADOWMAP",
  9920. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9921. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  9922. "}",
  9923. "#endif"
  9924. ].join("\n"),
  9925. // ALPHATEST
  9926. alphatest_fragment: [
  9927. "#ifdef ALPHATEST",
  9928. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  9929. "#endif"
  9930. ].join("\n"),
  9931. // LINEAR SPACE
  9932. linear_to_gamma_fragment: [
  9933. "#ifdef GAMMA_OUTPUT",
  9934. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9935. "#endif"
  9936. ].join("\n")
  9937. };
  9938. THREE.UniformsUtils = {
  9939. merge: function ( uniforms ) {
  9940. var u, p, tmp, merged = {};
  9941. for ( u = 0; u < uniforms.length; u ++ ) {
  9942. tmp = this.clone( uniforms[ u ] );
  9943. for ( p in tmp ) {
  9944. merged[ p ] = tmp[ p ];
  9945. }
  9946. }
  9947. return merged;
  9948. },
  9949. clone: function ( uniforms_src ) {
  9950. var u, p, parameter, parameter_src, uniforms_dst = {};
  9951. for ( u in uniforms_src ) {
  9952. uniforms_dst[ u ] = {};
  9953. for ( p in uniforms_src[ u ] ) {
  9954. parameter_src = uniforms_src[ u ][ p ];
  9955. if ( parameter_src instanceof THREE.Color ||
  9956. parameter_src instanceof THREE.Vector2 ||
  9957. parameter_src instanceof THREE.Vector3 ||
  9958. parameter_src instanceof THREE.Vector4 ||
  9959. parameter_src instanceof THREE.Matrix4 ||
  9960. parameter_src instanceof THREE.Texture ) {
  9961. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9962. } else if ( parameter_src instanceof Array ) {
  9963. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9964. } else {
  9965. uniforms_dst[ u ][ p ] = parameter_src;
  9966. }
  9967. }
  9968. }
  9969. return uniforms_dst;
  9970. }
  9971. };
  9972. THREE.UniformsLib = {
  9973. common: {
  9974. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9975. "opacity" : { type: "f", value: 1.0 },
  9976. "map" : { type: "t", value: null },
  9977. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9978. "lightMap" : { type: "t", value: null },
  9979. "specularMap" : { type: "t", value: null },
  9980. "envMap" : { type: "t", value: null },
  9981. "flipEnvMap" : { type: "f", value: -1 },
  9982. "useRefract" : { type: "i", value: 0 },
  9983. "reflectivity" : { type: "f", value: 1.0 },
  9984. "refractionRatio" : { type: "f", value: 0.98 },
  9985. "combine" : { type: "i", value: 0 },
  9986. "morphTargetInfluences" : { type: "f", value: 0 }
  9987. },
  9988. bump: {
  9989. "bumpMap" : { type: "t", value: null },
  9990. "bumpScale" : { type: "f", value: 1 }
  9991. },
  9992. normalmap: {
  9993. "normalMap" : { type: "t", value: null },
  9994. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9995. },
  9996. fog : {
  9997. "fogDensity" : { type: "f", value: 0.00025 },
  9998. "fogNear" : { type: "f", value: 1 },
  9999. "fogFar" : { type: "f", value: 2000 },
  10000. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10001. },
  10002. lights: {
  10003. "ambientLightColor" : { type: "fv", value: [] },
  10004. "directionalLightDirection" : { type: "fv", value: [] },
  10005. "directionalLightColor" : { type: "fv", value: [] },
  10006. "hemisphereLightDirection" : { type: "fv", value: [] },
  10007. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10008. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10009. "pointLightColor" : { type: "fv", value: [] },
  10010. "pointLightPosition" : { type: "fv", value: [] },
  10011. "pointLightDistance" : { type: "fv1", value: [] },
  10012. "spotLightColor" : { type: "fv", value: [] },
  10013. "spotLightPosition" : { type: "fv", value: [] },
  10014. "spotLightDirection" : { type: "fv", value: [] },
  10015. "spotLightDistance" : { type: "fv1", value: [] },
  10016. "spotLightAngleCos" : { type: "fv1", value: [] },
  10017. "spotLightExponent" : { type: "fv1", value: [] }
  10018. },
  10019. particle: {
  10020. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10021. "opacity" : { type: "f", value: 1.0 },
  10022. "size" : { type: "f", value: 1.0 },
  10023. "scale" : { type: "f", value: 1.0 },
  10024. "map" : { type: "t", value: null },
  10025. "fogDensity" : { type: "f", value: 0.00025 },
  10026. "fogNear" : { type: "f", value: 1 },
  10027. "fogFar" : { type: "f", value: 2000 },
  10028. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10029. },
  10030. shadowmap: {
  10031. "shadowMap": { type: "tv", value: [] },
  10032. "shadowMapSize": { type: "v2v", value: [] },
  10033. "shadowBias" : { type: "fv1", value: [] },
  10034. "shadowDarkness": { type: "fv1", value: [] },
  10035. "shadowMatrix" : { type: "m4v", value: [] }
  10036. }
  10037. };
  10038. THREE.ShaderLib = {
  10039. 'depth': {
  10040. uniforms: {
  10041. "mNear": { type: "f", value: 1.0 },
  10042. "mFar" : { type: "f", value: 2000.0 },
  10043. "opacity" : { type: "f", value: 1.0 }
  10044. },
  10045. vertexShader: [
  10046. "void main() {",
  10047. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10048. "}"
  10049. ].join("\n"),
  10050. fragmentShader: [
  10051. "uniform float mNear;",
  10052. "uniform float mFar;",
  10053. "uniform float opacity;",
  10054. "void main() {",
  10055. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10056. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10057. "gl_FragColor = vec4( vec3( color ), opacity );",
  10058. "}"
  10059. ].join("\n")
  10060. },
  10061. 'normal': {
  10062. uniforms: {
  10063. "opacity" : { type: "f", value: 1.0 }
  10064. },
  10065. vertexShader: [
  10066. "varying vec3 vNormal;",
  10067. "void main() {",
  10068. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10069. "vNormal = normalize( normalMatrix * normal );",
  10070. "gl_Position = projectionMatrix * mvPosition;",
  10071. "}"
  10072. ].join("\n"),
  10073. fragmentShader: [
  10074. "uniform float opacity;",
  10075. "varying vec3 vNormal;",
  10076. "void main() {",
  10077. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10078. "}"
  10079. ].join("\n")
  10080. },
  10081. 'basic': {
  10082. uniforms: THREE.UniformsUtils.merge( [
  10083. THREE.UniformsLib[ "common" ],
  10084. THREE.UniformsLib[ "fog" ],
  10085. THREE.UniformsLib[ "shadowmap" ]
  10086. ] ),
  10087. vertexShader: [
  10088. THREE.ShaderChunk[ "map_pars_vertex" ],
  10089. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10090. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10091. THREE.ShaderChunk[ "color_pars_vertex" ],
  10092. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10093. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10094. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10095. "void main() {",
  10096. THREE.ShaderChunk[ "map_vertex" ],
  10097. THREE.ShaderChunk[ "lightmap_vertex" ],
  10098. THREE.ShaderChunk[ "color_vertex" ],
  10099. THREE.ShaderChunk[ "skinbase_vertex" ],
  10100. "#ifdef USE_ENVMAP",
  10101. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10102. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10103. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10104. "#endif",
  10105. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10106. THREE.ShaderChunk[ "skinning_vertex" ],
  10107. THREE.ShaderChunk[ "default_vertex" ],
  10108. THREE.ShaderChunk[ "worldpos_vertex" ],
  10109. THREE.ShaderChunk[ "envmap_vertex" ],
  10110. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10111. "}"
  10112. ].join("\n"),
  10113. fragmentShader: [
  10114. "uniform vec3 diffuse;",
  10115. "uniform float opacity;",
  10116. THREE.ShaderChunk[ "color_pars_fragment" ],
  10117. THREE.ShaderChunk[ "map_pars_fragment" ],
  10118. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10119. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10120. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10121. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10122. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10123. "void main() {",
  10124. "gl_FragColor = vec4( diffuse, opacity );",
  10125. THREE.ShaderChunk[ "map_fragment" ],
  10126. THREE.ShaderChunk[ "alphatest_fragment" ],
  10127. THREE.ShaderChunk[ "specularmap_fragment" ],
  10128. THREE.ShaderChunk[ "lightmap_fragment" ],
  10129. THREE.ShaderChunk[ "color_fragment" ],
  10130. THREE.ShaderChunk[ "envmap_fragment" ],
  10131. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10132. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10133. THREE.ShaderChunk[ "fog_fragment" ],
  10134. "}"
  10135. ].join("\n")
  10136. },
  10137. 'lambert': {
  10138. uniforms: THREE.UniformsUtils.merge( [
  10139. THREE.UniformsLib[ "common" ],
  10140. THREE.UniformsLib[ "fog" ],
  10141. THREE.UniformsLib[ "lights" ],
  10142. THREE.UniformsLib[ "shadowmap" ],
  10143. {
  10144. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10145. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10146. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10147. }
  10148. ] ),
  10149. vertexShader: [
  10150. "#define LAMBERT",
  10151. "varying vec3 vLightFront;",
  10152. "#ifdef DOUBLE_SIDED",
  10153. "varying vec3 vLightBack;",
  10154. "#endif",
  10155. THREE.ShaderChunk[ "map_pars_vertex" ],
  10156. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10157. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10158. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10159. THREE.ShaderChunk[ "color_pars_vertex" ],
  10160. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10161. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10162. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10163. "void main() {",
  10164. THREE.ShaderChunk[ "map_vertex" ],
  10165. THREE.ShaderChunk[ "lightmap_vertex" ],
  10166. THREE.ShaderChunk[ "color_vertex" ],
  10167. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10168. THREE.ShaderChunk[ "skinbase_vertex" ],
  10169. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10170. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10171. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10172. THREE.ShaderChunk[ "skinning_vertex" ],
  10173. THREE.ShaderChunk[ "default_vertex" ],
  10174. THREE.ShaderChunk[ "worldpos_vertex" ],
  10175. THREE.ShaderChunk[ "envmap_vertex" ],
  10176. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10177. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10178. "}"
  10179. ].join("\n"),
  10180. fragmentShader: [
  10181. "uniform float opacity;",
  10182. "varying vec3 vLightFront;",
  10183. "#ifdef DOUBLE_SIDED",
  10184. "varying vec3 vLightBack;",
  10185. "#endif",
  10186. THREE.ShaderChunk[ "color_pars_fragment" ],
  10187. THREE.ShaderChunk[ "map_pars_fragment" ],
  10188. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10189. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10190. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10191. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10192. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10193. "void main() {",
  10194. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10195. THREE.ShaderChunk[ "map_fragment" ],
  10196. THREE.ShaderChunk[ "alphatest_fragment" ],
  10197. THREE.ShaderChunk[ "specularmap_fragment" ],
  10198. "#ifdef DOUBLE_SIDED",
  10199. //"float isFront = float( gl_FrontFacing );",
  10200. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10201. "if ( gl_FrontFacing )",
  10202. "gl_FragColor.xyz *= vLightFront;",
  10203. "else",
  10204. "gl_FragColor.xyz *= vLightBack;",
  10205. "#else",
  10206. "gl_FragColor.xyz *= vLightFront;",
  10207. "#endif",
  10208. THREE.ShaderChunk[ "lightmap_fragment" ],
  10209. THREE.ShaderChunk[ "color_fragment" ],
  10210. THREE.ShaderChunk[ "envmap_fragment" ],
  10211. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10212. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10213. THREE.ShaderChunk[ "fog_fragment" ],
  10214. "}"
  10215. ].join("\n")
  10216. },
  10217. 'phong': {
  10218. uniforms: THREE.UniformsUtils.merge( [
  10219. THREE.UniformsLib[ "common" ],
  10220. THREE.UniformsLib[ "bump" ],
  10221. THREE.UniformsLib[ "normalmap" ],
  10222. THREE.UniformsLib[ "fog" ],
  10223. THREE.UniformsLib[ "lights" ],
  10224. THREE.UniformsLib[ "shadowmap" ],
  10225. {
  10226. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10227. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10228. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10229. "shininess": { type: "f", value: 30 },
  10230. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10231. }
  10232. ] ),
  10233. vertexShader: [
  10234. "#define PHONG",
  10235. "varying vec3 vViewPosition;",
  10236. "varying vec3 vNormal;",
  10237. THREE.ShaderChunk[ "map_pars_vertex" ],
  10238. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10239. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10240. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10241. THREE.ShaderChunk[ "color_pars_vertex" ],
  10242. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10243. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10244. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10245. "void main() {",
  10246. THREE.ShaderChunk[ "map_vertex" ],
  10247. THREE.ShaderChunk[ "lightmap_vertex" ],
  10248. THREE.ShaderChunk[ "color_vertex" ],
  10249. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10250. THREE.ShaderChunk[ "skinbase_vertex" ],
  10251. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10252. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10253. "vNormal = normalize( transformedNormal );",
  10254. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10255. THREE.ShaderChunk[ "skinning_vertex" ],
  10256. THREE.ShaderChunk[ "default_vertex" ],
  10257. "vViewPosition = -mvPosition.xyz;",
  10258. THREE.ShaderChunk[ "worldpos_vertex" ],
  10259. THREE.ShaderChunk[ "envmap_vertex" ],
  10260. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10261. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10262. "}"
  10263. ].join("\n"),
  10264. fragmentShader: [
  10265. "uniform vec3 diffuse;",
  10266. "uniform float opacity;",
  10267. "uniform vec3 ambient;",
  10268. "uniform vec3 emissive;",
  10269. "uniform vec3 specular;",
  10270. "uniform float shininess;",
  10271. THREE.ShaderChunk[ "color_pars_fragment" ],
  10272. THREE.ShaderChunk[ "map_pars_fragment" ],
  10273. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10274. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10275. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10276. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10277. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10278. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10279. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10280. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10281. "void main() {",
  10282. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10283. THREE.ShaderChunk[ "map_fragment" ],
  10284. THREE.ShaderChunk[ "alphatest_fragment" ],
  10285. THREE.ShaderChunk[ "specularmap_fragment" ],
  10286. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10287. THREE.ShaderChunk[ "lightmap_fragment" ],
  10288. THREE.ShaderChunk[ "color_fragment" ],
  10289. THREE.ShaderChunk[ "envmap_fragment" ],
  10290. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10291. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10292. THREE.ShaderChunk[ "fog_fragment" ],
  10293. "}"
  10294. ].join("\n")
  10295. },
  10296. 'particle_basic': {
  10297. uniforms: THREE.UniformsUtils.merge( [
  10298. THREE.UniformsLib[ "particle" ],
  10299. THREE.UniformsLib[ "shadowmap" ]
  10300. ] ),
  10301. vertexShader: [
  10302. "uniform float size;",
  10303. "uniform float scale;",
  10304. THREE.ShaderChunk[ "color_pars_vertex" ],
  10305. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10306. "void main() {",
  10307. THREE.ShaderChunk[ "color_vertex" ],
  10308. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10309. "#ifdef USE_SIZEATTENUATION",
  10310. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10311. "#else",
  10312. "gl_PointSize = size;",
  10313. "#endif",
  10314. "gl_Position = projectionMatrix * mvPosition;",
  10315. THREE.ShaderChunk[ "worldpos_vertex" ],
  10316. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10317. "}"
  10318. ].join("\n"),
  10319. fragmentShader: [
  10320. "uniform vec3 psColor;",
  10321. "uniform float opacity;",
  10322. THREE.ShaderChunk[ "color_pars_fragment" ],
  10323. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10324. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10325. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10326. "void main() {",
  10327. "gl_FragColor = vec4( psColor, opacity );",
  10328. THREE.ShaderChunk[ "map_particle_fragment" ],
  10329. THREE.ShaderChunk[ "alphatest_fragment" ],
  10330. THREE.ShaderChunk[ "color_fragment" ],
  10331. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10332. THREE.ShaderChunk[ "fog_fragment" ],
  10333. "}"
  10334. ].join("\n")
  10335. },
  10336. 'dashed': {
  10337. uniforms: THREE.UniformsUtils.merge( [
  10338. THREE.UniformsLib[ "common" ],
  10339. THREE.UniformsLib[ "fog" ],
  10340. {
  10341. "scale": { type: "f", value: 1 },
  10342. "dashSize": { type: "f", value: 1 },
  10343. "totalSize": { type: "f", value: 2 }
  10344. }
  10345. ] ),
  10346. vertexShader: [
  10347. "uniform float scale;",
  10348. "attribute float lineDistance;",
  10349. "varying float vLineDistance;",
  10350. THREE.ShaderChunk[ "color_pars_vertex" ],
  10351. "void main() {",
  10352. THREE.ShaderChunk[ "color_vertex" ],
  10353. "vLineDistance = scale * lineDistance;",
  10354. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10355. "gl_Position = projectionMatrix * mvPosition;",
  10356. "}"
  10357. ].join("\n"),
  10358. fragmentShader: [
  10359. "uniform vec3 diffuse;",
  10360. "uniform float opacity;",
  10361. "uniform float dashSize;",
  10362. "uniform float totalSize;",
  10363. "varying float vLineDistance;",
  10364. THREE.ShaderChunk[ "color_pars_fragment" ],
  10365. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10366. "void main() {",
  10367. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10368. "discard;",
  10369. "}",
  10370. "gl_FragColor = vec4( diffuse, opacity );",
  10371. THREE.ShaderChunk[ "color_fragment" ],
  10372. THREE.ShaderChunk[ "fog_fragment" ],
  10373. "}"
  10374. ].join("\n")
  10375. },
  10376. // Depth encoding into RGBA texture
  10377. // based on SpiderGL shadow map example
  10378. // http://spidergl.org/example.php?id=6
  10379. // originally from
  10380. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10381. // see also here:
  10382. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10383. 'depthRGBA': {
  10384. uniforms: {},
  10385. vertexShader: [
  10386. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10387. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10388. "void main() {",
  10389. THREE.ShaderChunk[ "skinbase_vertex" ],
  10390. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10391. THREE.ShaderChunk[ "skinning_vertex" ],
  10392. THREE.ShaderChunk[ "default_vertex" ],
  10393. "}"
  10394. ].join("\n"),
  10395. fragmentShader: [
  10396. "vec4 pack_depth( const in float depth ) {",
  10397. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10398. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10399. "vec4 res = fract( depth * bit_shift );",
  10400. "res -= res.xxyz * bit_mask;",
  10401. "return res;",
  10402. "}",
  10403. "void main() {",
  10404. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10405. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10406. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10407. //"gl_FragData[ 0 ] = pack_depth( z );",
  10408. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10409. "}"
  10410. ].join("\n")
  10411. }
  10412. };
  10413. /**
  10414. * @author supereggbert / http://www.paulbrunt.co.uk/
  10415. * @author mrdoob / http://mrdoob.com/
  10416. * @author alteredq / http://alteredqualia.com/
  10417. * @author szimek / https://github.com/szimek/
  10418. */
  10419. THREE.WebGLRenderer = function ( parameters ) {
  10420. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10421. parameters = parameters || {};
  10422. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10423. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10424. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  10425. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10426. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10427. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10428. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10429. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  10430. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  10431. // public properties
  10432. this.domElement = _canvas;
  10433. this.context = null;
  10434. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  10435. ? parameters.devicePixelRatio
  10436. : window.devicePixelRatio !== undefined
  10437. ? window.devicePixelRatio
  10438. : 1;
  10439. // clearing
  10440. this.autoClear = true;
  10441. this.autoClearColor = true;
  10442. this.autoClearDepth = true;
  10443. this.autoClearStencil = true;
  10444. // scene graph
  10445. this.sortObjects = true;
  10446. this.autoUpdateObjects = true;
  10447. this.autoUpdateScene = true;
  10448. // physically based shading
  10449. this.gammaInput = false;
  10450. this.gammaOutput = false;
  10451. this.physicallyBasedShading = false;
  10452. // shadow map
  10453. this.shadowMapEnabled = false;
  10454. this.shadowMapAutoUpdate = true;
  10455. this.shadowMapType = THREE.PCFShadowMap;
  10456. this.shadowMapCullFace = THREE.CullFaceFront;
  10457. this.shadowMapDebug = false;
  10458. this.shadowMapCascade = false;
  10459. // morphs
  10460. this.maxMorphTargets = 8;
  10461. this.maxMorphNormals = 4;
  10462. // flags
  10463. this.autoScaleCubemaps = true;
  10464. // custom render plugins
  10465. this.renderPluginsPre = [];
  10466. this.renderPluginsPost = [];
  10467. // info
  10468. this.info = {
  10469. memory: {
  10470. programs: 0,
  10471. geometries: 0,
  10472. textures: 0
  10473. },
  10474. render: {
  10475. calls: 0,
  10476. vertices: 0,
  10477. faces: 0,
  10478. points: 0
  10479. }
  10480. };
  10481. // internal properties
  10482. var _this = this,
  10483. _programs = [],
  10484. _programs_counter = 0,
  10485. // internal state cache
  10486. _currentProgram = null,
  10487. _currentFramebuffer = null,
  10488. _currentMaterialId = -1,
  10489. _currentGeometryGroupHash = null,
  10490. _currentCamera = null,
  10491. _geometryGroupCounter = 0,
  10492. _usedTextureUnits = 0,
  10493. // GL state cache
  10494. _oldDoubleSided = -1,
  10495. _oldFlipSided = -1,
  10496. _oldBlending = -1,
  10497. _oldBlendEquation = -1,
  10498. _oldBlendSrc = -1,
  10499. _oldBlendDst = -1,
  10500. _oldDepthTest = -1,
  10501. _oldDepthWrite = -1,
  10502. _oldPolygonOffset = null,
  10503. _oldPolygonOffsetFactor = null,
  10504. _oldPolygonOffsetUnits = null,
  10505. _oldLineWidth = null,
  10506. _viewportX = 0,
  10507. _viewportY = 0,
  10508. _viewportWidth = 0,
  10509. _viewportHeight = 0,
  10510. _currentWidth = 0,
  10511. _currentHeight = 0,
  10512. _enabledAttributes = {},
  10513. // frustum
  10514. _frustum = new THREE.Frustum(),
  10515. // camera matrices cache
  10516. _projScreenMatrix = new THREE.Matrix4(),
  10517. _projScreenMatrixPS = new THREE.Matrix4(),
  10518. _vector3 = new THREE.Vector3(),
  10519. // light arrays cache
  10520. _direction = new THREE.Vector3(),
  10521. _lightsNeedUpdate = true,
  10522. _lights = {
  10523. ambient: [ 0, 0, 0 ],
  10524. directional: { length: 0, colors: new Array(), positions: new Array() },
  10525. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  10526. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  10527. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  10528. };
  10529. // initialize
  10530. var _gl;
  10531. var _glExtensionTextureFloat;
  10532. var _glExtensionStandardDerivatives;
  10533. var _glExtensionTextureFilterAnisotropic;
  10534. var _glExtensionCompressedTextureS3TC;
  10535. initGL();
  10536. setDefaultGLState();
  10537. this.context = _gl;
  10538. // GPU capabilities
  10539. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10540. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10541. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10542. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10543. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10544. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  10545. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  10546. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  10547. //
  10548. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  10549. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  10550. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  10551. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  10552. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  10553. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  10554. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  10555. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  10556. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  10557. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  10558. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  10559. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  10560. // clamp precision to maximum available
  10561. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  10562. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  10563. if ( _precision === "highp" && ! highpAvailable ) {
  10564. if ( mediumpAvailable ) {
  10565. _precision = "mediump";
  10566. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  10567. } else {
  10568. _precision = "lowp";
  10569. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  10570. }
  10571. }
  10572. if ( _precision === "mediump" && ! mediumpAvailable ) {
  10573. _precision = "lowp";
  10574. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  10575. }
  10576. // API
  10577. this.getContext = function () {
  10578. return _gl;
  10579. };
  10580. this.supportsVertexTextures = function () {
  10581. return _supportsVertexTextures;
  10582. };
  10583. this.getMaxAnisotropy = function () {
  10584. return _maxAnisotropy;
  10585. };
  10586. this.getPrecision = function () {
  10587. return _precision;
  10588. };
  10589. this.setSize = function ( width, height ) {
  10590. _canvas.width = width * this.devicePixelRatio;
  10591. _canvas.height = height * this.devicePixelRatio;
  10592. _canvas.style.width = width + 'px';
  10593. _canvas.style.height = height + 'px';
  10594. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  10595. };
  10596. this.setViewport = function ( x, y, width, height ) {
  10597. _viewportX = x !== undefined ? x : 0;
  10598. _viewportY = y !== undefined ? y : 0;
  10599. _viewportWidth = width !== undefined ? width : _canvas.width;
  10600. _viewportHeight = height !== undefined ? height : _canvas.height;
  10601. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10602. };
  10603. this.setScissor = function ( x, y, width, height ) {
  10604. _gl.scissor( x, y, width, height );
  10605. };
  10606. this.enableScissorTest = function ( enable ) {
  10607. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  10608. };
  10609. // Clearing
  10610. this.setClearColorHex = function ( hex, alpha ) {
  10611. _clearColor.setHex( hex );
  10612. _clearAlpha = alpha;
  10613. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10614. };
  10615. this.setClearColor = function ( color, alpha ) {
  10616. _clearColor.copy( color );
  10617. _clearAlpha = alpha;
  10618. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10619. };
  10620. this.getClearColor = function () {
  10621. return _clearColor;
  10622. };
  10623. this.getClearAlpha = function () {
  10624. return _clearAlpha;
  10625. };
  10626. this.clear = function ( color, depth, stencil ) {
  10627. var bits = 0;
  10628. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  10629. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  10630. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  10631. _gl.clear( bits );
  10632. };
  10633. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  10634. this.setRenderTarget( renderTarget );
  10635. this.clear( color, depth, stencil );
  10636. };
  10637. // Plugins
  10638. this.addPostPlugin = function ( plugin ) {
  10639. plugin.init( this );
  10640. this.renderPluginsPost.push( plugin );
  10641. };
  10642. this.addPrePlugin = function ( plugin ) {
  10643. plugin.init( this );
  10644. this.renderPluginsPre.push( plugin );
  10645. };
  10646. // Rendering
  10647. this.updateShadowMap = function ( scene, camera ) {
  10648. _currentProgram = null;
  10649. _oldBlending = -1;
  10650. _oldDepthTest = -1;
  10651. _oldDepthWrite = -1;
  10652. _currentGeometryGroupHash = -1;
  10653. _currentMaterialId = -1;
  10654. _lightsNeedUpdate = true;
  10655. _oldDoubleSided = -1;
  10656. _oldFlipSided = -1;
  10657. this.shadowMapPlugin.update( scene, camera );
  10658. };
  10659. // Internal functions
  10660. // Buffer allocation
  10661. function createParticleBuffers ( geometry ) {
  10662. geometry.__webglVertexBuffer = _gl.createBuffer();
  10663. geometry.__webglColorBuffer = _gl.createBuffer();
  10664. _this.info.memory.geometries ++;
  10665. };
  10666. function createLineBuffers ( geometry ) {
  10667. geometry.__webglVertexBuffer = _gl.createBuffer();
  10668. geometry.__webglColorBuffer = _gl.createBuffer();
  10669. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  10670. _this.info.memory.geometries ++;
  10671. };
  10672. function createRibbonBuffers ( geometry ) {
  10673. geometry.__webglVertexBuffer = _gl.createBuffer();
  10674. geometry.__webglColorBuffer = _gl.createBuffer();
  10675. geometry.__webglNormalBuffer = _gl.createBuffer();
  10676. _this.info.memory.geometries ++;
  10677. };
  10678. function createMeshBuffers ( geometryGroup ) {
  10679. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  10680. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  10681. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  10682. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  10683. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  10684. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  10685. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  10686. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  10687. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  10688. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  10689. var m, ml;
  10690. if ( geometryGroup.numMorphTargets ) {
  10691. geometryGroup.__webglMorphTargetsBuffers = [];
  10692. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10693. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  10694. }
  10695. }
  10696. if ( geometryGroup.numMorphNormals ) {
  10697. geometryGroup.__webglMorphNormalsBuffers = [];
  10698. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10699. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  10700. }
  10701. }
  10702. _this.info.memory.geometries ++;
  10703. };
  10704. // Events
  10705. var onGeometryDispose = function ( event ) {
  10706. var geometry = event.target;
  10707. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10708. deallocateGeometry( geometry );
  10709. _this.info.memory.geometries --;
  10710. };
  10711. var onTextureDispose = function ( event ) {
  10712. var texture = event.target;
  10713. texture.removeEventListener( 'dispose', onTextureDispose );
  10714. deallocateTexture( texture );
  10715. _this.info.memory.textures --;
  10716. };
  10717. var onRenderTargetDispose = function ( event ) {
  10718. var renderTarget = event.target;
  10719. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10720. deallocateRenderTarget( renderTarget );
  10721. _this.info.memory.textures --;
  10722. };
  10723. var onMaterialDispose = function ( event ) {
  10724. var material = event.target;
  10725. material.removeEventListener( 'dispose', onMaterialDispose );
  10726. deallocateMaterial( material );
  10727. };
  10728. // Buffer deallocation
  10729. var deallocateGeometry = function ( geometry ) {
  10730. geometry.__webglInit = undefined;
  10731. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10732. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10733. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  10734. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  10735. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  10736. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  10737. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  10738. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  10739. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  10740. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  10741. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10742. // geometry groups
  10743. if ( geometry.geometryGroups !== undefined ) {
  10744. for ( var g in geometry.geometryGroups ) {
  10745. var geometryGroup = geometry.geometryGroups[ g ];
  10746. if ( geometryGroup.numMorphTargets !== undefined ) {
  10747. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10748. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10749. }
  10750. }
  10751. if ( geometryGroup.numMorphNormals !== undefined ) {
  10752. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10753. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10754. }
  10755. }
  10756. deleteCustomAttributesBuffers( geometryGroup );
  10757. }
  10758. }
  10759. deleteCustomAttributesBuffers( geometry );
  10760. };
  10761. var deallocateTexture = function ( texture ) {
  10762. if ( texture.image && texture.image.__webglTextureCube ) {
  10763. // cube texture
  10764. _gl.deleteTexture( texture.image.__webglTextureCube );
  10765. } else {
  10766. // 2D texture
  10767. if ( ! texture.__webglInit ) return;
  10768. texture.__webglInit = false;
  10769. _gl.deleteTexture( texture.__webglTexture );
  10770. }
  10771. };
  10772. var deallocateRenderTarget = function ( renderTarget ) {
  10773. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  10774. _gl.deleteTexture( renderTarget.__webglTexture );
  10775. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  10776. for ( var i = 0; i < 6; i ++ ) {
  10777. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  10778. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  10779. }
  10780. } else {
  10781. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  10782. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  10783. }
  10784. };
  10785. var deallocateMaterial = function ( material ) {
  10786. var program = material.program;
  10787. if ( program === undefined ) return;
  10788. material.program = undefined;
  10789. // only deallocate GL program if this was the last use of shared program
  10790. // assumed there is only single copy of any program in the _programs list
  10791. // (that's how it's constructed)
  10792. var i, il, programInfo;
  10793. var deleteProgram = false;
  10794. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10795. programInfo = _programs[ i ];
  10796. if ( programInfo.program === program ) {
  10797. programInfo.usedTimes --;
  10798. if ( programInfo.usedTimes === 0 ) {
  10799. deleteProgram = true;
  10800. }
  10801. break;
  10802. }
  10803. }
  10804. if ( deleteProgram === true ) {
  10805. // avoid using array.splice, this is costlier than creating new array from scratch
  10806. var newPrograms = [];
  10807. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10808. programInfo = _programs[ i ];
  10809. if ( programInfo.program !== program ) {
  10810. newPrograms.push( programInfo );
  10811. }
  10812. }
  10813. _programs = newPrograms;
  10814. _gl.deleteProgram( program );
  10815. _this.info.memory.programs --;
  10816. }
  10817. };
  10818. //
  10819. /*
  10820. function deleteParticleBuffers ( geometry ) {
  10821. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10822. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10823. deleteCustomAttributesBuffers( geometry );
  10824. _this.info.memory.geometries --;
  10825. };
  10826. function deleteLineBuffers ( geometry ) {
  10827. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10828. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10829. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10830. deleteCustomAttributesBuffers( geometry );
  10831. _this.info.memory.geometries --;
  10832. };
  10833. function deleteRibbonBuffers ( geometry ) {
  10834. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10835. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10836. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10837. deleteCustomAttributesBuffers( geometry );
  10838. _this.info.memory.geometries --;
  10839. };
  10840. function deleteMeshBuffers ( geometryGroup ) {
  10841. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  10842. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  10843. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  10844. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  10845. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  10846. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  10847. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  10848. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  10849. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  10850. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  10851. var m, ml;
  10852. if ( geometryGroup.numMorphTargets ) {
  10853. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10854. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10855. }
  10856. }
  10857. if ( geometryGroup.numMorphNormals ) {
  10858. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10859. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10860. }
  10861. }
  10862. deleteCustomAttributesBuffers( geometryGroup );
  10863. _this.info.memory.geometries --;
  10864. };
  10865. */
  10866. function deleteCustomAttributesBuffers( geometry ) {
  10867. if ( geometry.__webglCustomAttributesList ) {
  10868. for ( var id in geometry.__webglCustomAttributesList ) {
  10869. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  10870. }
  10871. }
  10872. };
  10873. // Buffer initialization
  10874. function initCustomAttributes ( geometry, object ) {
  10875. var nvertices = geometry.vertices.length;
  10876. var material = object.material;
  10877. if ( material.attributes ) {
  10878. if ( geometry.__webglCustomAttributesList === undefined ) {
  10879. geometry.__webglCustomAttributesList = [];
  10880. }
  10881. for ( var a in material.attributes ) {
  10882. var attribute = material.attributes[ a ];
  10883. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10884. attribute.__webglInitialized = true;
  10885. var size = 1; // "f" and "i"
  10886. if ( attribute.type === "v2" ) size = 2;
  10887. else if ( attribute.type === "v3" ) size = 3;
  10888. else if ( attribute.type === "v4" ) size = 4;
  10889. else if ( attribute.type === "c" ) size = 3;
  10890. attribute.size = size;
  10891. attribute.array = new Float32Array( nvertices * size );
  10892. attribute.buffer = _gl.createBuffer();
  10893. attribute.buffer.belongsToAttribute = a;
  10894. attribute.needsUpdate = true;
  10895. }
  10896. geometry.__webglCustomAttributesList.push( attribute );
  10897. }
  10898. }
  10899. };
  10900. function initParticleBuffers ( geometry, object ) {
  10901. var nvertices = geometry.vertices.length;
  10902. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10903. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10904. geometry.__sortArray = [];
  10905. geometry.__webglParticleCount = nvertices;
  10906. initCustomAttributes ( geometry, object );
  10907. };
  10908. function initLineBuffers ( geometry, object ) {
  10909. var nvertices = geometry.vertices.length;
  10910. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10911. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10912. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  10913. geometry.__webglLineCount = nvertices;
  10914. initCustomAttributes ( geometry, object );
  10915. };
  10916. function initRibbonBuffers ( geometry, object ) {
  10917. var nvertices = geometry.vertices.length;
  10918. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10919. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10920. geometry.__normalArray = new Float32Array( nvertices * 3 );
  10921. geometry.__webglVertexCount = nvertices;
  10922. initCustomAttributes ( geometry, object );
  10923. };
  10924. function initMeshBuffers ( geometryGroup, object ) {
  10925. var geometry = object.geometry,
  10926. faces3 = geometryGroup.faces3,
  10927. faces4 = geometryGroup.faces4,
  10928. nvertices = faces3.length * 3 + faces4.length * 4,
  10929. ntris = faces3.length * 1 + faces4.length * 2,
  10930. nlines = faces3.length * 3 + faces4.length * 4,
  10931. material = getBufferMaterial( object, geometryGroup ),
  10932. uvType = bufferGuessUVType( material ),
  10933. normalType = bufferGuessNormalType( material ),
  10934. vertexColorType = bufferGuessVertexColorType( material );
  10935. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  10936. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  10937. if ( normalType ) {
  10938. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  10939. }
  10940. if ( geometry.hasTangents ) {
  10941. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  10942. }
  10943. if ( vertexColorType ) {
  10944. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  10945. }
  10946. if ( uvType ) {
  10947. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  10948. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  10949. }
  10950. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  10951. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  10952. }
  10953. }
  10954. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  10955. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  10956. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  10957. }
  10958. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  10959. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  10960. var m, ml;
  10961. if ( geometryGroup.numMorphTargets ) {
  10962. geometryGroup.__morphTargetsArrays = [];
  10963. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10964. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  10965. }
  10966. }
  10967. if ( geometryGroup.numMorphNormals ) {
  10968. geometryGroup.__morphNormalsArrays = [];
  10969. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10970. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  10971. }
  10972. }
  10973. geometryGroup.__webglFaceCount = ntris * 3;
  10974. geometryGroup.__webglLineCount = nlines * 2;
  10975. // custom attributes
  10976. if ( material.attributes ) {
  10977. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  10978. geometryGroup.__webglCustomAttributesList = [];
  10979. }
  10980. for ( var a in material.attributes ) {
  10981. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  10982. // attribute buffers which are correctly indexed in the setMeshBuffers function
  10983. var originalAttribute = material.attributes[ a ];
  10984. var attribute = {};
  10985. for ( var property in originalAttribute ) {
  10986. attribute[ property ] = originalAttribute[ property ];
  10987. }
  10988. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10989. attribute.__webglInitialized = true;
  10990. var size = 1; // "f" and "i"
  10991. if( attribute.type === "v2" ) size = 2;
  10992. else if( attribute.type === "v3" ) size = 3;
  10993. else if( attribute.type === "v4" ) size = 4;
  10994. else if( attribute.type === "c" ) size = 3;
  10995. attribute.size = size;
  10996. attribute.array = new Float32Array( nvertices * size );
  10997. attribute.buffer = _gl.createBuffer();
  10998. attribute.buffer.belongsToAttribute = a;
  10999. originalAttribute.needsUpdate = true;
  11000. attribute.__original = originalAttribute;
  11001. }
  11002. geometryGroup.__webglCustomAttributesList.push( attribute );
  11003. }
  11004. }
  11005. geometryGroup.__inittedArrays = true;
  11006. };
  11007. function getBufferMaterial( object, geometryGroup ) {
  11008. return object.material instanceof THREE.MeshFaceMaterial
  11009. ? object.material.materials[ geometryGroup.materialIndex ]
  11010. : object.material;
  11011. };
  11012. function materialNeedsSmoothNormals ( material ) {
  11013. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  11014. };
  11015. function bufferGuessNormalType ( material ) {
  11016. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  11017. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  11018. return false;
  11019. }
  11020. if ( materialNeedsSmoothNormals( material ) ) {
  11021. return THREE.SmoothShading;
  11022. } else {
  11023. return THREE.FlatShading;
  11024. }
  11025. };
  11026. function bufferGuessVertexColorType ( material ) {
  11027. if ( material.vertexColors ) {
  11028. return material.vertexColors;
  11029. }
  11030. return false;
  11031. };
  11032. function bufferGuessUVType ( material ) {
  11033. // material must use some texture to require uvs
  11034. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  11035. return true;
  11036. }
  11037. return false;
  11038. };
  11039. //
  11040. function initDirectBuffers( geometry ) {
  11041. var a, attribute, type;
  11042. for ( a in geometry.attributes ) {
  11043. if ( a === "index" ) {
  11044. type = _gl.ELEMENT_ARRAY_BUFFER;
  11045. } else {
  11046. type = _gl.ARRAY_BUFFER;
  11047. }
  11048. attribute = geometry.attributes[ a ];
  11049. attribute.buffer = _gl.createBuffer();
  11050. _gl.bindBuffer( type, attribute.buffer );
  11051. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  11052. }
  11053. };
  11054. // Buffer setting
  11055. function setParticleBuffers ( geometry, hint, object ) {
  11056. var v, c, vertex, offset, index, color,
  11057. vertices = geometry.vertices,
  11058. vl = vertices.length,
  11059. colors = geometry.colors,
  11060. cl = colors.length,
  11061. vertexArray = geometry.__vertexArray,
  11062. colorArray = geometry.__colorArray,
  11063. sortArray = geometry.__sortArray,
  11064. dirtyVertices = geometry.verticesNeedUpdate,
  11065. dirtyElements = geometry.elementsNeedUpdate,
  11066. dirtyColors = geometry.colorsNeedUpdate,
  11067. customAttributes = geometry.__webglCustomAttributesList,
  11068. i, il,
  11069. a, ca, cal, value,
  11070. customAttribute;
  11071. if ( object.sortParticles ) {
  11072. _projScreenMatrixPS.copy( _projScreenMatrix );
  11073. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  11074. for ( v = 0; v < vl; v ++ ) {
  11075. vertex = vertices[ v ];
  11076. _vector3.copy( vertex );
  11077. _vector3.applyMatrix4( _projScreenMatrixPS );
  11078. sortArray[ v ] = [ _vector3.z, v ];
  11079. }
  11080. sortArray.sort( numericalSort );
  11081. for ( v = 0; v < vl; v ++ ) {
  11082. vertex = vertices[ sortArray[v][1] ];
  11083. offset = v * 3;
  11084. vertexArray[ offset ] = vertex.x;
  11085. vertexArray[ offset + 1 ] = vertex.y;
  11086. vertexArray[ offset + 2 ] = vertex.z;
  11087. }
  11088. for ( c = 0; c < cl; c ++ ) {
  11089. offset = c * 3;
  11090. color = colors[ sortArray[c][1] ];
  11091. colorArray[ offset ] = color.r;
  11092. colorArray[ offset + 1 ] = color.g;
  11093. colorArray[ offset + 2 ] = color.b;
  11094. }
  11095. if ( customAttributes ) {
  11096. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11097. customAttribute = customAttributes[ i ];
  11098. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  11099. offset = 0;
  11100. cal = customAttribute.value.length;
  11101. if ( customAttribute.size === 1 ) {
  11102. for ( ca = 0; ca < cal; ca ++ ) {
  11103. index = sortArray[ ca ][ 1 ];
  11104. customAttribute.array[ ca ] = customAttribute.value[ index ];
  11105. }
  11106. } else if ( customAttribute.size === 2 ) {
  11107. for ( ca = 0; ca < cal; ca ++ ) {
  11108. index = sortArray[ ca ][ 1 ];
  11109. value = customAttribute.value[ index ];
  11110. customAttribute.array[ offset ] = value.x;
  11111. customAttribute.array[ offset + 1 ] = value.y;
  11112. offset += 2;
  11113. }
  11114. } else if ( customAttribute.size === 3 ) {
  11115. if ( customAttribute.type === "c" ) {
  11116. for ( ca = 0; ca < cal; ca ++ ) {
  11117. index = sortArray[ ca ][ 1 ];
  11118. value = customAttribute.value[ index ];
  11119. customAttribute.array[ offset ] = value.r;
  11120. customAttribute.array[ offset + 1 ] = value.g;
  11121. customAttribute.array[ offset + 2 ] = value.b;
  11122. offset += 3;
  11123. }
  11124. } else {
  11125. for ( ca = 0; ca < cal; ca ++ ) {
  11126. index = sortArray[ ca ][ 1 ];
  11127. value = customAttribute.value[ index ];
  11128. customAttribute.array[ offset ] = value.x;
  11129. customAttribute.array[ offset + 1 ] = value.y;
  11130. customAttribute.array[ offset + 2 ] = value.z;
  11131. offset += 3;
  11132. }
  11133. }
  11134. } else if ( customAttribute.size === 4 ) {
  11135. for ( ca = 0; ca < cal; ca ++ ) {
  11136. index = sortArray[ ca ][ 1 ];
  11137. value = customAttribute.value[ index ];
  11138. customAttribute.array[ offset ] = value.x;
  11139. customAttribute.array[ offset + 1 ] = value.y;
  11140. customAttribute.array[ offset + 2 ] = value.z;
  11141. customAttribute.array[ offset + 3 ] = value.w;
  11142. offset += 4;
  11143. }
  11144. }
  11145. }
  11146. }
  11147. } else {
  11148. if ( dirtyVertices ) {
  11149. for ( v = 0; v < vl; v ++ ) {
  11150. vertex = vertices[ v ];
  11151. offset = v * 3;
  11152. vertexArray[ offset ] = vertex.x;
  11153. vertexArray[ offset + 1 ] = vertex.y;
  11154. vertexArray[ offset + 2 ] = vertex.z;
  11155. }
  11156. }
  11157. if ( dirtyColors ) {
  11158. for ( c = 0; c < cl; c ++ ) {
  11159. color = colors[ c ];
  11160. offset = c * 3;
  11161. colorArray[ offset ] = color.r;
  11162. colorArray[ offset + 1 ] = color.g;
  11163. colorArray[ offset + 2 ] = color.b;
  11164. }
  11165. }
  11166. if ( customAttributes ) {
  11167. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11168. customAttribute = customAttributes[ i ];
  11169. if ( customAttribute.needsUpdate &&
  11170. ( customAttribute.boundTo === undefined ||
  11171. customAttribute.boundTo === "vertices") ) {
  11172. cal = customAttribute.value.length;
  11173. offset = 0;
  11174. if ( customAttribute.size === 1 ) {
  11175. for ( ca = 0; ca < cal; ca ++ ) {
  11176. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11177. }
  11178. } else if ( customAttribute.size === 2 ) {
  11179. for ( ca = 0; ca < cal; ca ++ ) {
  11180. value = customAttribute.value[ ca ];
  11181. customAttribute.array[ offset ] = value.x;
  11182. customAttribute.array[ offset + 1 ] = value.y;
  11183. offset += 2;
  11184. }
  11185. } else if ( customAttribute.size === 3 ) {
  11186. if ( customAttribute.type === "c" ) {
  11187. for ( ca = 0; ca < cal; ca ++ ) {
  11188. value = customAttribute.value[ ca ];
  11189. customAttribute.array[ offset ] = value.r;
  11190. customAttribute.array[ offset + 1 ] = value.g;
  11191. customAttribute.array[ offset + 2 ] = value.b;
  11192. offset += 3;
  11193. }
  11194. } else {
  11195. for ( ca = 0; ca < cal; ca ++ ) {
  11196. value = customAttribute.value[ ca ];
  11197. customAttribute.array[ offset ] = value.x;
  11198. customAttribute.array[ offset + 1 ] = value.y;
  11199. customAttribute.array[ offset + 2 ] = value.z;
  11200. offset += 3;
  11201. }
  11202. }
  11203. } else if ( customAttribute.size === 4 ) {
  11204. for ( ca = 0; ca < cal; ca ++ ) {
  11205. value = customAttribute.value[ ca ];
  11206. customAttribute.array[ offset ] = value.x;
  11207. customAttribute.array[ offset + 1 ] = value.y;
  11208. customAttribute.array[ offset + 2 ] = value.z;
  11209. customAttribute.array[ offset + 3 ] = value.w;
  11210. offset += 4;
  11211. }
  11212. }
  11213. }
  11214. }
  11215. }
  11216. }
  11217. if ( dirtyVertices || object.sortParticles ) {
  11218. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11219. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11220. }
  11221. if ( dirtyColors || object.sortParticles ) {
  11222. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11223. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11224. }
  11225. if ( customAttributes ) {
  11226. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11227. customAttribute = customAttributes[ i ];
  11228. if ( customAttribute.needsUpdate || object.sortParticles ) {
  11229. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11230. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11231. }
  11232. }
  11233. }
  11234. };
  11235. function setLineBuffers ( geometry, hint ) {
  11236. var v, c, d, vertex, offset, color,
  11237. vertices = geometry.vertices,
  11238. colors = geometry.colors,
  11239. lineDistances = geometry.lineDistances,
  11240. vl = vertices.length,
  11241. cl = colors.length,
  11242. dl = lineDistances.length,
  11243. vertexArray = geometry.__vertexArray,
  11244. colorArray = geometry.__colorArray,
  11245. lineDistanceArray = geometry.__lineDistanceArray,
  11246. dirtyVertices = geometry.verticesNeedUpdate,
  11247. dirtyColors = geometry.colorsNeedUpdate,
  11248. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  11249. customAttributes = geometry.__webglCustomAttributesList,
  11250. i, il,
  11251. a, ca, cal, value,
  11252. customAttribute;
  11253. if ( dirtyVertices ) {
  11254. for ( v = 0; v < vl; v ++ ) {
  11255. vertex = vertices[ v ];
  11256. offset = v * 3;
  11257. vertexArray[ offset ] = vertex.x;
  11258. vertexArray[ offset + 1 ] = vertex.y;
  11259. vertexArray[ offset + 2 ] = vertex.z;
  11260. }
  11261. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11262. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11263. }
  11264. if ( dirtyColors ) {
  11265. for ( c = 0; c < cl; c ++ ) {
  11266. color = colors[ c ];
  11267. offset = c * 3;
  11268. colorArray[ offset ] = color.r;
  11269. colorArray[ offset + 1 ] = color.g;
  11270. colorArray[ offset + 2 ] = color.b;
  11271. }
  11272. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11273. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11274. }
  11275. if ( dirtyLineDistances ) {
  11276. for ( d = 0; d < dl; d ++ ) {
  11277. lineDistanceArray[ d ] = lineDistances[ d ];
  11278. }
  11279. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  11280. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  11281. }
  11282. if ( customAttributes ) {
  11283. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11284. customAttribute = customAttributes[ i ];
  11285. if ( customAttribute.needsUpdate &&
  11286. ( customAttribute.boundTo === undefined ||
  11287. customAttribute.boundTo === "vertices" ) ) {
  11288. offset = 0;
  11289. cal = customAttribute.value.length;
  11290. if ( customAttribute.size === 1 ) {
  11291. for ( ca = 0; ca < cal; ca ++ ) {
  11292. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11293. }
  11294. } else if ( customAttribute.size === 2 ) {
  11295. for ( ca = 0; ca < cal; ca ++ ) {
  11296. value = customAttribute.value[ ca ];
  11297. customAttribute.array[ offset ] = value.x;
  11298. customAttribute.array[ offset + 1 ] = value.y;
  11299. offset += 2;
  11300. }
  11301. } else if ( customAttribute.size === 3 ) {
  11302. if ( customAttribute.type === "c" ) {
  11303. for ( ca = 0; ca < cal; ca ++ ) {
  11304. value = customAttribute.value[ ca ];
  11305. customAttribute.array[ offset ] = value.r;
  11306. customAttribute.array[ offset + 1 ] = value.g;
  11307. customAttribute.array[ offset + 2 ] = value.b;
  11308. offset += 3;
  11309. }
  11310. } else {
  11311. for ( ca = 0; ca < cal; ca ++ ) {
  11312. value = customAttribute.value[ ca ];
  11313. customAttribute.array[ offset ] = value.x;
  11314. customAttribute.array[ offset + 1 ] = value.y;
  11315. customAttribute.array[ offset + 2 ] = value.z;
  11316. offset += 3;
  11317. }
  11318. }
  11319. } else if ( customAttribute.size === 4 ) {
  11320. for ( ca = 0; ca < cal; ca ++ ) {
  11321. value = customAttribute.value[ ca ];
  11322. customAttribute.array[ offset ] = value.x;
  11323. customAttribute.array[ offset + 1 ] = value.y;
  11324. customAttribute.array[ offset + 2 ] = value.z;
  11325. customAttribute.array[ offset + 3 ] = value.w;
  11326. offset += 4;
  11327. }
  11328. }
  11329. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11330. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11331. }
  11332. }
  11333. }
  11334. };
  11335. function setRibbonBuffers ( geometry, hint ) {
  11336. var v, c, n, vertex, offset, color, normal,
  11337. i, il, ca, cal, customAttribute, value,
  11338. vertices = geometry.vertices,
  11339. colors = geometry.colors,
  11340. normals = geometry.normals,
  11341. vl = vertices.length,
  11342. cl = colors.length,
  11343. nl = normals.length,
  11344. vertexArray = geometry.__vertexArray,
  11345. colorArray = geometry.__colorArray,
  11346. normalArray = geometry.__normalArray,
  11347. dirtyVertices = geometry.verticesNeedUpdate,
  11348. dirtyColors = geometry.colorsNeedUpdate,
  11349. dirtyNormals = geometry.normalsNeedUpdate,
  11350. customAttributes = geometry.__webglCustomAttributesList;
  11351. if ( dirtyVertices ) {
  11352. for ( v = 0; v < vl; v ++ ) {
  11353. vertex = vertices[ v ];
  11354. offset = v * 3;
  11355. vertexArray[ offset ] = vertex.x;
  11356. vertexArray[ offset + 1 ] = vertex.y;
  11357. vertexArray[ offset + 2 ] = vertex.z;
  11358. }
  11359. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11360. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11361. }
  11362. if ( dirtyColors ) {
  11363. for ( c = 0; c < cl; c ++ ) {
  11364. color = colors[ c ];
  11365. offset = c * 3;
  11366. colorArray[ offset ] = color.r;
  11367. colorArray[ offset + 1 ] = color.g;
  11368. colorArray[ offset + 2 ] = color.b;
  11369. }
  11370. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11371. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11372. }
  11373. if ( dirtyNormals ) {
  11374. for ( n = 0; n < nl; n ++ ) {
  11375. normal = normals[ n ];
  11376. offset = n * 3;
  11377. normalArray[ offset ] = normal.x;
  11378. normalArray[ offset + 1 ] = normal.y;
  11379. normalArray[ offset + 2 ] = normal.z;
  11380. }
  11381. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  11382. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11383. }
  11384. if ( customAttributes ) {
  11385. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11386. customAttribute = customAttributes[ i ];
  11387. if ( customAttribute.needsUpdate &&
  11388. ( customAttribute.boundTo === undefined ||
  11389. customAttribute.boundTo === "vertices" ) ) {
  11390. offset = 0;
  11391. cal = customAttribute.value.length;
  11392. if ( customAttribute.size === 1 ) {
  11393. for ( ca = 0; ca < cal; ca ++ ) {
  11394. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11395. }
  11396. } else if ( customAttribute.size === 2 ) {
  11397. for ( ca = 0; ca < cal; ca ++ ) {
  11398. value = customAttribute.value[ ca ];
  11399. customAttribute.array[ offset ] = value.x;
  11400. customAttribute.array[ offset + 1 ] = value.y;
  11401. offset += 2;
  11402. }
  11403. } else if ( customAttribute.size === 3 ) {
  11404. if ( customAttribute.type === "c" ) {
  11405. for ( ca = 0; ca < cal; ca ++ ) {
  11406. value = customAttribute.value[ ca ];
  11407. customAttribute.array[ offset ] = value.r;
  11408. customAttribute.array[ offset + 1 ] = value.g;
  11409. customAttribute.array[ offset + 2 ] = value.b;
  11410. offset += 3;
  11411. }
  11412. } else {
  11413. for ( ca = 0; ca < cal; ca ++ ) {
  11414. value = customAttribute.value[ ca ];
  11415. customAttribute.array[ offset ] = value.x;
  11416. customAttribute.array[ offset + 1 ] = value.y;
  11417. customAttribute.array[ offset + 2 ] = value.z;
  11418. offset += 3;
  11419. }
  11420. }
  11421. } else if ( customAttribute.size === 4 ) {
  11422. for ( ca = 0; ca < cal; ca ++ ) {
  11423. value = customAttribute.value[ ca ];
  11424. customAttribute.array[ offset ] = value.x;
  11425. customAttribute.array[ offset + 1 ] = value.y;
  11426. customAttribute.array[ offset + 2 ] = value.z;
  11427. customAttribute.array[ offset + 3 ] = value.w;
  11428. offset += 4;
  11429. }
  11430. }
  11431. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11432. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11433. }
  11434. }
  11435. }
  11436. };
  11437. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  11438. if ( ! geometryGroup.__inittedArrays ) {
  11439. return;
  11440. }
  11441. var normalType = bufferGuessNormalType( material ),
  11442. vertexColorType = bufferGuessVertexColorType( material ),
  11443. uvType = bufferGuessUVType( material ),
  11444. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  11445. var f, fl, fi, face,
  11446. vertexNormals, faceNormal, normal,
  11447. vertexColors, faceColor,
  11448. vertexTangents,
  11449. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  11450. c1, c2, c3, c4,
  11451. sw1, sw2, sw3, sw4,
  11452. si1, si2, si3, si4,
  11453. sa1, sa2, sa3, sa4,
  11454. sb1, sb2, sb3, sb4,
  11455. m, ml, i, il,
  11456. vn, uvi, uv2i,
  11457. vk, vkl, vka,
  11458. nka, chf, faceVertexNormals,
  11459. a,
  11460. vertexIndex = 0,
  11461. offset = 0,
  11462. offset_uv = 0,
  11463. offset_uv2 = 0,
  11464. offset_face = 0,
  11465. offset_normal = 0,
  11466. offset_tangent = 0,
  11467. offset_line = 0,
  11468. offset_color = 0,
  11469. offset_skin = 0,
  11470. offset_morphTarget = 0,
  11471. offset_custom = 0,
  11472. offset_customSrc = 0,
  11473. value,
  11474. vertexArray = geometryGroup.__vertexArray,
  11475. uvArray = geometryGroup.__uvArray,
  11476. uv2Array = geometryGroup.__uv2Array,
  11477. normalArray = geometryGroup.__normalArray,
  11478. tangentArray = geometryGroup.__tangentArray,
  11479. colorArray = geometryGroup.__colorArray,
  11480. skinIndexArray = geometryGroup.__skinIndexArray,
  11481. skinWeightArray = geometryGroup.__skinWeightArray,
  11482. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  11483. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  11484. customAttributes = geometryGroup.__webglCustomAttributesList,
  11485. customAttribute,
  11486. faceArray = geometryGroup.__faceArray,
  11487. lineArray = geometryGroup.__lineArray,
  11488. geometry = object.geometry, // this is shared for all chunks
  11489. dirtyVertices = geometry.verticesNeedUpdate,
  11490. dirtyElements = geometry.elementsNeedUpdate,
  11491. dirtyUvs = geometry.uvsNeedUpdate,
  11492. dirtyNormals = geometry.normalsNeedUpdate,
  11493. dirtyTangents = geometry.tangentsNeedUpdate,
  11494. dirtyColors = geometry.colorsNeedUpdate,
  11495. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  11496. vertices = geometry.vertices,
  11497. chunk_faces3 = geometryGroup.faces3,
  11498. chunk_faces4 = geometryGroup.faces4,
  11499. obj_faces = geometry.faces,
  11500. obj_uvs = geometry.faceVertexUvs[ 0 ],
  11501. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  11502. obj_colors = geometry.colors,
  11503. obj_skinIndices = geometry.skinIndices,
  11504. obj_skinWeights = geometry.skinWeights,
  11505. morphTargets = geometry.morphTargets,
  11506. morphNormals = geometry.morphNormals;
  11507. if ( dirtyVertices ) {
  11508. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11509. face = obj_faces[ chunk_faces3[ f ] ];
  11510. v1 = vertices[ face.a ];
  11511. v2 = vertices[ face.b ];
  11512. v3 = vertices[ face.c ];
  11513. vertexArray[ offset ] = v1.x;
  11514. vertexArray[ offset + 1 ] = v1.y;
  11515. vertexArray[ offset + 2 ] = v1.z;
  11516. vertexArray[ offset + 3 ] = v2.x;
  11517. vertexArray[ offset + 4 ] = v2.y;
  11518. vertexArray[ offset + 5 ] = v2.z;
  11519. vertexArray[ offset + 6 ] = v3.x;
  11520. vertexArray[ offset + 7 ] = v3.y;
  11521. vertexArray[ offset + 8 ] = v3.z;
  11522. offset += 9;
  11523. }
  11524. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11525. face = obj_faces[ chunk_faces4[ f ] ];
  11526. v1 = vertices[ face.a ];
  11527. v2 = vertices[ face.b ];
  11528. v3 = vertices[ face.c ];
  11529. v4 = vertices[ face.d ];
  11530. vertexArray[ offset ] = v1.x;
  11531. vertexArray[ offset + 1 ] = v1.y;
  11532. vertexArray[ offset + 2 ] = v1.z;
  11533. vertexArray[ offset + 3 ] = v2.x;
  11534. vertexArray[ offset + 4 ] = v2.y;
  11535. vertexArray[ offset + 5 ] = v2.z;
  11536. vertexArray[ offset + 6 ] = v3.x;
  11537. vertexArray[ offset + 7 ] = v3.y;
  11538. vertexArray[ offset + 8 ] = v3.z;
  11539. vertexArray[ offset + 9 ] = v4.x;
  11540. vertexArray[ offset + 10 ] = v4.y;
  11541. vertexArray[ offset + 11 ] = v4.z;
  11542. offset += 12;
  11543. }
  11544. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11545. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11546. }
  11547. if ( dirtyMorphTargets ) {
  11548. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  11549. offset_morphTarget = 0;
  11550. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11551. chf = chunk_faces3[ f ];
  11552. face = obj_faces[ chf ];
  11553. // morph positions
  11554. v1 = morphTargets[ vk ].vertices[ face.a ];
  11555. v2 = morphTargets[ vk ].vertices[ face.b ];
  11556. v3 = morphTargets[ vk ].vertices[ face.c ];
  11557. vka = morphTargetsArrays[ vk ];
  11558. vka[ offset_morphTarget ] = v1.x;
  11559. vka[ offset_morphTarget + 1 ] = v1.y;
  11560. vka[ offset_morphTarget + 2 ] = v1.z;
  11561. vka[ offset_morphTarget + 3 ] = v2.x;
  11562. vka[ offset_morphTarget + 4 ] = v2.y;
  11563. vka[ offset_morphTarget + 5 ] = v2.z;
  11564. vka[ offset_morphTarget + 6 ] = v3.x;
  11565. vka[ offset_morphTarget + 7 ] = v3.y;
  11566. vka[ offset_morphTarget + 8 ] = v3.z;
  11567. // morph normals
  11568. if ( material.morphNormals ) {
  11569. if ( needsSmoothNormals ) {
  11570. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11571. n1 = faceVertexNormals.a;
  11572. n2 = faceVertexNormals.b;
  11573. n3 = faceVertexNormals.c;
  11574. } else {
  11575. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11576. n2 = n1;
  11577. n3 = n1;
  11578. }
  11579. nka = morphNormalsArrays[ vk ];
  11580. nka[ offset_morphTarget ] = n1.x;
  11581. nka[ offset_morphTarget + 1 ] = n1.y;
  11582. nka[ offset_morphTarget + 2 ] = n1.z;
  11583. nka[ offset_morphTarget + 3 ] = n2.x;
  11584. nka[ offset_morphTarget + 4 ] = n2.y;
  11585. nka[ offset_morphTarget + 5 ] = n2.z;
  11586. nka[ offset_morphTarget + 6 ] = n3.x;
  11587. nka[ offset_morphTarget + 7 ] = n3.y;
  11588. nka[ offset_morphTarget + 8 ] = n3.z;
  11589. }
  11590. //
  11591. offset_morphTarget += 9;
  11592. }
  11593. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11594. chf = chunk_faces4[ f ];
  11595. face = obj_faces[ chf ];
  11596. // morph positions
  11597. v1 = morphTargets[ vk ].vertices[ face.a ];
  11598. v2 = morphTargets[ vk ].vertices[ face.b ];
  11599. v3 = morphTargets[ vk ].vertices[ face.c ];
  11600. v4 = morphTargets[ vk ].vertices[ face.d ];
  11601. vka = morphTargetsArrays[ vk ];
  11602. vka[ offset_morphTarget ] = v1.x;
  11603. vka[ offset_morphTarget + 1 ] = v1.y;
  11604. vka[ offset_morphTarget + 2 ] = v1.z;
  11605. vka[ offset_morphTarget + 3 ] = v2.x;
  11606. vka[ offset_morphTarget + 4 ] = v2.y;
  11607. vka[ offset_morphTarget + 5 ] = v2.z;
  11608. vka[ offset_morphTarget + 6 ] = v3.x;
  11609. vka[ offset_morphTarget + 7 ] = v3.y;
  11610. vka[ offset_morphTarget + 8 ] = v3.z;
  11611. vka[ offset_morphTarget + 9 ] = v4.x;
  11612. vka[ offset_morphTarget + 10 ] = v4.y;
  11613. vka[ offset_morphTarget + 11 ] = v4.z;
  11614. // morph normals
  11615. if ( material.morphNormals ) {
  11616. if ( needsSmoothNormals ) {
  11617. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11618. n1 = faceVertexNormals.a;
  11619. n2 = faceVertexNormals.b;
  11620. n3 = faceVertexNormals.c;
  11621. n4 = faceVertexNormals.d;
  11622. } else {
  11623. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11624. n2 = n1;
  11625. n3 = n1;
  11626. n4 = n1;
  11627. }
  11628. nka = morphNormalsArrays[ vk ];
  11629. nka[ offset_morphTarget ] = n1.x;
  11630. nka[ offset_morphTarget + 1 ] = n1.y;
  11631. nka[ offset_morphTarget + 2 ] = n1.z;
  11632. nka[ offset_morphTarget + 3 ] = n2.x;
  11633. nka[ offset_morphTarget + 4 ] = n2.y;
  11634. nka[ offset_morphTarget + 5 ] = n2.z;
  11635. nka[ offset_morphTarget + 6 ] = n3.x;
  11636. nka[ offset_morphTarget + 7 ] = n3.y;
  11637. nka[ offset_morphTarget + 8 ] = n3.z;
  11638. nka[ offset_morphTarget + 9 ] = n4.x;
  11639. nka[ offset_morphTarget + 10 ] = n4.y;
  11640. nka[ offset_morphTarget + 11 ] = n4.z;
  11641. }
  11642. //
  11643. offset_morphTarget += 12;
  11644. }
  11645. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  11646. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  11647. if ( material.morphNormals ) {
  11648. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  11649. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  11650. }
  11651. }
  11652. }
  11653. if ( obj_skinWeights.length ) {
  11654. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11655. face = obj_faces[ chunk_faces3[ f ] ];
  11656. // weights
  11657. sw1 = obj_skinWeights[ face.a ];
  11658. sw2 = obj_skinWeights[ face.b ];
  11659. sw3 = obj_skinWeights[ face.c ];
  11660. skinWeightArray[ offset_skin ] = sw1.x;
  11661. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11662. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11663. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11664. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11665. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11666. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11667. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11668. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11669. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11670. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11671. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11672. // indices
  11673. si1 = obj_skinIndices[ face.a ];
  11674. si2 = obj_skinIndices[ face.b ];
  11675. si3 = obj_skinIndices[ face.c ];
  11676. skinIndexArray[ offset_skin ] = si1.x;
  11677. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11678. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11679. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11680. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11681. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11682. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11683. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11684. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11685. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11686. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11687. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11688. offset_skin += 12;
  11689. }
  11690. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11691. face = obj_faces[ chunk_faces4[ f ] ];
  11692. // weights
  11693. sw1 = obj_skinWeights[ face.a ];
  11694. sw2 = obj_skinWeights[ face.b ];
  11695. sw3 = obj_skinWeights[ face.c ];
  11696. sw4 = obj_skinWeights[ face.d ];
  11697. skinWeightArray[ offset_skin ] = sw1.x;
  11698. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11699. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11700. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11701. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11702. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11703. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11704. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11705. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11706. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11707. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11708. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11709. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  11710. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  11711. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  11712. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  11713. // indices
  11714. si1 = obj_skinIndices[ face.a ];
  11715. si2 = obj_skinIndices[ face.b ];
  11716. si3 = obj_skinIndices[ face.c ];
  11717. si4 = obj_skinIndices[ face.d ];
  11718. skinIndexArray[ offset_skin ] = si1.x;
  11719. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11720. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11721. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11722. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11723. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11724. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11725. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11726. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11727. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11728. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11729. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11730. skinIndexArray[ offset_skin + 12 ] = si4.x;
  11731. skinIndexArray[ offset_skin + 13 ] = si4.y;
  11732. skinIndexArray[ offset_skin + 14 ] = si4.z;
  11733. skinIndexArray[ offset_skin + 15 ] = si4.w;
  11734. offset_skin += 16;
  11735. }
  11736. if ( offset_skin > 0 ) {
  11737. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11738. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  11739. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11740. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  11741. }
  11742. }
  11743. if ( dirtyColors && vertexColorType ) {
  11744. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11745. face = obj_faces[ chunk_faces3[ f ] ];
  11746. vertexColors = face.vertexColors;
  11747. faceColor = face.color;
  11748. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  11749. c1 = vertexColors[ 0 ];
  11750. c2 = vertexColors[ 1 ];
  11751. c3 = vertexColors[ 2 ];
  11752. } else {
  11753. c1 = faceColor;
  11754. c2 = faceColor;
  11755. c3 = faceColor;
  11756. }
  11757. colorArray[ offset_color ] = c1.r;
  11758. colorArray[ offset_color + 1 ] = c1.g;
  11759. colorArray[ offset_color + 2 ] = c1.b;
  11760. colorArray[ offset_color + 3 ] = c2.r;
  11761. colorArray[ offset_color + 4 ] = c2.g;
  11762. colorArray[ offset_color + 5 ] = c2.b;
  11763. colorArray[ offset_color + 6 ] = c3.r;
  11764. colorArray[ offset_color + 7 ] = c3.g;
  11765. colorArray[ offset_color + 8 ] = c3.b;
  11766. offset_color += 9;
  11767. }
  11768. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11769. face = obj_faces[ chunk_faces4[ f ] ];
  11770. vertexColors = face.vertexColors;
  11771. faceColor = face.color;
  11772. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  11773. c1 = vertexColors[ 0 ];
  11774. c2 = vertexColors[ 1 ];
  11775. c3 = vertexColors[ 2 ];
  11776. c4 = vertexColors[ 3 ];
  11777. } else {
  11778. c1 = faceColor;
  11779. c2 = faceColor;
  11780. c3 = faceColor;
  11781. c4 = faceColor;
  11782. }
  11783. colorArray[ offset_color ] = c1.r;
  11784. colorArray[ offset_color + 1 ] = c1.g;
  11785. colorArray[ offset_color + 2 ] = c1.b;
  11786. colorArray[ offset_color + 3 ] = c2.r;
  11787. colorArray[ offset_color + 4 ] = c2.g;
  11788. colorArray[ offset_color + 5 ] = c2.b;
  11789. colorArray[ offset_color + 6 ] = c3.r;
  11790. colorArray[ offset_color + 7 ] = c3.g;
  11791. colorArray[ offset_color + 8 ] = c3.b;
  11792. colorArray[ offset_color + 9 ] = c4.r;
  11793. colorArray[ offset_color + 10 ] = c4.g;
  11794. colorArray[ offset_color + 11 ] = c4.b;
  11795. offset_color += 12;
  11796. }
  11797. if ( offset_color > 0 ) {
  11798. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11799. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11800. }
  11801. }
  11802. if ( dirtyTangents && geometry.hasTangents ) {
  11803. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11804. face = obj_faces[ chunk_faces3[ f ] ];
  11805. vertexTangents = face.vertexTangents;
  11806. t1 = vertexTangents[ 0 ];
  11807. t2 = vertexTangents[ 1 ];
  11808. t3 = vertexTangents[ 2 ];
  11809. tangentArray[ offset_tangent ] = t1.x;
  11810. tangentArray[ offset_tangent + 1 ] = t1.y;
  11811. tangentArray[ offset_tangent + 2 ] = t1.z;
  11812. tangentArray[ offset_tangent + 3 ] = t1.w;
  11813. tangentArray[ offset_tangent + 4 ] = t2.x;
  11814. tangentArray[ offset_tangent + 5 ] = t2.y;
  11815. tangentArray[ offset_tangent + 6 ] = t2.z;
  11816. tangentArray[ offset_tangent + 7 ] = t2.w;
  11817. tangentArray[ offset_tangent + 8 ] = t3.x;
  11818. tangentArray[ offset_tangent + 9 ] = t3.y;
  11819. tangentArray[ offset_tangent + 10 ] = t3.z;
  11820. tangentArray[ offset_tangent + 11 ] = t3.w;
  11821. offset_tangent += 12;
  11822. }
  11823. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11824. face = obj_faces[ chunk_faces4[ f ] ];
  11825. vertexTangents = face.vertexTangents;
  11826. t1 = vertexTangents[ 0 ];
  11827. t2 = vertexTangents[ 1 ];
  11828. t3 = vertexTangents[ 2 ];
  11829. t4 = vertexTangents[ 3 ];
  11830. tangentArray[ offset_tangent ] = t1.x;
  11831. tangentArray[ offset_tangent + 1 ] = t1.y;
  11832. tangentArray[ offset_tangent + 2 ] = t1.z;
  11833. tangentArray[ offset_tangent + 3 ] = t1.w;
  11834. tangentArray[ offset_tangent + 4 ] = t2.x;
  11835. tangentArray[ offset_tangent + 5 ] = t2.y;
  11836. tangentArray[ offset_tangent + 6 ] = t2.z;
  11837. tangentArray[ offset_tangent + 7 ] = t2.w;
  11838. tangentArray[ offset_tangent + 8 ] = t3.x;
  11839. tangentArray[ offset_tangent + 9 ] = t3.y;
  11840. tangentArray[ offset_tangent + 10 ] = t3.z;
  11841. tangentArray[ offset_tangent + 11 ] = t3.w;
  11842. tangentArray[ offset_tangent + 12 ] = t4.x;
  11843. tangentArray[ offset_tangent + 13 ] = t4.y;
  11844. tangentArray[ offset_tangent + 14 ] = t4.z;
  11845. tangentArray[ offset_tangent + 15 ] = t4.w;
  11846. offset_tangent += 16;
  11847. }
  11848. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11849. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  11850. }
  11851. if ( dirtyNormals && normalType ) {
  11852. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11853. face = obj_faces[ chunk_faces3[ f ] ];
  11854. vertexNormals = face.vertexNormals;
  11855. faceNormal = face.normal;
  11856. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  11857. for ( i = 0; i < 3; i ++ ) {
  11858. vn = vertexNormals[ i ];
  11859. normalArray[ offset_normal ] = vn.x;
  11860. normalArray[ offset_normal + 1 ] = vn.y;
  11861. normalArray[ offset_normal + 2 ] = vn.z;
  11862. offset_normal += 3;
  11863. }
  11864. } else {
  11865. for ( i = 0; i < 3; i ++ ) {
  11866. normalArray[ offset_normal ] = faceNormal.x;
  11867. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11868. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11869. offset_normal += 3;
  11870. }
  11871. }
  11872. }
  11873. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11874. face = obj_faces[ chunk_faces4[ f ] ];
  11875. vertexNormals = face.vertexNormals;
  11876. faceNormal = face.normal;
  11877. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  11878. for ( i = 0; i < 4; i ++ ) {
  11879. vn = vertexNormals[ i ];
  11880. normalArray[ offset_normal ] = vn.x;
  11881. normalArray[ offset_normal + 1 ] = vn.y;
  11882. normalArray[ offset_normal + 2 ] = vn.z;
  11883. offset_normal += 3;
  11884. }
  11885. } else {
  11886. for ( i = 0; i < 4; i ++ ) {
  11887. normalArray[ offset_normal ] = faceNormal.x;
  11888. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11889. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11890. offset_normal += 3;
  11891. }
  11892. }
  11893. }
  11894. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11895. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11896. }
  11897. if ( dirtyUvs && obj_uvs && uvType ) {
  11898. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11899. fi = chunk_faces3[ f ];
  11900. uv = obj_uvs[ fi ];
  11901. if ( uv === undefined ) continue;
  11902. for ( i = 0; i < 3; i ++ ) {
  11903. uvi = uv[ i ];
  11904. uvArray[ offset_uv ] = uvi.x;
  11905. uvArray[ offset_uv + 1 ] = uvi.y;
  11906. offset_uv += 2;
  11907. }
  11908. }
  11909. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11910. fi = chunk_faces4[ f ];
  11911. uv = obj_uvs[ fi ];
  11912. if ( uv === undefined ) continue;
  11913. for ( i = 0; i < 4; i ++ ) {
  11914. uvi = uv[ i ];
  11915. uvArray[ offset_uv ] = uvi.x;
  11916. uvArray[ offset_uv + 1 ] = uvi.y;
  11917. offset_uv += 2;
  11918. }
  11919. }
  11920. if ( offset_uv > 0 ) {
  11921. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11922. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  11923. }
  11924. }
  11925. if ( dirtyUvs && obj_uvs2 && uvType ) {
  11926. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11927. fi = chunk_faces3[ f ];
  11928. uv2 = obj_uvs2[ fi ];
  11929. if ( uv2 === undefined ) continue;
  11930. for ( i = 0; i < 3; i ++ ) {
  11931. uv2i = uv2[ i ];
  11932. uv2Array[ offset_uv2 ] = uv2i.x;
  11933. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11934. offset_uv2 += 2;
  11935. }
  11936. }
  11937. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11938. fi = chunk_faces4[ f ];
  11939. uv2 = obj_uvs2[ fi ];
  11940. if ( uv2 === undefined ) continue;
  11941. for ( i = 0; i < 4; i ++ ) {
  11942. uv2i = uv2[ i ];
  11943. uv2Array[ offset_uv2 ] = uv2i.x;
  11944. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11945. offset_uv2 += 2;
  11946. }
  11947. }
  11948. if ( offset_uv2 > 0 ) {
  11949. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11950. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  11951. }
  11952. }
  11953. if ( dirtyElements ) {
  11954. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11955. faceArray[ offset_face ] = vertexIndex;
  11956. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11957. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  11958. offset_face += 3;
  11959. lineArray[ offset_line ] = vertexIndex;
  11960. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11961. lineArray[ offset_line + 2 ] = vertexIndex;
  11962. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  11963. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11964. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11965. offset_line += 6;
  11966. vertexIndex += 3;
  11967. }
  11968. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11969. faceArray[ offset_face ] = vertexIndex;
  11970. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11971. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  11972. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  11973. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  11974. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  11975. offset_face += 6;
  11976. lineArray[ offset_line ] = vertexIndex;
  11977. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11978. lineArray[ offset_line + 2 ] = vertexIndex;
  11979. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  11980. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11981. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11982. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  11983. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  11984. offset_line += 8;
  11985. vertexIndex += 4;
  11986. }
  11987. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11988. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  11989. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11990. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  11991. }
  11992. if ( customAttributes ) {
  11993. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11994. customAttribute = customAttributes[ i ];
  11995. if ( ! customAttribute.__original.needsUpdate ) continue;
  11996. offset_custom = 0;
  11997. offset_customSrc = 0;
  11998. if ( customAttribute.size === 1 ) {
  11999. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12000. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12001. face = obj_faces[ chunk_faces3[ f ] ];
  12002. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12003. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12004. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12005. offset_custom += 3;
  12006. }
  12007. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12008. face = obj_faces[ chunk_faces4[ f ] ];
  12009. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12010. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12011. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12012. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  12013. offset_custom += 4;
  12014. }
  12015. } else if ( customAttribute.boundTo === "faces" ) {
  12016. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12017. value = customAttribute.value[ chunk_faces3[ f ] ];
  12018. customAttribute.array[ offset_custom ] = value;
  12019. customAttribute.array[ offset_custom + 1 ] = value;
  12020. customAttribute.array[ offset_custom + 2 ] = value;
  12021. offset_custom += 3;
  12022. }
  12023. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12024. value = customAttribute.value[ chunk_faces4[ f ] ];
  12025. customAttribute.array[ offset_custom ] = value;
  12026. customAttribute.array[ offset_custom + 1 ] = value;
  12027. customAttribute.array[ offset_custom + 2 ] = value;
  12028. customAttribute.array[ offset_custom + 3 ] = value;
  12029. offset_custom += 4;
  12030. }
  12031. }
  12032. } else if ( customAttribute.size === 2 ) {
  12033. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12034. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12035. face = obj_faces[ chunk_faces3[ f ] ];
  12036. v1 = customAttribute.value[ face.a ];
  12037. v2 = customAttribute.value[ face.b ];
  12038. v3 = customAttribute.value[ face.c ];
  12039. customAttribute.array[ offset_custom ] = v1.x;
  12040. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12041. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12042. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12043. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12044. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12045. offset_custom += 6;
  12046. }
  12047. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12048. face = obj_faces[ chunk_faces4[ f ] ];
  12049. v1 = customAttribute.value[ face.a ];
  12050. v2 = customAttribute.value[ face.b ];
  12051. v3 = customAttribute.value[ face.c ];
  12052. v4 = customAttribute.value[ face.d ];
  12053. customAttribute.array[ offset_custom ] = v1.x;
  12054. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12055. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12056. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12057. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12058. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12059. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12060. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12061. offset_custom += 8;
  12062. }
  12063. } else if ( customAttribute.boundTo === "faces" ) {
  12064. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12065. value = customAttribute.value[ chunk_faces3[ f ] ];
  12066. v1 = value;
  12067. v2 = value;
  12068. v3 = value;
  12069. customAttribute.array[ offset_custom ] = v1.x;
  12070. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12071. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12072. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12073. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12074. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12075. offset_custom += 6;
  12076. }
  12077. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12078. value = customAttribute.value[ chunk_faces4[ f ] ];
  12079. v1 = value;
  12080. v2 = value;
  12081. v3 = value;
  12082. v4 = value;
  12083. customAttribute.array[ offset_custom ] = v1.x;
  12084. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12085. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12086. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12087. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12088. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12089. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12090. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12091. offset_custom += 8;
  12092. }
  12093. }
  12094. } else if ( customAttribute.size === 3 ) {
  12095. var pp;
  12096. if ( customAttribute.type === "c" ) {
  12097. pp = [ "r", "g", "b" ];
  12098. } else {
  12099. pp = [ "x", "y", "z" ];
  12100. }
  12101. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12102. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12103. face = obj_faces[ chunk_faces3[ f ] ];
  12104. v1 = customAttribute.value[ face.a ];
  12105. v2 = customAttribute.value[ face.b ];
  12106. v3 = customAttribute.value[ face.c ];
  12107. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12108. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12109. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12110. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12111. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12112. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12113. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12114. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12115. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12116. offset_custom += 9;
  12117. }
  12118. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12119. face = obj_faces[ chunk_faces4[ f ] ];
  12120. v1 = customAttribute.value[ face.a ];
  12121. v2 = customAttribute.value[ face.b ];
  12122. v3 = customAttribute.value[ face.c ];
  12123. v4 = customAttribute.value[ face.d ];
  12124. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12125. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12126. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12127. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12128. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12129. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12130. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12131. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12132. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12133. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12134. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12135. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12136. offset_custom += 12;
  12137. }
  12138. } else if ( customAttribute.boundTo === "faces" ) {
  12139. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12140. value = customAttribute.value[ chunk_faces3[ f ] ];
  12141. v1 = value;
  12142. v2 = value;
  12143. v3 = value;
  12144. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12145. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12146. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12147. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12148. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12149. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12150. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12151. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12152. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12153. offset_custom += 9;
  12154. }
  12155. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12156. value = customAttribute.value[ chunk_faces4[ f ] ];
  12157. v1 = value;
  12158. v2 = value;
  12159. v3 = value;
  12160. v4 = value;
  12161. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12162. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12163. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12164. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12165. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12166. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12167. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12168. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12169. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12170. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12171. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12172. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12173. offset_custom += 12;
  12174. }
  12175. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12176. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12177. value = customAttribute.value[ chunk_faces3[ f ] ];
  12178. v1 = value[ 0 ];
  12179. v2 = value[ 1 ];
  12180. v3 = value[ 2 ];
  12181. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12182. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12183. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12184. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12185. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12186. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12187. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12188. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12189. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12190. offset_custom += 9;
  12191. }
  12192. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12193. value = customAttribute.value[ chunk_faces4[ f ] ];
  12194. v1 = value[ 0 ];
  12195. v2 = value[ 1 ];
  12196. v3 = value[ 2 ];
  12197. v4 = value[ 3 ];
  12198. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12199. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12200. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12201. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12202. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12203. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12204. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12205. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12206. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12207. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12208. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12209. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12210. offset_custom += 12;
  12211. }
  12212. }
  12213. } else if ( customAttribute.size === 4 ) {
  12214. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12215. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12216. face = obj_faces[ chunk_faces3[ f ] ];
  12217. v1 = customAttribute.value[ face.a ];
  12218. v2 = customAttribute.value[ face.b ];
  12219. v3 = customAttribute.value[ face.c ];
  12220. customAttribute.array[ offset_custom ] = v1.x;
  12221. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12222. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12223. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12224. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12225. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12226. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12227. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12228. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12229. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12230. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12231. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12232. offset_custom += 12;
  12233. }
  12234. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12235. face = obj_faces[ chunk_faces4[ f ] ];
  12236. v1 = customAttribute.value[ face.a ];
  12237. v2 = customAttribute.value[ face.b ];
  12238. v3 = customAttribute.value[ face.c ];
  12239. v4 = customAttribute.value[ face.d ];
  12240. customAttribute.array[ offset_custom ] = v1.x;
  12241. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12242. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12243. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12244. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12245. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12246. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12247. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12248. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12249. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12250. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12251. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12252. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12253. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12254. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12255. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12256. offset_custom += 16;
  12257. }
  12258. } else if ( customAttribute.boundTo === "faces" ) {
  12259. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12260. value = customAttribute.value[ chunk_faces3[ f ] ];
  12261. v1 = value;
  12262. v2 = value;
  12263. v3 = value;
  12264. customAttribute.array[ offset_custom ] = v1.x;
  12265. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12266. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12267. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12268. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12269. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12270. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12271. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12272. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12273. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12274. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12275. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12276. offset_custom += 12;
  12277. }
  12278. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12279. value = customAttribute.value[ chunk_faces4[ f ] ];
  12280. v1 = value;
  12281. v2 = value;
  12282. v3 = value;
  12283. v4 = value;
  12284. customAttribute.array[ offset_custom ] = v1.x;
  12285. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12286. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12287. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12288. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12289. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12290. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12291. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12292. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12293. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12294. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12295. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12296. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12297. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12298. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12299. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12300. offset_custom += 16;
  12301. }
  12302. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12303. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12304. value = customAttribute.value[ chunk_faces3[ f ] ];
  12305. v1 = value[ 0 ];
  12306. v2 = value[ 1 ];
  12307. v3 = value[ 2 ];
  12308. customAttribute.array[ offset_custom ] = v1.x;
  12309. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12310. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12311. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12312. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12313. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12314. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12315. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12316. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12317. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12318. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12319. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12320. offset_custom += 12;
  12321. }
  12322. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12323. value = customAttribute.value[ chunk_faces4[ f ] ];
  12324. v1 = value[ 0 ];
  12325. v2 = value[ 1 ];
  12326. v3 = value[ 2 ];
  12327. v4 = value[ 3 ];
  12328. customAttribute.array[ offset_custom ] = v1.x;
  12329. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12330. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12331. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12332. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12333. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12334. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12335. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12336. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12337. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12338. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12339. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12340. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12341. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12342. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12343. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12344. offset_custom += 16;
  12345. }
  12346. }
  12347. }
  12348. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12349. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12350. }
  12351. }
  12352. if ( dispose ) {
  12353. delete geometryGroup.__inittedArrays;
  12354. delete geometryGroup.__colorArray;
  12355. delete geometryGroup.__normalArray;
  12356. delete geometryGroup.__tangentArray;
  12357. delete geometryGroup.__uvArray;
  12358. delete geometryGroup.__uv2Array;
  12359. delete geometryGroup.__faceArray;
  12360. delete geometryGroup.__vertexArray;
  12361. delete geometryGroup.__lineArray;
  12362. delete geometryGroup.__skinIndexArray;
  12363. delete geometryGroup.__skinWeightArray;
  12364. }
  12365. };
  12366. function setDirectBuffers ( geometry, hint, dispose ) {
  12367. var attributes = geometry.attributes;
  12368. var index = attributes[ "index" ];
  12369. var position = attributes[ "position" ];
  12370. var normal = attributes[ "normal" ];
  12371. var uv = attributes[ "uv" ];
  12372. var color = attributes[ "color" ];
  12373. var tangent = attributes[ "tangent" ];
  12374. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  12375. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12376. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  12377. }
  12378. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  12379. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12380. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  12381. }
  12382. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  12383. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12384. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  12385. }
  12386. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  12387. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12388. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  12389. }
  12390. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  12391. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12392. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  12393. }
  12394. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  12395. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12396. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  12397. }
  12398. if ( dispose ) {
  12399. for ( var i in geometry.attributes ) {
  12400. delete geometry.attributes[ i ].array;
  12401. }
  12402. }
  12403. };
  12404. // Buffer rendering
  12405. this.renderBufferImmediate = function ( object, program, material ) {
  12406. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12407. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12408. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12409. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12410. if ( object.hasPositions ) {
  12411. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12412. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12413. _gl.enableVertexAttribArray( program.attributes.position );
  12414. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12415. }
  12416. if ( object.hasNormals ) {
  12417. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12418. if ( material.shading === THREE.FlatShading ) {
  12419. var nx, ny, nz,
  12420. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12421. normalArray,
  12422. i, il = object.count * 3;
  12423. for( i = 0; i < il; i += 9 ) {
  12424. normalArray = object.normalArray;
  12425. nax = normalArray[ i ];
  12426. nay = normalArray[ i + 1 ];
  12427. naz = normalArray[ i + 2 ];
  12428. nbx = normalArray[ i + 3 ];
  12429. nby = normalArray[ i + 4 ];
  12430. nbz = normalArray[ i + 5 ];
  12431. ncx = normalArray[ i + 6 ];
  12432. ncy = normalArray[ i + 7 ];
  12433. ncz = normalArray[ i + 8 ];
  12434. nx = ( nax + nbx + ncx ) / 3;
  12435. ny = ( nay + nby + ncy ) / 3;
  12436. nz = ( naz + nbz + ncz ) / 3;
  12437. normalArray[ i ] = nx;
  12438. normalArray[ i + 1 ] = ny;
  12439. normalArray[ i + 2 ] = nz;
  12440. normalArray[ i + 3 ] = nx;
  12441. normalArray[ i + 4 ] = ny;
  12442. normalArray[ i + 5 ] = nz;
  12443. normalArray[ i + 6 ] = nx;
  12444. normalArray[ i + 7 ] = ny;
  12445. normalArray[ i + 8 ] = nz;
  12446. }
  12447. }
  12448. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12449. _gl.enableVertexAttribArray( program.attributes.normal );
  12450. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12451. }
  12452. if ( object.hasUvs && material.map ) {
  12453. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  12454. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12455. _gl.enableVertexAttribArray( program.attributes.uv );
  12456. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12457. }
  12458. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  12459. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  12460. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12461. _gl.enableVertexAttribArray( program.attributes.color );
  12462. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12463. }
  12464. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12465. object.count = 0;
  12466. };
  12467. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  12468. if ( material.visible === false ) return;
  12469. var program, attributes, linewidth, primitives, a, attribute;
  12470. program = setProgram( camera, lights, fog, material, object );
  12471. attributes = program.attributes;
  12472. var updateBuffers = false,
  12473. wireframeBit = material.wireframe ? 1 : 0,
  12474. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12475. if ( geometryHash !== _currentGeometryGroupHash ) {
  12476. _currentGeometryGroupHash = geometryHash;
  12477. updateBuffers = true;
  12478. }
  12479. if ( updateBuffers ) {
  12480. disableAttributes();
  12481. }
  12482. // render mesh
  12483. if ( object instanceof THREE.Mesh ) {
  12484. var index = geometry.attributes[ "index" ];
  12485. // indexed triangles
  12486. if ( index ) {
  12487. var offsets = geometry.offsets;
  12488. // if there is more than 1 chunk
  12489. // must set attribute pointers to use new offsets for each chunk
  12490. // even if geometry and materials didn't change
  12491. if ( offsets.length > 1 ) updateBuffers = true;
  12492. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12493. var startIndex = offsets[ i ].index;
  12494. if ( updateBuffers ) {
  12495. // vertices
  12496. var position = geometry.attributes[ "position" ];
  12497. var positionSize = position.itemSize;
  12498. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12499. enableAttribute( attributes.position );
  12500. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  12501. // normals
  12502. var normal = geometry.attributes[ "normal" ];
  12503. if ( attributes.normal >= 0 && normal ) {
  12504. var normalSize = normal.itemSize;
  12505. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12506. enableAttribute( attributes.normal );
  12507. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  12508. }
  12509. // uvs
  12510. var uv = geometry.attributes[ "uv" ];
  12511. if ( attributes.uv >= 0 && uv ) {
  12512. var uvSize = uv.itemSize;
  12513. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12514. enableAttribute( attributes.uv );
  12515. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  12516. }
  12517. // colors
  12518. var color = geometry.attributes[ "color" ];
  12519. if ( attributes.color >= 0 && color ) {
  12520. var colorSize = color.itemSize;
  12521. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12522. enableAttribute( attributes.color );
  12523. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  12524. }
  12525. // tangents
  12526. var tangent = geometry.attributes[ "tangent" ];
  12527. if ( attributes.tangent >= 0 && tangent ) {
  12528. var tangentSize = tangent.itemSize;
  12529. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12530. enableAttribute( attributes.tangent );
  12531. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  12532. }
  12533. // indices
  12534. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12535. }
  12536. // render indexed triangles
  12537. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  12538. _this.info.render.calls ++;
  12539. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12540. _this.info.render.faces += offsets[ i ].count / 3;
  12541. }
  12542. // non-indexed triangles
  12543. } else {
  12544. if ( updateBuffers ) {
  12545. // vertices
  12546. var position = geometry.attributes[ "position" ];
  12547. var positionSize = position.itemSize;
  12548. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12549. enableAttribute( attributes.position );
  12550. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12551. // normals
  12552. var normal = geometry.attributes[ "normal" ];
  12553. if ( attributes.normal >= 0 && normal ) {
  12554. var normalSize = normal.itemSize;
  12555. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12556. enableAttribute( attributes.normal );
  12557. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, 0 );
  12558. }
  12559. // uvs
  12560. var uv = geometry.attributes[ "uv" ];
  12561. if ( attributes.uv >= 0 && uv ) {
  12562. var uvSize = uv.itemSize;
  12563. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12564. enableAttribute( attributes.uv );
  12565. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, 0 );
  12566. }
  12567. // colors
  12568. var color = geometry.attributes[ "color" ];
  12569. if ( attributes.color >= 0 && color ) {
  12570. var colorSize = color.itemSize;
  12571. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12572. enableAttribute( attributes.color );
  12573. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12574. }
  12575. // tangents
  12576. var tangent = geometry.attributes[ "tangent" ];
  12577. if ( attributes.tangent >= 0 && tangent ) {
  12578. var tangentSize = tangent.itemSize;
  12579. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12580. enableAttribute( attributes.tangent );
  12581. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0 );
  12582. }
  12583. }
  12584. // render non-indexed triangles
  12585. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  12586. _this.info.render.calls ++;
  12587. _this.info.render.vertices += position.numItems / 3;
  12588. _this.info.render.faces += position.numItems / 3 / 3;
  12589. }
  12590. // render particles
  12591. } else if ( object instanceof THREE.ParticleSystem ) {
  12592. if ( updateBuffers ) {
  12593. // vertices
  12594. var position = geometry.attributes[ "position" ];
  12595. var positionSize = position.itemSize;
  12596. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12597. enableAttribute( attributes.position );
  12598. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12599. // colors
  12600. var color = geometry.attributes[ "color" ];
  12601. if ( attributes.color >= 0 && color ) {
  12602. var colorSize = color.itemSize;
  12603. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12604. enableAttribute( attributes.color );
  12605. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12606. }
  12607. // render particles
  12608. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  12609. _this.info.render.calls ++;
  12610. _this.info.render.points += position.numItems / 3;
  12611. }
  12612. }
  12613. };
  12614. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  12615. if ( material.visible === false ) return;
  12616. var program, attributes, linewidth, primitives, a, attribute, i, il;
  12617. program = setProgram( camera, lights, fog, material, object );
  12618. attributes = program.attributes;
  12619. var updateBuffers = false,
  12620. wireframeBit = material.wireframe ? 1 : 0,
  12621. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12622. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  12623. _currentGeometryGroupHash = geometryGroupHash;
  12624. updateBuffers = true;
  12625. }
  12626. if ( updateBuffers ) {
  12627. disableAttributes();
  12628. }
  12629. // vertices
  12630. if ( !material.morphTargets && attributes.position >= 0 ) {
  12631. if ( updateBuffers ) {
  12632. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12633. enableAttribute( attributes.position );
  12634. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12635. }
  12636. } else {
  12637. if ( object.morphTargetBase ) {
  12638. setupMorphTargets( material, geometryGroup, object );
  12639. }
  12640. }
  12641. if ( updateBuffers ) {
  12642. // custom attributes
  12643. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  12644. if ( geometryGroup.__webglCustomAttributesList ) {
  12645. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  12646. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  12647. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  12648. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  12649. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  12650. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  12651. }
  12652. }
  12653. }
  12654. // colors
  12655. if ( attributes.color >= 0 ) {
  12656. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12657. enableAttribute( attributes.color );
  12658. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12659. }
  12660. // normals
  12661. if ( attributes.normal >= 0 ) {
  12662. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12663. enableAttribute( attributes.normal );
  12664. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12665. }
  12666. // tangents
  12667. if ( attributes.tangent >= 0 ) {
  12668. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12669. enableAttribute( attributes.tangent );
  12670. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  12671. }
  12672. // uvs
  12673. if ( attributes.uv >= 0 ) {
  12674. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12675. enableAttribute( attributes.uv );
  12676. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12677. }
  12678. if ( attributes.uv2 >= 0 ) {
  12679. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12680. enableAttribute( attributes.uv2 );
  12681. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  12682. }
  12683. if ( material.skinning &&
  12684. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12685. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12686. enableAttribute( attributes.skinIndex );
  12687. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  12688. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12689. enableAttribute( attributes.skinWeight );
  12690. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  12691. }
  12692. // line distances
  12693. if ( attributes.lineDistance >= 0 ) {
  12694. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  12695. enableAttribute( attributes.lineDistance );
  12696. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  12697. }
  12698. }
  12699. // render mesh
  12700. if ( object instanceof THREE.Mesh ) {
  12701. // wireframe
  12702. if ( material.wireframe ) {
  12703. setLineWidth( material.wireframeLinewidth );
  12704. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12705. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  12706. // triangles
  12707. } else {
  12708. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12709. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  12710. }
  12711. _this.info.render.calls ++;
  12712. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  12713. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  12714. // render lines
  12715. } else if ( object instanceof THREE.Line ) {
  12716. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12717. setLineWidth( material.linewidth );
  12718. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  12719. _this.info.render.calls ++;
  12720. // render particles
  12721. } else if ( object instanceof THREE.ParticleSystem ) {
  12722. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  12723. _this.info.render.calls ++;
  12724. _this.info.render.points += geometryGroup.__webglParticleCount;
  12725. // render ribbon
  12726. } else if ( object instanceof THREE.Ribbon ) {
  12727. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  12728. _this.info.render.calls ++;
  12729. }
  12730. };
  12731. function enableAttribute( attribute ) {
  12732. if ( ! _enabledAttributes[ attribute ] ) {
  12733. _gl.enableVertexAttribArray( attribute );
  12734. _enabledAttributes[ attribute ] = true;
  12735. }
  12736. };
  12737. function disableAttributes() {
  12738. for ( var attribute in _enabledAttributes ) {
  12739. if ( _enabledAttributes[ attribute ] ) {
  12740. _gl.disableVertexAttribArray( attribute );
  12741. _enabledAttributes[ attribute ] = false;
  12742. }
  12743. }
  12744. };
  12745. function setupMorphTargets ( material, geometryGroup, object ) {
  12746. // set base
  12747. var attributes = material.program.attributes;
  12748. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  12749. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  12750. enableAttribute( attributes.position );
  12751. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12752. } else if ( attributes.position >= 0 ) {
  12753. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12754. enableAttribute( attributes.position );
  12755. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12756. }
  12757. if ( object.morphTargetForcedOrder.length ) {
  12758. // set forced order
  12759. var m = 0;
  12760. var order = object.morphTargetForcedOrder;
  12761. var influences = object.morphTargetInfluences;
  12762. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  12763. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12764. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  12765. enableAttribute( attributes[ "morphTarget" + m ] );
  12766. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12767. }
  12768. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12769. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  12770. enableAttribute( attributes[ "morphNormal" + m ] );
  12771. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12772. }
  12773. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  12774. m ++;
  12775. }
  12776. } else {
  12777. // find the most influencing
  12778. var influence, activeInfluenceIndices = [];
  12779. var influences = object.morphTargetInfluences;
  12780. var i, il = influences.length;
  12781. for ( i = 0; i < il; i ++ ) {
  12782. influence = influences[ i ];
  12783. if ( influence > 0 ) {
  12784. activeInfluenceIndices.push( [ influence, i ] );
  12785. }
  12786. }
  12787. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  12788. activeInfluenceIndices.sort( numericalSort );
  12789. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  12790. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  12791. activeInfluenceIndices.sort( numericalSort );
  12792. } else if ( activeInfluenceIndices.length === 0 ) {
  12793. activeInfluenceIndices.push( [ 0, 0 ] );
  12794. };
  12795. var influenceIndex, m = 0;
  12796. while ( m < material.numSupportedMorphTargets ) {
  12797. if ( activeInfluenceIndices[ m ] ) {
  12798. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  12799. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12800. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  12801. enableAttribute( attributes[ "morphTarget" + m ] );
  12802. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12803. }
  12804. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12805. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  12806. enableAttribute( attributes[ "morphNormal" + m ] );
  12807. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12808. }
  12809. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  12810. } else {
  12811. /*
  12812. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12813. if ( material.morphNormals ) {
  12814. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12815. }
  12816. */
  12817. object.__webglMorphTargetInfluences[ m ] = 0;
  12818. }
  12819. m ++;
  12820. }
  12821. }
  12822. // load updated influences uniform
  12823. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  12824. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  12825. }
  12826. };
  12827. // Sorting
  12828. function painterSortStable ( a, b ) {
  12829. if ( a.z !== b.z ) {
  12830. return b.z - a.z;
  12831. } else {
  12832. return b.id - a.id;
  12833. }
  12834. };
  12835. function numericalSort ( a, b ) {
  12836. return b[ 0 ] - a[ 0 ];
  12837. };
  12838. // Rendering
  12839. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12840. if ( camera instanceof THREE.Camera === false ) {
  12841. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12842. return;
  12843. }
  12844. var i, il,
  12845. webglObject, object,
  12846. renderList,
  12847. lights = scene.__lights,
  12848. fog = scene.fog;
  12849. // reset caching for this frame
  12850. _currentMaterialId = -1;
  12851. _lightsNeedUpdate = true;
  12852. // update scene graph
  12853. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  12854. // update camera matrices and frustum
  12855. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  12856. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12857. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  12858. _frustum.setFromMatrix( _projScreenMatrix );
  12859. // update WebGL objects
  12860. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  12861. // custom render plugins (pre pass)
  12862. renderPlugins( this.renderPluginsPre, scene, camera );
  12863. //
  12864. _this.info.render.calls = 0;
  12865. _this.info.render.vertices = 0;
  12866. _this.info.render.faces = 0;
  12867. _this.info.render.points = 0;
  12868. this.setRenderTarget( renderTarget );
  12869. if ( this.autoClear || forceClear ) {
  12870. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12871. }
  12872. // set matrices for regular objects (frustum culled)
  12873. renderList = scene.__webglObjects;
  12874. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12875. webglObject = renderList[ i ];
  12876. object = webglObject.object;
  12877. webglObject.render = false;
  12878. if ( object.visible ) {
  12879. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  12880. setupMatrices( object, camera );
  12881. unrollBufferMaterial( webglObject );
  12882. webglObject.render = true;
  12883. if ( this.sortObjects === true ) {
  12884. if ( object.renderDepth !== null ) {
  12885. webglObject.z = object.renderDepth;
  12886. } else {
  12887. _vector3.copy( object.matrixWorld.getPosition() );
  12888. _vector3.applyMatrix4( _projScreenMatrix );
  12889. webglObject.z = _vector3.z;
  12890. }
  12891. webglObject.id = object.id;
  12892. }
  12893. }
  12894. }
  12895. }
  12896. if ( this.sortObjects ) {
  12897. renderList.sort( painterSortStable );
  12898. }
  12899. // set matrices for immediate objects
  12900. renderList = scene.__webglObjectsImmediate;
  12901. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12902. webglObject = renderList[ i ];
  12903. object = webglObject.object;
  12904. if ( object.visible ) {
  12905. setupMatrices( object, camera );
  12906. unrollImmediateBufferMaterial( webglObject );
  12907. }
  12908. }
  12909. if ( scene.overrideMaterial ) {
  12910. var material = scene.overrideMaterial;
  12911. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12912. this.setDepthTest( material.depthTest );
  12913. this.setDepthWrite( material.depthWrite );
  12914. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12915. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  12916. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  12917. } else {
  12918. var material = null;
  12919. // opaque pass (front-to-back order)
  12920. this.setBlending( THREE.NoBlending );
  12921. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  12922. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  12923. // transparent pass (back-to-front order)
  12924. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  12925. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  12926. }
  12927. // custom render plugins (post pass)
  12928. renderPlugins( this.renderPluginsPost, scene, camera );
  12929. // Generate mipmap if we're using any kind of mipmap filtering
  12930. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  12931. updateRenderTargetMipmap( renderTarget );
  12932. }
  12933. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12934. this.setDepthTest( true );
  12935. this.setDepthWrite( true );
  12936. // _gl.finish();
  12937. };
  12938. function renderPlugins( plugins, scene, camera ) {
  12939. if ( ! plugins.length ) return;
  12940. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  12941. // reset state for plugin (to start from clean slate)
  12942. _currentProgram = null;
  12943. _currentCamera = null;
  12944. _oldBlending = -1;
  12945. _oldDepthTest = -1;
  12946. _oldDepthWrite = -1;
  12947. _oldDoubleSided = -1;
  12948. _oldFlipSided = -1;
  12949. _currentGeometryGroupHash = -1;
  12950. _currentMaterialId = -1;
  12951. _lightsNeedUpdate = true;
  12952. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  12953. // reset state after plugin (anything could have changed)
  12954. _currentProgram = null;
  12955. _currentCamera = null;
  12956. _oldBlending = -1;
  12957. _oldDepthTest = -1;
  12958. _oldDepthWrite = -1;
  12959. _oldDoubleSided = -1;
  12960. _oldFlipSided = -1;
  12961. _currentGeometryGroupHash = -1;
  12962. _currentMaterialId = -1;
  12963. _lightsNeedUpdate = true;
  12964. }
  12965. };
  12966. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12967. var webglObject, object, buffer, material, start, end, delta;
  12968. if ( reverse ) {
  12969. start = renderList.length - 1;
  12970. end = -1;
  12971. delta = -1;
  12972. } else {
  12973. start = 0;
  12974. end = renderList.length;
  12975. delta = 1;
  12976. }
  12977. for ( var i = start; i !== end; i += delta ) {
  12978. webglObject = renderList[ i ];
  12979. if ( webglObject.render ) {
  12980. object = webglObject.object;
  12981. buffer = webglObject.buffer;
  12982. if ( overrideMaterial ) {
  12983. material = overrideMaterial;
  12984. } else {
  12985. material = webglObject[ materialType ];
  12986. if ( ! material ) continue;
  12987. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12988. _this.setDepthTest( material.depthTest );
  12989. _this.setDepthWrite( material.depthWrite );
  12990. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12991. }
  12992. _this.setMaterialFaces( material );
  12993. if ( buffer instanceof THREE.BufferGeometry ) {
  12994. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  12995. } else {
  12996. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  12997. }
  12998. }
  12999. }
  13000. };
  13001. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13002. var webglObject, object, material, program;
  13003. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13004. webglObject = renderList[ i ];
  13005. object = webglObject.object;
  13006. if ( object.visible ) {
  13007. if ( overrideMaterial ) {
  13008. material = overrideMaterial;
  13009. } else {
  13010. material = webglObject[ materialType ];
  13011. if ( ! material ) continue;
  13012. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13013. _this.setDepthTest( material.depthTest );
  13014. _this.setDepthWrite( material.depthWrite );
  13015. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13016. }
  13017. _this.renderImmediateObject( camera, lights, fog, material, object );
  13018. }
  13019. }
  13020. };
  13021. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13022. var program = setProgram( camera, lights, fog, material, object );
  13023. _currentGeometryGroupHash = -1;
  13024. _this.setMaterialFaces( material );
  13025. if ( object.immediateRenderCallback ) {
  13026. object.immediateRenderCallback( program, _gl, _frustum );
  13027. } else {
  13028. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13029. }
  13030. };
  13031. function unrollImmediateBufferMaterial ( globject ) {
  13032. var object = globject.object,
  13033. material = object.material;
  13034. if ( material.transparent ) {
  13035. globject.transparent = material;
  13036. globject.opaque = null;
  13037. } else {
  13038. globject.opaque = material;
  13039. globject.transparent = null;
  13040. }
  13041. };
  13042. function unrollBufferMaterial ( globject ) {
  13043. var object = globject.object,
  13044. buffer = globject.buffer,
  13045. material, materialIndex, meshMaterial;
  13046. meshMaterial = object.material;
  13047. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13048. materialIndex = buffer.materialIndex;
  13049. material = meshMaterial.materials[ materialIndex ];
  13050. if ( material.transparent ) {
  13051. globject.transparent = material;
  13052. globject.opaque = null;
  13053. } else {
  13054. globject.opaque = material;
  13055. globject.transparent = null;
  13056. }
  13057. } else {
  13058. material = meshMaterial;
  13059. if ( material ) {
  13060. if ( material.transparent ) {
  13061. globject.transparent = material;
  13062. globject.opaque = null;
  13063. } else {
  13064. globject.opaque = material;
  13065. globject.transparent = null;
  13066. }
  13067. }
  13068. }
  13069. };
  13070. // Geometry splitting
  13071. function sortFacesByMaterial ( geometry, material ) {
  13072. var f, fl, face, materialIndex, vertices,
  13073. groupHash, hash_map = {};
  13074. var numMorphTargets = geometry.morphTargets.length;
  13075. var numMorphNormals = geometry.morphNormals.length;
  13076. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13077. geometry.geometryGroups = {};
  13078. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13079. face = geometry.faces[ f ];
  13080. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13081. if ( hash_map[ materialIndex ] === undefined ) {
  13082. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13083. }
  13084. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13085. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13086. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13087. }
  13088. vertices = face instanceof THREE.Face3 ? 3 : 4;
  13089. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13090. hash_map[ materialIndex ].counter += 1;
  13091. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13092. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13093. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13094. }
  13095. }
  13096. if ( face instanceof THREE.Face3 ) {
  13097. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13098. } else {
  13099. geometry.geometryGroups[ groupHash ].faces4.push( f );
  13100. }
  13101. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13102. }
  13103. geometry.geometryGroupsList = [];
  13104. for ( var g in geometry.geometryGroups ) {
  13105. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13106. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13107. }
  13108. };
  13109. // Objects refresh
  13110. this.initWebGLObjects = function ( scene ) {
  13111. if ( !scene.__webglObjects ) {
  13112. scene.__webglObjects = [];
  13113. scene.__webglObjectsImmediate = [];
  13114. scene.__webglSprites = [];
  13115. scene.__webglFlares = [];
  13116. }
  13117. while ( scene.__objectsAdded.length ) {
  13118. addObject( scene.__objectsAdded[ 0 ], scene );
  13119. scene.__objectsAdded.splice( 0, 1 );
  13120. }
  13121. while ( scene.__objectsRemoved.length ) {
  13122. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13123. scene.__objectsRemoved.splice( 0, 1 );
  13124. }
  13125. // update must be called after objects adding / removal
  13126. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13127. updateObject( scene.__webglObjects[ o ].object );
  13128. }
  13129. };
  13130. // Objects adding
  13131. function addObject ( object, scene ) {
  13132. var g, geometry, material, geometryGroup;
  13133. if ( ! object.__webglInit ) {
  13134. object.__webglInit = true;
  13135. object._modelViewMatrix = new THREE.Matrix4();
  13136. object._normalMatrix = new THREE.Matrix3();
  13137. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13138. object.geometry.__webglInit = true;
  13139. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13140. }
  13141. if ( object instanceof THREE.Mesh ) {
  13142. geometry = object.geometry;
  13143. material = object.material;
  13144. if ( geometry instanceof THREE.Geometry ) {
  13145. if ( geometry.geometryGroups === undefined ) {
  13146. sortFacesByMaterial( geometry, material );
  13147. }
  13148. // create separate VBOs per geometry chunk
  13149. for ( g in geometry.geometryGroups ) {
  13150. geometryGroup = geometry.geometryGroups[ g ];
  13151. // initialise VBO on the first access
  13152. if ( ! geometryGroup.__webglVertexBuffer ) {
  13153. createMeshBuffers( geometryGroup );
  13154. initMeshBuffers( geometryGroup, object );
  13155. geometry.verticesNeedUpdate = true;
  13156. geometry.morphTargetsNeedUpdate = true;
  13157. geometry.elementsNeedUpdate = true;
  13158. geometry.uvsNeedUpdate = true;
  13159. geometry.normalsNeedUpdate = true;
  13160. geometry.tangentsNeedUpdate = true;
  13161. geometry.colorsNeedUpdate = true;
  13162. }
  13163. }
  13164. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13165. initDirectBuffers( geometry );
  13166. }
  13167. } else if ( object instanceof THREE.Ribbon ) {
  13168. geometry = object.geometry;
  13169. if ( ! geometry.__webglVertexBuffer ) {
  13170. createRibbonBuffers( geometry );
  13171. initRibbonBuffers( geometry, object );
  13172. geometry.verticesNeedUpdate = true;
  13173. geometry.colorsNeedUpdate = true;
  13174. geometry.normalsNeedUpdate = true;
  13175. }
  13176. } else if ( object instanceof THREE.Line ) {
  13177. geometry = object.geometry;
  13178. if ( ! geometry.__webglVertexBuffer ) {
  13179. createLineBuffers( geometry );
  13180. initLineBuffers( geometry, object );
  13181. geometry.verticesNeedUpdate = true;
  13182. geometry.colorsNeedUpdate = true;
  13183. geometry.lineDistancesNeedUpdate = true;
  13184. }
  13185. } else if ( object instanceof THREE.ParticleSystem ) {
  13186. geometry = object.geometry;
  13187. if ( ! geometry.__webglVertexBuffer ) {
  13188. if ( geometry instanceof THREE.Geometry ) {
  13189. createParticleBuffers( geometry );
  13190. initParticleBuffers( geometry, object );
  13191. geometry.verticesNeedUpdate = true;
  13192. geometry.colorsNeedUpdate = true;
  13193. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13194. initDirectBuffers( geometry );
  13195. }
  13196. }
  13197. }
  13198. }
  13199. if ( ! object.__webglActive ) {
  13200. if ( object instanceof THREE.Mesh ) {
  13201. geometry = object.geometry;
  13202. if ( geometry instanceof THREE.BufferGeometry ) {
  13203. addBuffer( scene.__webglObjects, geometry, object );
  13204. } else if ( geometry instanceof THREE.Geometry ) {
  13205. for ( g in geometry.geometryGroups ) {
  13206. geometryGroup = geometry.geometryGroups[ g ];
  13207. addBuffer( scene.__webglObjects, geometryGroup, object );
  13208. }
  13209. }
  13210. } else if ( object instanceof THREE.Ribbon ||
  13211. object instanceof THREE.Line ||
  13212. object instanceof THREE.ParticleSystem ) {
  13213. geometry = object.geometry;
  13214. addBuffer( scene.__webglObjects, geometry, object );
  13215. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13216. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13217. } else if ( object instanceof THREE.Sprite ) {
  13218. scene.__webglSprites.push( object );
  13219. } else if ( object instanceof THREE.LensFlare ) {
  13220. scene.__webglFlares.push( object );
  13221. }
  13222. object.__webglActive = true;
  13223. }
  13224. };
  13225. function addBuffer ( objlist, buffer, object ) {
  13226. objlist.push(
  13227. {
  13228. buffer: buffer,
  13229. object: object,
  13230. opaque: null,
  13231. transparent: null
  13232. }
  13233. );
  13234. };
  13235. function addBufferImmediate ( objlist, object ) {
  13236. objlist.push(
  13237. {
  13238. object: object,
  13239. opaque: null,
  13240. transparent: null
  13241. }
  13242. );
  13243. };
  13244. // Objects updates
  13245. function updateObject ( object ) {
  13246. var geometry = object.geometry,
  13247. geometryGroup, customAttributesDirty, material;
  13248. if ( object instanceof THREE.Mesh ) {
  13249. if ( geometry instanceof THREE.BufferGeometry ) {
  13250. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  13251. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13252. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  13253. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13254. }
  13255. geometry.verticesNeedUpdate = false;
  13256. geometry.elementsNeedUpdate = false;
  13257. geometry.uvsNeedUpdate = false;
  13258. geometry.normalsNeedUpdate = false;
  13259. geometry.colorsNeedUpdate = false;
  13260. geometry.tangentsNeedUpdate = false;
  13261. } else {
  13262. // check all geometry groups
  13263. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13264. geometryGroup = geometry.geometryGroupsList[ i ];
  13265. material = getBufferMaterial( object, geometryGroup );
  13266. if ( geometry.buffersNeedUpdate ) {
  13267. initMeshBuffers( geometryGroup, object );
  13268. }
  13269. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13270. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13271. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13272. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13273. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13274. }
  13275. }
  13276. geometry.verticesNeedUpdate = false;
  13277. geometry.morphTargetsNeedUpdate = false;
  13278. geometry.elementsNeedUpdate = false;
  13279. geometry.uvsNeedUpdate = false;
  13280. geometry.normalsNeedUpdate = false;
  13281. geometry.colorsNeedUpdate = false;
  13282. geometry.tangentsNeedUpdate = false;
  13283. geometry.buffersNeedUpdate = false;
  13284. material.attributes && clearCustomAttributes( material );
  13285. }
  13286. } else if ( object instanceof THREE.Ribbon ) {
  13287. material = getBufferMaterial( object, geometry );
  13288. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13289. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  13290. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  13291. }
  13292. geometry.verticesNeedUpdate = false;
  13293. geometry.colorsNeedUpdate = false;
  13294. geometry.normalsNeedUpdate = false;
  13295. material.attributes && clearCustomAttributes( material );
  13296. } else if ( object instanceof THREE.Line ) {
  13297. material = getBufferMaterial( object, geometry );
  13298. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13299. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13300. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13301. }
  13302. geometry.verticesNeedUpdate = false;
  13303. geometry.colorsNeedUpdate = false;
  13304. geometry.lineDistancesNeedUpdate = false;
  13305. material.attributes && clearCustomAttributes( material );
  13306. } else if ( object instanceof THREE.ParticleSystem ) {
  13307. if ( geometry instanceof THREE.BufferGeometry ) {
  13308. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  13309. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13310. }
  13311. geometry.verticesNeedUpdate = false;
  13312. geometry.colorsNeedUpdate = false;
  13313. } else {
  13314. material = getBufferMaterial( object, geometry );
  13315. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13316. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13317. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13318. }
  13319. geometry.verticesNeedUpdate = false;
  13320. geometry.colorsNeedUpdate = false;
  13321. material.attributes && clearCustomAttributes( material );
  13322. }
  13323. }
  13324. };
  13325. // Objects updates - custom attributes check
  13326. function areCustomAttributesDirty ( material ) {
  13327. for ( var a in material.attributes ) {
  13328. if ( material.attributes[ a ].needsUpdate ) return true;
  13329. }
  13330. return false;
  13331. };
  13332. function clearCustomAttributes ( material ) {
  13333. for ( var a in material.attributes ) {
  13334. material.attributes[ a ].needsUpdate = false;
  13335. }
  13336. };
  13337. // Objects removal
  13338. function removeObject ( object, scene ) {
  13339. if ( object instanceof THREE.Mesh ||
  13340. object instanceof THREE.ParticleSystem ||
  13341. object instanceof THREE.Ribbon ||
  13342. object instanceof THREE.Line ) {
  13343. removeInstances( scene.__webglObjects, object );
  13344. } else if ( object instanceof THREE.Sprite ) {
  13345. removeInstancesDirect( scene.__webglSprites, object );
  13346. } else if ( object instanceof THREE.LensFlare ) {
  13347. removeInstancesDirect( scene.__webglFlares, object );
  13348. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13349. removeInstances( scene.__webglObjectsImmediate, object );
  13350. }
  13351. object.__webglActive = false;
  13352. };
  13353. function removeInstances ( objlist, object ) {
  13354. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13355. if ( objlist[ o ].object === object ) {
  13356. objlist.splice( o, 1 );
  13357. }
  13358. }
  13359. };
  13360. function removeInstancesDirect ( objlist, object ) {
  13361. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13362. if ( objlist[ o ] === object ) {
  13363. objlist.splice( o, 1 );
  13364. }
  13365. }
  13366. };
  13367. // Materials
  13368. this.initMaterial = function ( material, lights, fog, object ) {
  13369. material.addEventListener( 'dispose', onMaterialDispose );
  13370. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13371. if ( material instanceof THREE.MeshDepthMaterial ) {
  13372. shaderID = 'depth';
  13373. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13374. shaderID = 'normal';
  13375. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13376. shaderID = 'basic';
  13377. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13378. shaderID = 'lambert';
  13379. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13380. shaderID = 'phong';
  13381. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13382. shaderID = 'basic';
  13383. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13384. shaderID = 'dashed';
  13385. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13386. shaderID = 'particle_basic';
  13387. }
  13388. if ( shaderID ) {
  13389. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13390. }
  13391. // heuristics to create shader parameters according to lights in the scene
  13392. // (not to blow over maxLights budget)
  13393. maxLightCount = allocateLights( lights );
  13394. maxShadows = allocateShadows( lights );
  13395. maxBones = allocateBones( object );
  13396. parameters = {
  13397. map: !!material.map,
  13398. envMap: !!material.envMap,
  13399. lightMap: !!material.lightMap,
  13400. bumpMap: !!material.bumpMap,
  13401. normalMap: !!material.normalMap,
  13402. specularMap: !!material.specularMap,
  13403. vertexColors: material.vertexColors,
  13404. fog: fog,
  13405. useFog: material.fog,
  13406. fogExp: fog instanceof THREE.FogExp2,
  13407. sizeAttenuation: material.sizeAttenuation,
  13408. skinning: material.skinning,
  13409. maxBones: maxBones,
  13410. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13411. boneTextureWidth: object && object.boneTextureWidth,
  13412. boneTextureHeight: object && object.boneTextureHeight,
  13413. morphTargets: material.morphTargets,
  13414. morphNormals: material.morphNormals,
  13415. maxMorphTargets: this.maxMorphTargets,
  13416. maxMorphNormals: this.maxMorphNormals,
  13417. maxDirLights: maxLightCount.directional,
  13418. maxPointLights: maxLightCount.point,
  13419. maxSpotLights: maxLightCount.spot,
  13420. maxHemiLights: maxLightCount.hemi,
  13421. maxShadows: maxShadows,
  13422. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13423. shadowMapType: this.shadowMapType,
  13424. shadowMapDebug: this.shadowMapDebug,
  13425. shadowMapCascade: this.shadowMapCascade,
  13426. alphaTest: material.alphaTest,
  13427. metal: material.metal,
  13428. perPixel: material.perPixel,
  13429. wrapAround: material.wrapAround,
  13430. doubleSided: material.side === THREE.DoubleSide,
  13431. flipSided: material.side === THREE.BackSide
  13432. };
  13433. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  13434. var attributes = material.program.attributes;
  13435. if ( material.morphTargets ) {
  13436. material.numSupportedMorphTargets = 0;
  13437. var id, base = "morphTarget";
  13438. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13439. id = base + i;
  13440. if ( attributes[ id ] >= 0 ) {
  13441. material.numSupportedMorphTargets ++;
  13442. }
  13443. }
  13444. }
  13445. if ( material.morphNormals ) {
  13446. material.numSupportedMorphNormals = 0;
  13447. var id, base = "morphNormal";
  13448. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13449. id = base + i;
  13450. if ( attributes[ id ] >= 0 ) {
  13451. material.numSupportedMorphNormals ++;
  13452. }
  13453. }
  13454. }
  13455. material.uniformsList = [];
  13456. for ( u in material.uniforms ) {
  13457. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13458. }
  13459. };
  13460. function setMaterialShaders( material, shaders ) {
  13461. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  13462. material.vertexShader = shaders.vertexShader;
  13463. material.fragmentShader = shaders.fragmentShader;
  13464. };
  13465. function setProgram( camera, lights, fog, material, object ) {
  13466. _usedTextureUnits = 0;
  13467. if ( material.needsUpdate ) {
  13468. if ( material.program ) deallocateMaterial( material );
  13469. _this.initMaterial( material, lights, fog, object );
  13470. material.needsUpdate = false;
  13471. }
  13472. if ( material.morphTargets ) {
  13473. if ( ! object.__webglMorphTargetInfluences ) {
  13474. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13475. }
  13476. }
  13477. var refreshMaterial = false;
  13478. var program = material.program,
  13479. p_uniforms = program.uniforms,
  13480. m_uniforms = material.uniforms;
  13481. if ( program !== _currentProgram ) {
  13482. _gl.useProgram( program );
  13483. _currentProgram = program;
  13484. refreshMaterial = true;
  13485. }
  13486. if ( material.id !== _currentMaterialId ) {
  13487. _currentMaterialId = material.id;
  13488. refreshMaterial = true;
  13489. }
  13490. if ( refreshMaterial || camera !== _currentCamera ) {
  13491. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13492. if ( camera !== _currentCamera ) _currentCamera = camera;
  13493. }
  13494. // skinning uniforms must be set even if material didn't change
  13495. // auto-setting of texture unit for bone texture must go before other textures
  13496. // not sure why, but otherwise weird things happen
  13497. if ( material.skinning ) {
  13498. if ( _supportsBoneTextures && object.useVertexTexture ) {
  13499. if ( p_uniforms.boneTexture !== null ) {
  13500. var textureUnit = getTextureUnit();
  13501. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13502. _this.setTexture( object.boneTexture, textureUnit );
  13503. }
  13504. } else {
  13505. if ( p_uniforms.boneGlobalMatrices !== null ) {
  13506. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  13507. }
  13508. }
  13509. }
  13510. if ( refreshMaterial ) {
  13511. // refresh uniforms common to several materials
  13512. if ( fog && material.fog ) {
  13513. refreshUniformsFog( m_uniforms, fog );
  13514. }
  13515. if ( material instanceof THREE.MeshPhongMaterial ||
  13516. material instanceof THREE.MeshLambertMaterial ||
  13517. material.lights ) {
  13518. if ( _lightsNeedUpdate ) {
  13519. setupLights( program, lights );
  13520. _lightsNeedUpdate = false;
  13521. }
  13522. refreshUniformsLights( m_uniforms, _lights );
  13523. }
  13524. if ( material instanceof THREE.MeshBasicMaterial ||
  13525. material instanceof THREE.MeshLambertMaterial ||
  13526. material instanceof THREE.MeshPhongMaterial ) {
  13527. refreshUniformsCommon( m_uniforms, material );
  13528. }
  13529. // refresh single material specific uniforms
  13530. if ( material instanceof THREE.LineBasicMaterial ) {
  13531. refreshUniformsLine( m_uniforms, material );
  13532. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13533. refreshUniformsLine( m_uniforms, material );
  13534. refreshUniformsDash( m_uniforms, material );
  13535. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13536. refreshUniformsParticle( m_uniforms, material );
  13537. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13538. refreshUniformsPhong( m_uniforms, material );
  13539. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13540. refreshUniformsLambert( m_uniforms, material );
  13541. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13542. m_uniforms.mNear.value = camera.near;
  13543. m_uniforms.mFar.value = camera.far;
  13544. m_uniforms.opacity.value = material.opacity;
  13545. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13546. m_uniforms.opacity.value = material.opacity;
  13547. }
  13548. if ( object.receiveShadow && ! material._shadowPass ) {
  13549. refreshUniformsShadow( m_uniforms, lights );
  13550. }
  13551. // load common uniforms
  13552. loadUniformsGeneric( program, material.uniformsList );
  13553. // load material specific uniforms
  13554. // (shader material also gets them for the sake of genericity)
  13555. if ( material instanceof THREE.ShaderMaterial ||
  13556. material instanceof THREE.MeshPhongMaterial ||
  13557. material.envMap ) {
  13558. if ( p_uniforms.cameraPosition !== null ) {
  13559. var position = camera.matrixWorld.getPosition();
  13560. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  13561. }
  13562. }
  13563. if ( material instanceof THREE.MeshPhongMaterial ||
  13564. material instanceof THREE.MeshLambertMaterial ||
  13565. material instanceof THREE.ShaderMaterial ||
  13566. material.skinning ) {
  13567. if ( p_uniforms.viewMatrix !== null ) {
  13568. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13569. }
  13570. }
  13571. }
  13572. loadUniformsMatrices( p_uniforms, object );
  13573. if ( p_uniforms.modelMatrix !== null ) {
  13574. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13575. }
  13576. return program;
  13577. };
  13578. // Uniforms (refresh uniforms objects)
  13579. function refreshUniformsCommon ( uniforms, material ) {
  13580. uniforms.opacity.value = material.opacity;
  13581. if ( _this.gammaInput ) {
  13582. uniforms.diffuse.value.copyGammaToLinear( material.color );
  13583. } else {
  13584. uniforms.diffuse.value = material.color;
  13585. }
  13586. uniforms.map.value = material.map;
  13587. uniforms.lightMap.value = material.lightMap;
  13588. uniforms.specularMap.value = material.specularMap;
  13589. if ( material.bumpMap ) {
  13590. uniforms.bumpMap.value = material.bumpMap;
  13591. uniforms.bumpScale.value = material.bumpScale;
  13592. }
  13593. if ( material.normalMap ) {
  13594. uniforms.normalMap.value = material.normalMap;
  13595. uniforms.normalScale.value.copy( material.normalScale );
  13596. }
  13597. // uv repeat and offset setting priorities
  13598. // 1. color map
  13599. // 2. specular map
  13600. // 3. normal map
  13601. // 4. bump map
  13602. var uvScaleMap;
  13603. if ( material.map ) {
  13604. uvScaleMap = material.map;
  13605. } else if ( material.specularMap ) {
  13606. uvScaleMap = material.specularMap;
  13607. } else if ( material.normalMap ) {
  13608. uvScaleMap = material.normalMap;
  13609. } else if ( material.bumpMap ) {
  13610. uvScaleMap = material.bumpMap;
  13611. }
  13612. if ( uvScaleMap !== undefined ) {
  13613. var offset = uvScaleMap.offset;
  13614. var repeat = uvScaleMap.repeat;
  13615. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13616. }
  13617. uniforms.envMap.value = material.envMap;
  13618. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  13619. if ( _this.gammaInput ) {
  13620. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  13621. uniforms.reflectivity.value = material.reflectivity;
  13622. } else {
  13623. uniforms.reflectivity.value = material.reflectivity;
  13624. }
  13625. uniforms.refractionRatio.value = material.refractionRatio;
  13626. uniforms.combine.value = material.combine;
  13627. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  13628. };
  13629. function refreshUniformsLine ( uniforms, material ) {
  13630. uniforms.diffuse.value = material.color;
  13631. uniforms.opacity.value = material.opacity;
  13632. };
  13633. function refreshUniformsDash ( uniforms, material ) {
  13634. uniforms.dashSize.value = material.dashSize;
  13635. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13636. uniforms.scale.value = material.scale;
  13637. };
  13638. function refreshUniformsParticle ( uniforms, material ) {
  13639. uniforms.psColor.value = material.color;
  13640. uniforms.opacity.value = material.opacity;
  13641. uniforms.size.value = material.size;
  13642. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  13643. uniforms.map.value = material.map;
  13644. };
  13645. function refreshUniformsFog ( uniforms, fog ) {
  13646. uniforms.fogColor.value = fog.color;
  13647. if ( fog instanceof THREE.Fog ) {
  13648. uniforms.fogNear.value = fog.near;
  13649. uniforms.fogFar.value = fog.far;
  13650. } else if ( fog instanceof THREE.FogExp2 ) {
  13651. uniforms.fogDensity.value = fog.density;
  13652. }
  13653. };
  13654. function refreshUniformsPhong ( uniforms, material ) {
  13655. uniforms.shininess.value = material.shininess;
  13656. if ( _this.gammaInput ) {
  13657. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13658. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13659. uniforms.specular.value.copyGammaToLinear( material.specular );
  13660. } else {
  13661. uniforms.ambient.value = material.ambient;
  13662. uniforms.emissive.value = material.emissive;
  13663. uniforms.specular.value = material.specular;
  13664. }
  13665. if ( material.wrapAround ) {
  13666. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13667. }
  13668. };
  13669. function refreshUniformsLambert ( uniforms, material ) {
  13670. if ( _this.gammaInput ) {
  13671. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13672. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13673. } else {
  13674. uniforms.ambient.value = material.ambient;
  13675. uniforms.emissive.value = material.emissive;
  13676. }
  13677. if ( material.wrapAround ) {
  13678. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13679. }
  13680. };
  13681. function refreshUniformsLights ( uniforms, lights ) {
  13682. uniforms.ambientLightColor.value = lights.ambient;
  13683. uniforms.directionalLightColor.value = lights.directional.colors;
  13684. uniforms.directionalLightDirection.value = lights.directional.positions;
  13685. uniforms.pointLightColor.value = lights.point.colors;
  13686. uniforms.pointLightPosition.value = lights.point.positions;
  13687. uniforms.pointLightDistance.value = lights.point.distances;
  13688. uniforms.spotLightColor.value = lights.spot.colors;
  13689. uniforms.spotLightPosition.value = lights.spot.positions;
  13690. uniforms.spotLightDistance.value = lights.spot.distances;
  13691. uniforms.spotLightDirection.value = lights.spot.directions;
  13692. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  13693. uniforms.spotLightExponent.value = lights.spot.exponents;
  13694. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  13695. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  13696. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  13697. };
  13698. function refreshUniformsShadow ( uniforms, lights ) {
  13699. if ( uniforms.shadowMatrix ) {
  13700. var j = 0;
  13701. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  13702. var light = lights[ i ];
  13703. if ( ! light.castShadow ) continue;
  13704. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  13705. uniforms.shadowMap.value[ j ] = light.shadowMap;
  13706. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  13707. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  13708. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  13709. uniforms.shadowBias.value[ j ] = light.shadowBias;
  13710. j ++;
  13711. }
  13712. }
  13713. }
  13714. };
  13715. // Uniforms (load to GPU)
  13716. function loadUniformsMatrices ( uniforms, object ) {
  13717. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  13718. if ( uniforms.normalMatrix ) {
  13719. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  13720. }
  13721. };
  13722. function getTextureUnit() {
  13723. var textureUnit = _usedTextureUnits;
  13724. if ( textureUnit >= _maxTextures ) {
  13725. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  13726. }
  13727. _usedTextureUnits += 1;
  13728. return textureUnit;
  13729. };
  13730. function loadUniformsGeneric ( program, uniforms ) {
  13731. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  13732. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  13733. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  13734. if ( !location ) continue;
  13735. uniform = uniforms[ j ][ 0 ];
  13736. type = uniform.type;
  13737. value = uniform.value;
  13738. if ( type === "i" ) { // single integer
  13739. _gl.uniform1i( location, value );
  13740. } else if ( type === "f" ) { // single float
  13741. _gl.uniform1f( location, value );
  13742. } else if ( type === "v2" ) { // single THREE.Vector2
  13743. _gl.uniform2f( location, value.x, value.y );
  13744. } else if ( type === "v3" ) { // single THREE.Vector3
  13745. _gl.uniform3f( location, value.x, value.y, value.z );
  13746. } else if ( type === "v4" ) { // single THREE.Vector4
  13747. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  13748. } else if ( type === "c" ) { // single THREE.Color
  13749. _gl.uniform3f( location, value.r, value.g, value.b );
  13750. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  13751. _gl.uniform1iv( location, value );
  13752. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  13753. _gl.uniform3iv( location, value );
  13754. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  13755. _gl.uniform1fv( location, value );
  13756. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  13757. _gl.uniform3fv( location, value );
  13758. } else if ( type === "v2v" ) { // array of THREE.Vector2
  13759. if ( uniform._array === undefined ) {
  13760. uniform._array = new Float32Array( 2 * value.length );
  13761. }
  13762. for ( i = 0, il = value.length; i < il; i ++ ) {
  13763. offset = i * 2;
  13764. uniform._array[ offset ] = value[ i ].x;
  13765. uniform._array[ offset + 1 ] = value[ i ].y;
  13766. }
  13767. _gl.uniform2fv( location, uniform._array );
  13768. } else if ( type === "v3v" ) { // array of THREE.Vector3
  13769. if ( uniform._array === undefined ) {
  13770. uniform._array = new Float32Array( 3 * value.length );
  13771. }
  13772. for ( i = 0, il = value.length; i < il; i ++ ) {
  13773. offset = i * 3;
  13774. uniform._array[ offset ] = value[ i ].x;
  13775. uniform._array[ offset + 1 ] = value[ i ].y;
  13776. uniform._array[ offset + 2 ] = value[ i ].z;
  13777. }
  13778. _gl.uniform3fv( location, uniform._array );
  13779. } else if ( type === "v4v" ) { // array of THREE.Vector4
  13780. if ( uniform._array === undefined ) {
  13781. uniform._array = new Float32Array( 4 * value.length );
  13782. }
  13783. for ( i = 0, il = value.length; i < il; i ++ ) {
  13784. offset = i * 4;
  13785. uniform._array[ offset ] = value[ i ].x;
  13786. uniform._array[ offset + 1 ] = value[ i ].y;
  13787. uniform._array[ offset + 2 ] = value[ i ].z;
  13788. uniform._array[ offset + 3 ] = value[ i ].w;
  13789. }
  13790. _gl.uniform4fv( location, uniform._array );
  13791. } else if ( type === "m4") { // single THREE.Matrix4
  13792. if ( uniform._array === undefined ) {
  13793. uniform._array = new Float32Array( 16 );
  13794. }
  13795. value.flattenToArray( uniform._array );
  13796. _gl.uniformMatrix4fv( location, false, uniform._array );
  13797. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  13798. if ( uniform._array === undefined ) {
  13799. uniform._array = new Float32Array( 16 * value.length );
  13800. }
  13801. for ( i = 0, il = value.length; i < il; i ++ ) {
  13802. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  13803. }
  13804. _gl.uniformMatrix4fv( location, false, uniform._array );
  13805. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  13806. texture = value;
  13807. textureUnit = getTextureUnit();
  13808. _gl.uniform1i( location, textureUnit );
  13809. if ( !texture ) continue;
  13810. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  13811. setCubeTexture( texture, textureUnit );
  13812. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  13813. setCubeTextureDynamic( texture, textureUnit );
  13814. } else {
  13815. _this.setTexture( texture, textureUnit );
  13816. }
  13817. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  13818. if ( uniform._array === undefined ) {
  13819. uniform._array = [];
  13820. }
  13821. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13822. uniform._array[ i ] = getTextureUnit();
  13823. }
  13824. _gl.uniform1iv( location, uniform._array );
  13825. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13826. texture = uniform.value[ i ];
  13827. textureUnit = uniform._array[ i ];
  13828. if ( !texture ) continue;
  13829. _this.setTexture( texture, textureUnit );
  13830. }
  13831. }
  13832. }
  13833. };
  13834. function setupMatrices ( object, camera ) {
  13835. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  13836. object._normalMatrix.getInverse( object._modelViewMatrix );
  13837. object._normalMatrix.transpose();
  13838. };
  13839. //
  13840. function setColorGamma( array, offset, color, intensitySq ) {
  13841. array[ offset ] = color.r * color.r * intensitySq;
  13842. array[ offset + 1 ] = color.g * color.g * intensitySq;
  13843. array[ offset + 2 ] = color.b * color.b * intensitySq;
  13844. };
  13845. function setColorLinear( array, offset, color, intensity ) {
  13846. array[ offset ] = color.r * intensity;
  13847. array[ offset + 1 ] = color.g * intensity;
  13848. array[ offset + 2 ] = color.b * intensity;
  13849. };
  13850. function setupLights ( program, lights ) {
  13851. var l, ll, light, n,
  13852. r = 0, g = 0, b = 0,
  13853. color, skyColor, groundColor,
  13854. intensity, intensitySq,
  13855. position,
  13856. distance,
  13857. zlights = _lights,
  13858. dirColors = zlights.directional.colors,
  13859. dirPositions = zlights.directional.positions,
  13860. pointColors = zlights.point.colors,
  13861. pointPositions = zlights.point.positions,
  13862. pointDistances = zlights.point.distances,
  13863. spotColors = zlights.spot.colors,
  13864. spotPositions = zlights.spot.positions,
  13865. spotDistances = zlights.spot.distances,
  13866. spotDirections = zlights.spot.directions,
  13867. spotAnglesCos = zlights.spot.anglesCos,
  13868. spotExponents = zlights.spot.exponents,
  13869. hemiSkyColors = zlights.hemi.skyColors,
  13870. hemiGroundColors = zlights.hemi.groundColors,
  13871. hemiPositions = zlights.hemi.positions,
  13872. dirLength = 0,
  13873. pointLength = 0,
  13874. spotLength = 0,
  13875. hemiLength = 0,
  13876. dirCount = 0,
  13877. pointCount = 0,
  13878. spotCount = 0,
  13879. hemiCount = 0,
  13880. dirOffset = 0,
  13881. pointOffset = 0,
  13882. spotOffset = 0,
  13883. hemiOffset = 0;
  13884. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13885. light = lights[ l ];
  13886. if ( light.onlyShadow ) continue;
  13887. color = light.color;
  13888. intensity = light.intensity;
  13889. distance = light.distance;
  13890. if ( light instanceof THREE.AmbientLight ) {
  13891. if ( ! light.visible ) continue;
  13892. if ( _this.gammaInput ) {
  13893. r += color.r * color.r;
  13894. g += color.g * color.g;
  13895. b += color.b * color.b;
  13896. } else {
  13897. r += color.r;
  13898. g += color.g;
  13899. b += color.b;
  13900. }
  13901. } else if ( light instanceof THREE.DirectionalLight ) {
  13902. dirCount += 1;
  13903. if ( ! light.visible ) continue;
  13904. _direction.copy( light.matrixWorld.getPosition() );
  13905. _direction.subSelf( light.target.matrixWorld.getPosition() );
  13906. _direction.normalize();
  13907. // skip lights with undefined direction
  13908. // these create troubles in OpenGL (making pixel black)
  13909. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  13910. dirOffset = dirLength * 3;
  13911. dirPositions[ dirOffset ] = _direction.x;
  13912. dirPositions[ dirOffset + 1 ] = _direction.y;
  13913. dirPositions[ dirOffset + 2 ] = _direction.z;
  13914. if ( _this.gammaInput ) {
  13915. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  13916. } else {
  13917. setColorLinear( dirColors, dirOffset, color, intensity );
  13918. }
  13919. dirLength += 1;
  13920. } else if ( light instanceof THREE.PointLight ) {
  13921. pointCount += 1;
  13922. if ( ! light.visible ) continue;
  13923. pointOffset = pointLength * 3;
  13924. if ( _this.gammaInput ) {
  13925. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  13926. } else {
  13927. setColorLinear( pointColors, pointOffset, color, intensity );
  13928. }
  13929. position = light.matrixWorld.getPosition();
  13930. pointPositions[ pointOffset ] = position.x;
  13931. pointPositions[ pointOffset + 1 ] = position.y;
  13932. pointPositions[ pointOffset + 2 ] = position.z;
  13933. pointDistances[ pointLength ] = distance;
  13934. pointLength += 1;
  13935. } else if ( light instanceof THREE.SpotLight ) {
  13936. spotCount += 1;
  13937. if ( ! light.visible ) continue;
  13938. spotOffset = spotLength * 3;
  13939. if ( _this.gammaInput ) {
  13940. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  13941. } else {
  13942. setColorLinear( spotColors, spotOffset, color, intensity );
  13943. }
  13944. position = light.matrixWorld.getPosition();
  13945. spotPositions[ spotOffset ] = position.x;
  13946. spotPositions[ spotOffset + 1 ] = position.y;
  13947. spotPositions[ spotOffset + 2 ] = position.z;
  13948. spotDistances[ spotLength ] = distance;
  13949. _direction.copy( position );
  13950. _direction.subSelf( light.target.matrixWorld.getPosition() );
  13951. _direction.normalize();
  13952. spotDirections[ spotOffset ] = _direction.x;
  13953. spotDirections[ spotOffset + 1 ] = _direction.y;
  13954. spotDirections[ spotOffset + 2 ] = _direction.z;
  13955. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  13956. spotExponents[ spotLength ] = light.exponent;
  13957. spotLength += 1;
  13958. } else if ( light instanceof THREE.HemisphereLight ) {
  13959. hemiCount += 1;
  13960. if ( ! light.visible ) continue;
  13961. _direction.copy( light.matrixWorld.getPosition() );
  13962. _direction.normalize();
  13963. // skip lights with undefined direction
  13964. // these create troubles in OpenGL (making pixel black)
  13965. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  13966. hemiOffset = hemiLength * 3;
  13967. hemiPositions[ hemiOffset ] = _direction.x;
  13968. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  13969. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  13970. skyColor = light.color;
  13971. groundColor = light.groundColor;
  13972. if ( _this.gammaInput ) {
  13973. intensitySq = intensity * intensity;
  13974. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  13975. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  13976. } else {
  13977. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  13978. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  13979. }
  13980. hemiLength += 1;
  13981. }
  13982. }
  13983. // null eventual remains from removed lights
  13984. // (this is to avoid if in shader)
  13985. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  13986. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  13987. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  13988. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  13989. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  13990. zlights.directional.length = dirLength;
  13991. zlights.point.length = pointLength;
  13992. zlights.spot.length = spotLength;
  13993. zlights.hemi.length = hemiLength;
  13994. zlights.ambient[ 0 ] = r;
  13995. zlights.ambient[ 1 ] = g;
  13996. zlights.ambient[ 2 ] = b;
  13997. };
  13998. // GL state setting
  13999. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14000. if ( cullFace === THREE.CullFaceNone ) {
  14001. _gl.disable( _gl.CULL_FACE );
  14002. } else {
  14003. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14004. _gl.frontFace( _gl.CW );
  14005. } else {
  14006. _gl.frontFace( _gl.CCW );
  14007. }
  14008. if ( cullFace === THREE.CullFaceBack ) {
  14009. _gl.cullFace( _gl.BACK );
  14010. } else if ( cullFace === THREE.CullFaceFront ) {
  14011. _gl.cullFace( _gl.FRONT );
  14012. } else {
  14013. _gl.cullFace( _gl.FRONT_AND_BACK );
  14014. }
  14015. _gl.enable( _gl.CULL_FACE );
  14016. }
  14017. };
  14018. this.setMaterialFaces = function ( material ) {
  14019. var doubleSided = material.side === THREE.DoubleSide;
  14020. var flipSided = material.side === THREE.BackSide;
  14021. if ( _oldDoubleSided !== doubleSided ) {
  14022. if ( doubleSided ) {
  14023. _gl.disable( _gl.CULL_FACE );
  14024. } else {
  14025. _gl.enable( _gl.CULL_FACE );
  14026. }
  14027. _oldDoubleSided = doubleSided;
  14028. }
  14029. if ( _oldFlipSided !== flipSided ) {
  14030. if ( flipSided ) {
  14031. _gl.frontFace( _gl.CW );
  14032. } else {
  14033. _gl.frontFace( _gl.CCW );
  14034. }
  14035. _oldFlipSided = flipSided;
  14036. }
  14037. };
  14038. this.setDepthTest = function ( depthTest ) {
  14039. if ( _oldDepthTest !== depthTest ) {
  14040. if ( depthTest ) {
  14041. _gl.enable( _gl.DEPTH_TEST );
  14042. } else {
  14043. _gl.disable( _gl.DEPTH_TEST );
  14044. }
  14045. _oldDepthTest = depthTest;
  14046. }
  14047. };
  14048. this.setDepthWrite = function ( depthWrite ) {
  14049. if ( _oldDepthWrite !== depthWrite ) {
  14050. _gl.depthMask( depthWrite );
  14051. _oldDepthWrite = depthWrite;
  14052. }
  14053. };
  14054. function setLineWidth ( width ) {
  14055. if ( width !== _oldLineWidth ) {
  14056. _gl.lineWidth( width );
  14057. _oldLineWidth = width;
  14058. }
  14059. };
  14060. function setPolygonOffset ( polygonoffset, factor, units ) {
  14061. if ( _oldPolygonOffset !== polygonoffset ) {
  14062. if ( polygonoffset ) {
  14063. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14064. } else {
  14065. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14066. }
  14067. _oldPolygonOffset = polygonoffset;
  14068. }
  14069. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14070. _gl.polygonOffset( factor, units );
  14071. _oldPolygonOffsetFactor = factor;
  14072. _oldPolygonOffsetUnits = units;
  14073. }
  14074. };
  14075. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14076. if ( blending !== _oldBlending ) {
  14077. if ( blending === THREE.NoBlending ) {
  14078. _gl.disable( _gl.BLEND );
  14079. } else if ( blending === THREE.AdditiveBlending ) {
  14080. _gl.enable( _gl.BLEND );
  14081. _gl.blendEquation( _gl.FUNC_ADD );
  14082. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14083. } else if ( blending === THREE.SubtractiveBlending ) {
  14084. // TODO: Find blendFuncSeparate() combination
  14085. _gl.enable( _gl.BLEND );
  14086. _gl.blendEquation( _gl.FUNC_ADD );
  14087. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14088. } else if ( blending === THREE.MultiplyBlending ) {
  14089. // TODO: Find blendFuncSeparate() combination
  14090. _gl.enable( _gl.BLEND );
  14091. _gl.blendEquation( _gl.FUNC_ADD );
  14092. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14093. } else if ( blending === THREE.CustomBlending ) {
  14094. _gl.enable( _gl.BLEND );
  14095. } else {
  14096. _gl.enable( _gl.BLEND );
  14097. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14098. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14099. }
  14100. _oldBlending = blending;
  14101. }
  14102. if ( blending === THREE.CustomBlending ) {
  14103. if ( blendEquation !== _oldBlendEquation ) {
  14104. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14105. _oldBlendEquation = blendEquation;
  14106. }
  14107. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14108. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14109. _oldBlendSrc = blendSrc;
  14110. _oldBlendDst = blendDst;
  14111. }
  14112. } else {
  14113. _oldBlendEquation = null;
  14114. _oldBlendSrc = null;
  14115. _oldBlendDst = null;
  14116. }
  14117. };
  14118. // Defines
  14119. function generateDefines ( defines ) {
  14120. var value, chunk, chunks = [];
  14121. for ( var d in defines ) {
  14122. value = defines[ d ];
  14123. if ( value === false ) continue;
  14124. chunk = "#define " + d + " " + value;
  14125. chunks.push( chunk );
  14126. }
  14127. return chunks.join( "\n" );
  14128. };
  14129. // Shaders
  14130. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  14131. var p, pl, d, program, code;
  14132. var chunks = [];
  14133. // Generate code
  14134. if ( shaderID ) {
  14135. chunks.push( shaderID );
  14136. } else {
  14137. chunks.push( fragmentShader );
  14138. chunks.push( vertexShader );
  14139. }
  14140. for ( d in defines ) {
  14141. chunks.push( d );
  14142. chunks.push( defines[ d ] );
  14143. }
  14144. for ( p in parameters ) {
  14145. chunks.push( p );
  14146. chunks.push( parameters[ p ] );
  14147. }
  14148. code = chunks.join();
  14149. // Check if code has been already compiled
  14150. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14151. var programInfo = _programs[ p ];
  14152. if ( programInfo.code === code ) {
  14153. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  14154. programInfo.usedTimes ++;
  14155. return programInfo.program;
  14156. }
  14157. }
  14158. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14159. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14160. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14161. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14162. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14163. }
  14164. //console.log( "building new program " );
  14165. //
  14166. var customDefines = generateDefines( defines );
  14167. //
  14168. program = _gl.createProgram();
  14169. var prefix_vertex = [
  14170. "precision " + _precision + " float;",
  14171. customDefines,
  14172. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14173. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14174. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14175. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14176. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14177. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14178. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14179. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14180. "#define MAX_SHADOWS " + parameters.maxShadows,
  14181. "#define MAX_BONES " + parameters.maxBones,
  14182. parameters.map ? "#define USE_MAP" : "",
  14183. parameters.envMap ? "#define USE_ENVMAP" : "",
  14184. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14185. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14186. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14187. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14188. parameters.vertexColors ? "#define USE_COLOR" : "",
  14189. parameters.skinning ? "#define USE_SKINNING" : "",
  14190. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14191. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  14192. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  14193. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14194. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14195. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14196. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14197. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14198. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14199. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14200. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14201. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14202. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14203. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14204. "uniform mat4 modelMatrix;",
  14205. "uniform mat4 modelViewMatrix;",
  14206. "uniform mat4 projectionMatrix;",
  14207. "uniform mat4 viewMatrix;",
  14208. "uniform mat3 normalMatrix;",
  14209. "uniform vec3 cameraPosition;",
  14210. "attribute vec3 position;",
  14211. "attribute vec3 normal;",
  14212. "attribute vec2 uv;",
  14213. "attribute vec2 uv2;",
  14214. "#ifdef USE_COLOR",
  14215. "attribute vec3 color;",
  14216. "#endif",
  14217. "#ifdef USE_MORPHTARGETS",
  14218. "attribute vec3 morphTarget0;",
  14219. "attribute vec3 morphTarget1;",
  14220. "attribute vec3 morphTarget2;",
  14221. "attribute vec3 morphTarget3;",
  14222. "#ifdef USE_MORPHNORMALS",
  14223. "attribute vec3 morphNormal0;",
  14224. "attribute vec3 morphNormal1;",
  14225. "attribute vec3 morphNormal2;",
  14226. "attribute vec3 morphNormal3;",
  14227. "#else",
  14228. "attribute vec3 morphTarget4;",
  14229. "attribute vec3 morphTarget5;",
  14230. "attribute vec3 morphTarget6;",
  14231. "attribute vec3 morphTarget7;",
  14232. "#endif",
  14233. "#endif",
  14234. "#ifdef USE_SKINNING",
  14235. "attribute vec4 skinIndex;",
  14236. "attribute vec4 skinWeight;",
  14237. "#endif",
  14238. ""
  14239. ].join("\n");
  14240. var prefix_fragment = [
  14241. "precision " + _precision + " float;",
  14242. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14243. customDefines,
  14244. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14245. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14246. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14247. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14248. "#define MAX_SHADOWS " + parameters.maxShadows,
  14249. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14250. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14251. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14252. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14253. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14254. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14255. parameters.map ? "#define USE_MAP" : "",
  14256. parameters.envMap ? "#define USE_ENVMAP" : "",
  14257. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14258. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14259. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14260. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14261. parameters.vertexColors ? "#define USE_COLOR" : "",
  14262. parameters.metal ? "#define METAL" : "",
  14263. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14264. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14265. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14266. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14267. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14268. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14269. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14270. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14271. "uniform mat4 viewMatrix;",
  14272. "uniform vec3 cameraPosition;",
  14273. ""
  14274. ].join("\n");
  14275. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14276. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14277. _gl.attachShader( program, glVertexShader );
  14278. _gl.attachShader( program, glFragmentShader );
  14279. _gl.linkProgram( program );
  14280. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14281. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14282. }
  14283. // clean up
  14284. _gl.deleteShader( glFragmentShader );
  14285. _gl.deleteShader( glVertexShader );
  14286. //console.log( prefix_fragment + fragmentShader );
  14287. //console.log( prefix_vertex + vertexShader );
  14288. program.uniforms = {};
  14289. program.attributes = {};
  14290. var identifiers, u, a, i;
  14291. // cache uniform locations
  14292. identifiers = [
  14293. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14294. 'morphTargetInfluences'
  14295. ];
  14296. if ( parameters.useVertexTexture ) {
  14297. identifiers.push( 'boneTexture' );
  14298. } else {
  14299. identifiers.push( 'boneGlobalMatrices' );
  14300. }
  14301. for ( u in uniforms ) {
  14302. identifiers.push( u );
  14303. }
  14304. cacheUniformLocations( program, identifiers );
  14305. // cache attributes locations
  14306. identifiers = [
  14307. "position", "normal", "uv", "uv2", "tangent", "color",
  14308. "skinIndex", "skinWeight", "lineDistance"
  14309. ];
  14310. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14311. identifiers.push( "morphTarget" + i );
  14312. }
  14313. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14314. identifiers.push( "morphNormal" + i );
  14315. }
  14316. for ( a in attributes ) {
  14317. identifiers.push( a );
  14318. }
  14319. cacheAttributeLocations( program, identifiers );
  14320. program.id = _programs_counter ++;
  14321. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14322. _this.info.memory.programs = _programs.length;
  14323. return program;
  14324. };
  14325. // Shader parameters cache
  14326. function cacheUniformLocations ( program, identifiers ) {
  14327. var i, l, id;
  14328. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14329. id = identifiers[ i ];
  14330. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14331. }
  14332. };
  14333. function cacheAttributeLocations ( program, identifiers ) {
  14334. var i, l, id;
  14335. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14336. id = identifiers[ i ];
  14337. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14338. }
  14339. };
  14340. function addLineNumbers ( string ) {
  14341. var chunks = string.split( "\n" );
  14342. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14343. // Chrome reports shader errors on lines
  14344. // starting counting from 1
  14345. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14346. }
  14347. return chunks.join( "\n" );
  14348. };
  14349. function getShader ( type, string ) {
  14350. var shader;
  14351. if ( type === "fragment" ) {
  14352. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14353. } else if ( type === "vertex" ) {
  14354. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14355. }
  14356. _gl.shaderSource( shader, string );
  14357. _gl.compileShader( shader );
  14358. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14359. console.error( _gl.getShaderInfoLog( shader ) );
  14360. console.error( addLineNumbers( string ) );
  14361. return null;
  14362. }
  14363. return shader;
  14364. };
  14365. // Textures
  14366. function isPowerOfTwo ( value ) {
  14367. return ( value & ( value - 1 ) ) === 0;
  14368. };
  14369. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14370. if ( isImagePowerOfTwo ) {
  14371. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14372. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14373. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14374. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14375. } else {
  14376. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14377. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14378. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14379. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14380. }
  14381. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14382. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14383. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14384. texture.__oldAnisotropy = texture.anisotropy;
  14385. }
  14386. }
  14387. };
  14388. this.setTexture = function ( texture, slot ) {
  14389. if ( texture.needsUpdate ) {
  14390. if ( ! texture.__webglInit ) {
  14391. texture.__webglInit = true;
  14392. texture.addEventListener( 'dispose', onTextureDispose );
  14393. texture.__webglTexture = _gl.createTexture();
  14394. _this.info.memory.textures ++;
  14395. }
  14396. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14397. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14398. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14399. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14400. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14401. var image = texture.image,
  14402. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14403. glFormat = paramThreeToGL( texture.format ),
  14404. glType = paramThreeToGL( texture.type );
  14405. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14406. var mipmap, mipmaps = texture.mipmaps;
  14407. if ( texture instanceof THREE.DataTexture ) {
  14408. // use manually created mipmaps if available
  14409. // if there are no manual mipmaps
  14410. // set 0 level mipmap and then use GL to generate other mipmap levels
  14411. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14412. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14413. mipmap = mipmaps[ i ];
  14414. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14415. }
  14416. texture.generateMipmaps = false;
  14417. } else {
  14418. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14419. }
  14420. } else if ( texture instanceof THREE.CompressedTexture ) {
  14421. // compressed textures can only use manually created mipmaps
  14422. // WebGL can't generate mipmaps for DDS textures
  14423. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14424. mipmap = mipmaps[ i ];
  14425. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14426. }
  14427. } else { // regular Texture (image, video, canvas)
  14428. // use manually created mipmaps if available
  14429. // if there are no manual mipmaps
  14430. // set 0 level mipmap and then use GL to generate other mipmap levels
  14431. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14432. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14433. mipmap = mipmaps[ i ];
  14434. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14435. }
  14436. texture.generateMipmaps = false;
  14437. } else {
  14438. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14439. }
  14440. }
  14441. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14442. texture.needsUpdate = false;
  14443. if ( texture.onUpdate ) texture.onUpdate();
  14444. } else {
  14445. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14446. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14447. }
  14448. };
  14449. function clampToMaxSize ( image, maxSize ) {
  14450. if ( image.width <= maxSize && image.height <= maxSize ) {
  14451. return image;
  14452. }
  14453. // Warning: Scaling through the canvas will only work with images that use
  14454. // premultiplied alpha.
  14455. var maxDimension = Math.max( image.width, image.height );
  14456. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  14457. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  14458. var canvas = document.createElement( 'canvas' );
  14459. canvas.width = newWidth;
  14460. canvas.height = newHeight;
  14461. var ctx = canvas.getContext( "2d" );
  14462. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  14463. return canvas;
  14464. }
  14465. function setCubeTexture ( texture, slot ) {
  14466. if ( texture.image.length === 6 ) {
  14467. if ( texture.needsUpdate ) {
  14468. if ( ! texture.image.__webglTextureCube ) {
  14469. texture.image.__webglTextureCube = _gl.createTexture();
  14470. _this.info.memory.textures ++;
  14471. }
  14472. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14473. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14474. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14475. var isCompressed = texture instanceof THREE.CompressedTexture;
  14476. var cubeImage = [];
  14477. for ( var i = 0; i < 6; i ++ ) {
  14478. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  14479. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14480. } else {
  14481. cubeImage[ i ] = texture.image[ i ];
  14482. }
  14483. }
  14484. var image = cubeImage[ 0 ],
  14485. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14486. glFormat = paramThreeToGL( texture.format ),
  14487. glType = paramThreeToGL( texture.type );
  14488. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14489. for ( var i = 0; i < 6; i ++ ) {
  14490. if ( isCompressed ) {
  14491. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14492. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14493. mipmap = mipmaps[ j ];
  14494. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14495. }
  14496. } else {
  14497. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14498. }
  14499. }
  14500. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  14501. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14502. }
  14503. texture.needsUpdate = false;
  14504. if ( texture.onUpdate ) texture.onUpdate();
  14505. } else {
  14506. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14507. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14508. }
  14509. }
  14510. };
  14511. function setCubeTextureDynamic ( texture, slot ) {
  14512. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14513. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  14514. };
  14515. // Render targets
  14516. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  14517. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14518. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  14519. };
  14520. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  14521. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14522. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14523. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14524. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14525. /* For some reason this is not working. Defaulting to RGBA4.
  14526. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14527. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14528. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14529. */
  14530. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14531. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14532. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14533. } else {
  14534. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14535. }
  14536. };
  14537. this.setRenderTarget = function ( renderTarget ) {
  14538. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14539. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  14540. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14541. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14542. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14543. renderTarget.__webglTexture = _gl.createTexture();
  14544. _this.info.memory.textures ++;
  14545. // Setup texture, create render and frame buffers
  14546. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  14547. glFormat = paramThreeToGL( renderTarget.format ),
  14548. glType = paramThreeToGL( renderTarget.type );
  14549. if ( isCube ) {
  14550. renderTarget.__webglFramebuffer = [];
  14551. renderTarget.__webglRenderbuffer = [];
  14552. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14553. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  14554. for ( var i = 0; i < 6; i ++ ) {
  14555. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14556. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14557. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14558. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14559. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  14560. }
  14561. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14562. } else {
  14563. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  14564. if ( renderTarget.shareDepthFrom ) {
  14565. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  14566. } else {
  14567. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  14568. }
  14569. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14570. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  14571. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14572. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14573. if ( renderTarget.shareDepthFrom ) {
  14574. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14575. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14576. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14577. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14578. }
  14579. } else {
  14580. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  14581. }
  14582. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14583. }
  14584. // Release everything
  14585. if ( isCube ) {
  14586. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14587. } else {
  14588. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14589. }
  14590. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14591. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14592. }
  14593. var framebuffer, width, height, vx, vy;
  14594. if ( renderTarget ) {
  14595. if ( isCube ) {
  14596. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  14597. } else {
  14598. framebuffer = renderTarget.__webglFramebuffer;
  14599. }
  14600. width = renderTarget.width;
  14601. height = renderTarget.height;
  14602. vx = 0;
  14603. vy = 0;
  14604. } else {
  14605. framebuffer = null;
  14606. width = _viewportWidth;
  14607. height = _viewportHeight;
  14608. vx = _viewportX;
  14609. vy = _viewportY;
  14610. }
  14611. if ( framebuffer !== _currentFramebuffer ) {
  14612. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14613. _gl.viewport( vx, vy, width, height );
  14614. _currentFramebuffer = framebuffer;
  14615. }
  14616. _currentWidth = width;
  14617. _currentHeight = height;
  14618. };
  14619. function updateRenderTargetMipmap ( renderTarget ) {
  14620. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14621. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14622. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14623. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14624. } else {
  14625. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14626. _gl.generateMipmap( _gl.TEXTURE_2D );
  14627. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14628. }
  14629. };
  14630. // Fallback filters for non-power-of-2 textures
  14631. function filterFallback ( f ) {
  14632. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  14633. return _gl.NEAREST;
  14634. }
  14635. return _gl.LINEAR;
  14636. };
  14637. // Map three.js constants to WebGL constants
  14638. function paramThreeToGL ( p ) {
  14639. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  14640. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  14641. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  14642. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  14643. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  14644. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  14645. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  14646. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  14647. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  14648. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  14649. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  14650. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  14651. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  14652. if ( p === THREE.ByteType ) return _gl.BYTE;
  14653. if ( p === THREE.ShortType ) return _gl.SHORT;
  14654. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  14655. if ( p === THREE.IntType ) return _gl.INT;
  14656. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  14657. if ( p === THREE.FloatType ) return _gl.FLOAT;
  14658. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  14659. if ( p === THREE.RGBFormat ) return _gl.RGB;
  14660. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  14661. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  14662. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  14663. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  14664. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  14665. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  14666. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  14667. if ( p === THREE.OneFactor ) return _gl.ONE;
  14668. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  14669. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  14670. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  14671. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  14672. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  14673. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  14674. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  14675. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  14676. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  14677. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  14678. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14679. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14680. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14681. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14682. }
  14683. return 0;
  14684. };
  14685. // Allocations
  14686. function allocateBones ( object ) {
  14687. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  14688. return 1024;
  14689. } else {
  14690. // default for when object is not specified
  14691. // ( for example when prebuilding shader
  14692. // to be used with multiple objects )
  14693. //
  14694. // - leave some extra space for other uniforms
  14695. // - limit here is ANGLE's 254 max uniform vectors
  14696. // (up to 54 should be safe)
  14697. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  14698. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14699. var maxBones = nVertexMatrices;
  14700. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  14701. maxBones = Math.min( object.bones.length, maxBones );
  14702. if ( maxBones < object.bones.length ) {
  14703. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  14704. }
  14705. }
  14706. return maxBones;
  14707. }
  14708. };
  14709. function allocateLights ( lights ) {
  14710. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  14711. dirLights = pointLights = spotLights = hemiLights = 0;
  14712. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14713. light = lights[ l ];
  14714. if ( light.onlyShadow ) continue;
  14715. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  14716. if ( light instanceof THREE.PointLight ) pointLights ++;
  14717. if ( light instanceof THREE.SpotLight ) spotLights ++;
  14718. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  14719. }
  14720. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  14721. };
  14722. function allocateShadows ( lights ) {
  14723. var l, ll, light, maxShadows = 0;
  14724. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  14725. light = lights[ l ];
  14726. if ( ! light.castShadow ) continue;
  14727. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  14728. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  14729. }
  14730. return maxShadows;
  14731. };
  14732. // Initialization
  14733. function initGL () {
  14734. try {
  14735. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  14736. throw 'Error creating WebGL context.';
  14737. }
  14738. } catch ( error ) {
  14739. console.error( error );
  14740. }
  14741. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  14742. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  14743. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  14744. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  14745. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  14746. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  14747. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  14748. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  14749. if ( ! _glExtensionTextureFloat ) {
  14750. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  14751. }
  14752. if ( ! _glExtensionStandardDerivatives ) {
  14753. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  14754. }
  14755. if ( ! _glExtensionTextureFilterAnisotropic ) {
  14756. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  14757. }
  14758. if ( ! _glExtensionCompressedTextureS3TC ) {
  14759. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  14760. }
  14761. };
  14762. function setDefaultGLState () {
  14763. _gl.clearColor( 0, 0, 0, 1 );
  14764. _gl.clearDepth( 1 );
  14765. _gl.clearStencil( 0 );
  14766. _gl.enable( _gl.DEPTH_TEST );
  14767. _gl.depthFunc( _gl.LEQUAL );
  14768. _gl.frontFace( _gl.CCW );
  14769. _gl.cullFace( _gl.BACK );
  14770. _gl.enable( _gl.CULL_FACE );
  14771. _gl.enable( _gl.BLEND );
  14772. _gl.blendEquation( _gl.FUNC_ADD );
  14773. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  14774. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14775. };
  14776. // default plugins (order is important)
  14777. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  14778. this.addPrePlugin( this.shadowMapPlugin );
  14779. this.addPostPlugin( new THREE.SpritePlugin() );
  14780. this.addPostPlugin( new THREE.LensFlarePlugin() );
  14781. };
  14782. /**
  14783. * @author szimek / https://github.com/szimek/
  14784. * @author alteredq / http://alteredqualia.com/
  14785. */
  14786. THREE.WebGLRenderTarget = function ( width, height, options ) {
  14787. THREE.EventDispatcher.call( this );
  14788. this.width = width;
  14789. this.height = height;
  14790. options = options || {};
  14791. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  14792. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  14793. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  14794. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  14795. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  14796. this.offset = new THREE.Vector2( 0, 0 );
  14797. this.repeat = new THREE.Vector2( 1, 1 );
  14798. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  14799. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  14800. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  14801. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  14802. this.generateMipmaps = true;
  14803. this.shareDepthFrom = null;
  14804. };
  14805. THREE.WebGLRenderTarget.prototype.clone = function() {
  14806. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  14807. tmp.wrapS = this.wrapS;
  14808. tmp.wrapT = this.wrapT;
  14809. tmp.magFilter = this.magFilter;
  14810. tmp.minFilter = this.minFilter;
  14811. tmp.anisotropy = this.anisotropy;
  14812. tmp.offset.copy( this.offset );
  14813. tmp.repeat.copy( this.repeat );
  14814. tmp.format = this.format;
  14815. tmp.type = this.type;
  14816. tmp.depthBuffer = this.depthBuffer;
  14817. tmp.stencilBuffer = this.stencilBuffer;
  14818. tmp.generateMipmaps = this.generateMipmaps;
  14819. tmp.shareDepthFrom = this.shareDepthFrom;
  14820. return tmp;
  14821. };
  14822. THREE.WebGLRenderTarget.prototype.dispose = function () {
  14823. this.dispatchEvent( { type: 'dispose' } );
  14824. };
  14825. /**
  14826. * @author alteredq / http://alteredqualia.com
  14827. */
  14828. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  14829. THREE.WebGLRenderTarget.call( this, width, height, options );
  14830. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  14831. };
  14832. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  14833. /**
  14834. * @author mrdoob / http://mrdoob.com/
  14835. */
  14836. THREE.RenderableVertex = function () {
  14837. this.positionWorld = new THREE.Vector3();
  14838. this.positionScreen = new THREE.Vector4();
  14839. this.visible = true;
  14840. };
  14841. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  14842. this.positionWorld.copy( vertex.positionWorld );
  14843. this.positionScreen.copy( vertex.positionScreen );
  14844. };
  14845. /**
  14846. * @author mrdoob / http://mrdoob.com/
  14847. */
  14848. THREE.RenderableFace3 = function () {
  14849. this.v1 = new THREE.RenderableVertex();
  14850. this.v2 = new THREE.RenderableVertex();
  14851. this.v3 = new THREE.RenderableVertex();
  14852. this.centroidModel = new THREE.Vector3();
  14853. this.normalModel = new THREE.Vector3();
  14854. this.normalModelView = new THREE.Vector3();
  14855. this.vertexNormalsLength = 0;
  14856. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14857. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14858. this.color = null;
  14859. this.material = null;
  14860. this.uvs = [[]];
  14861. this.z = null;
  14862. };
  14863. /**
  14864. * @author mrdoob / http://mrdoob.com/
  14865. */
  14866. THREE.RenderableFace4 = function () {
  14867. this.v1 = new THREE.RenderableVertex();
  14868. this.v2 = new THREE.RenderableVertex();
  14869. this.v3 = new THREE.RenderableVertex();
  14870. this.v4 = new THREE.RenderableVertex();
  14871. this.centroidModel = new THREE.Vector3();
  14872. this.normalModel = new THREE.Vector3();
  14873. this.normalModelView = new THREE.Vector3();
  14874. this.vertexNormalsLength = 0;
  14875. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14876. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14877. this.color = null;
  14878. this.material = null;
  14879. this.uvs = [[]];
  14880. this.z = null;
  14881. };
  14882. /**
  14883. * @author mrdoob / http://mrdoob.com/
  14884. */
  14885. THREE.RenderableObject = function () {
  14886. this.object = null;
  14887. this.z = null;
  14888. };
  14889. /**
  14890. * @author mrdoob / http://mrdoob.com/
  14891. */
  14892. THREE.RenderableParticle = function () {
  14893. this.object = null;
  14894. this.x = null;
  14895. this.y = null;
  14896. this.z = null;
  14897. this.rotation = null;
  14898. this.scale = new THREE.Vector2();
  14899. this.material = null;
  14900. };
  14901. /**
  14902. * @author mrdoob / http://mrdoob.com/
  14903. */
  14904. THREE.RenderableLine = function () {
  14905. this.z = null;
  14906. this.v1 = new THREE.RenderableVertex();
  14907. this.v2 = new THREE.RenderableVertex();
  14908. this.material = null;
  14909. };
  14910. /**
  14911. * @author alteredq / http://alteredqualia.com/
  14912. */
  14913. THREE.ColorUtils = {
  14914. adjustHSV : function ( color, h, s, v ) {
  14915. var hsv = THREE.ColorUtils.__hsv;
  14916. color.getHSV( hsv );
  14917. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  14918. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  14919. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  14920. color.setHSV( hsv.h, hsv.s, hsv.v );
  14921. }
  14922. };
  14923. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  14924. * @author mrdoob / http://mrdoob.com/
  14925. * @author alteredq / http://alteredqualia.com/
  14926. */
  14927. THREE.GeometryUtils = {
  14928. // Merge two geometries or geometry and geometry from object (using object's transform)
  14929. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  14930. var matrix, normalMatrix,
  14931. vertexOffset = geometry1.vertices.length,
  14932. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  14933. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  14934. vertices1 = geometry1.vertices,
  14935. vertices2 = geometry2.vertices,
  14936. faces1 = geometry1.faces,
  14937. faces2 = geometry2.faces,
  14938. uvs1 = geometry1.faceVertexUvs[ 0 ],
  14939. uvs2 = geometry2.faceVertexUvs[ 0 ];
  14940. if ( object2 instanceof THREE.Mesh ) {
  14941. object2.matrixAutoUpdate && object2.updateMatrix();
  14942. matrix = object2.matrix;
  14943. normalMatrix = new THREE.Matrix3();
  14944. normalMatrix.getInverse( matrix );
  14945. normalMatrix.transpose();
  14946. }
  14947. // vertices
  14948. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  14949. var vertex = vertices2[ i ];
  14950. var vertexCopy = vertex.clone();
  14951. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  14952. vertices1.push( vertexCopy );
  14953. }
  14954. // faces
  14955. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  14956. var face = faces2[ i ], faceCopy, normal, color,
  14957. faceVertexNormals = face.vertexNormals,
  14958. faceVertexColors = face.vertexColors;
  14959. if ( face instanceof THREE.Face3 ) {
  14960. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  14961. } else if ( face instanceof THREE.Face4 ) {
  14962. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  14963. }
  14964. faceCopy.normal.copy( face.normal );
  14965. if ( normalMatrix ) {
  14966. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  14967. }
  14968. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  14969. normal = faceVertexNormals[ j ].clone();
  14970. if ( normalMatrix ) {
  14971. normal.applyMatrix3( normalMatrix ).normalize();
  14972. }
  14973. faceCopy.vertexNormals.push( normal );
  14974. }
  14975. faceCopy.color.copy( face.color );
  14976. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  14977. color = faceVertexColors[ j ];
  14978. faceCopy.vertexColors.push( color.clone() );
  14979. }
  14980. faceCopy.materialIndex = face.materialIndex;
  14981. faceCopy.centroid.copy( face.centroid );
  14982. if ( matrix ) {
  14983. faceCopy.centroid.applyMatrix4( matrix );
  14984. }
  14985. faces1.push( faceCopy );
  14986. }
  14987. // uvs
  14988. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  14989. var uv = uvs2[ i ], uvCopy = [];
  14990. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  14991. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  14992. }
  14993. uvs1.push( uvCopy );
  14994. }
  14995. },
  14996. removeMaterials: function ( geometry, materialIndexArray ) {
  14997. var materialIndexMap = {};
  14998. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  14999. materialIndexMap[ materialIndexArray[i] ] = true;
  15000. }
  15001. var face, newFaces = [];
  15002. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15003. face = geometry.faces[ i ];
  15004. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15005. }
  15006. geometry.faces = newFaces;
  15007. },
  15008. // Get random point in triangle (via barycentric coordinates)
  15009. // (uniform distribution)
  15010. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15011. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  15012. var a, b, c,
  15013. point = new THREE.Vector3(),
  15014. tmp = THREE.GeometryUtils.__v1;
  15015. a = THREE.GeometryUtils.random();
  15016. b = THREE.GeometryUtils.random();
  15017. if ( ( a + b ) > 1 ) {
  15018. a = 1 - a;
  15019. b = 1 - b;
  15020. }
  15021. c = 1 - a - b;
  15022. point.copy( vectorA );
  15023. point.multiplyScalar( a );
  15024. tmp.copy( vectorB );
  15025. tmp.multiplyScalar( b );
  15026. point.addSelf( tmp );
  15027. tmp.copy( vectorC );
  15028. tmp.multiplyScalar( c );
  15029. point.addSelf( tmp );
  15030. return point;
  15031. },
  15032. // Get random point in face (triangle / quad)
  15033. // (uniform distribution)
  15034. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15035. var vA, vB, vC, vD;
  15036. if ( face instanceof THREE.Face3 ) {
  15037. vA = geometry.vertices[ face.a ];
  15038. vB = geometry.vertices[ face.b ];
  15039. vC = geometry.vertices[ face.c ];
  15040. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15041. } else if ( face instanceof THREE.Face4 ) {
  15042. vA = geometry.vertices[ face.a ];
  15043. vB = geometry.vertices[ face.b ];
  15044. vC = geometry.vertices[ face.c ];
  15045. vD = geometry.vertices[ face.d ];
  15046. var area1, area2;
  15047. if ( useCachedAreas ) {
  15048. if ( face._area1 && face._area2 ) {
  15049. area1 = face._area1;
  15050. area2 = face._area2;
  15051. } else {
  15052. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15053. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15054. face._area1 = area1;
  15055. face._area2 = area2;
  15056. }
  15057. } else {
  15058. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  15059. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15060. }
  15061. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  15062. if ( r < area1 ) {
  15063. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  15064. } else {
  15065. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  15066. }
  15067. }
  15068. },
  15069. // Get uniformly distributed random points in mesh
  15070. // - create array with cumulative sums of face areas
  15071. // - pick random number from 0 to total area
  15072. // - find corresponding place in area array by binary search
  15073. // - get random point in face
  15074. randomPointsInGeometry: function ( geometry, n ) {
  15075. var face, i,
  15076. faces = geometry.faces,
  15077. vertices = geometry.vertices,
  15078. il = faces.length,
  15079. totalArea = 0,
  15080. cumulativeAreas = [],
  15081. vA, vB, vC, vD;
  15082. // precompute face areas
  15083. for ( i = 0; i < il; i ++ ) {
  15084. face = faces[ i ];
  15085. if ( face instanceof THREE.Face3 ) {
  15086. vA = vertices[ face.a ];
  15087. vB = vertices[ face.b ];
  15088. vC = vertices[ face.c ];
  15089. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15090. } else if ( face instanceof THREE.Face4 ) {
  15091. vA = vertices[ face.a ];
  15092. vB = vertices[ face.b ];
  15093. vC = vertices[ face.c ];
  15094. vD = vertices[ face.d ];
  15095. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15096. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15097. face._area = face._area1 + face._area2;
  15098. }
  15099. totalArea += face._area;
  15100. cumulativeAreas[ i ] = totalArea;
  15101. }
  15102. // binary search cumulative areas array
  15103. function binarySearchIndices( value ) {
  15104. function binarySearch( start, end ) {
  15105. // return closest larger index
  15106. // if exact number is not found
  15107. if ( end < start )
  15108. return start;
  15109. var mid = start + Math.floor( ( end - start ) / 2 );
  15110. if ( cumulativeAreas[ mid ] > value ) {
  15111. return binarySearch( start, mid - 1 );
  15112. } else if ( cumulativeAreas[ mid ] < value ) {
  15113. return binarySearch( mid + 1, end );
  15114. } else {
  15115. return mid;
  15116. }
  15117. }
  15118. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15119. return result;
  15120. }
  15121. // pick random face weighted by face area
  15122. var r, index,
  15123. result = [];
  15124. var stats = {};
  15125. for ( i = 0; i < n; i ++ ) {
  15126. r = THREE.GeometryUtils.random() * totalArea;
  15127. index = binarySearchIndices( r );
  15128. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15129. if ( ! stats[ index ] ) {
  15130. stats[ index ] = 1;
  15131. } else {
  15132. stats[ index ] += 1;
  15133. }
  15134. }
  15135. return result;
  15136. },
  15137. // Get triangle area (half of parallelogram)
  15138. // http://mathworld.wolfram.com/TriangleArea.html
  15139. triangleArea: function ( vectorA, vectorB, vectorC ) {
  15140. var tmp1 = THREE.GeometryUtils.__v1,
  15141. tmp2 = THREE.GeometryUtils.__v2;
  15142. tmp1.sub( vectorB, vectorA );
  15143. tmp2.sub( vectorC, vectorA );
  15144. tmp1.crossSelf( tmp2 );
  15145. return 0.5 * tmp1.length();
  15146. },
  15147. // Center geometry so that 0,0,0 is in center of bounding box
  15148. center: function ( geometry ) {
  15149. geometry.computeBoundingBox();
  15150. var bb = geometry.boundingBox;
  15151. var offset = new THREE.Vector3();
  15152. offset.add( bb.min, bb.max );
  15153. offset.multiplyScalar( -0.5 );
  15154. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset ) );
  15155. geometry.computeBoundingBox();
  15156. return offset;
  15157. },
  15158. // Normalize UVs to be from <0,1>
  15159. // (for now just the first set of UVs)
  15160. normalizeUVs: function ( geometry ) {
  15161. var uvSet = geometry.faceVertexUvs[ 0 ];
  15162. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  15163. var uvs = uvSet[ i ];
  15164. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  15165. // texture repeat
  15166. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  15167. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  15168. }
  15169. }
  15170. },
  15171. triangulateQuads: function ( geometry ) {
  15172. var i, il, j, jl;
  15173. var faces = [];
  15174. var faceUvs = [];
  15175. var faceVertexUvs = [];
  15176. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  15177. faceUvs[ i ] = [];
  15178. }
  15179. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15180. faceVertexUvs[ i ] = [];
  15181. }
  15182. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15183. var face = geometry.faces[ i ];
  15184. if ( face instanceof THREE.Face4 ) {
  15185. var a = face.a;
  15186. var b = face.b;
  15187. var c = face.c;
  15188. var d = face.d;
  15189. var triA = new THREE.Face3();
  15190. var triB = new THREE.Face3();
  15191. triA.color.copy( face.color );
  15192. triB.color.copy( face.color );
  15193. triA.materialIndex = face.materialIndex;
  15194. triB.materialIndex = face.materialIndex;
  15195. triA.a = a;
  15196. triA.b = b;
  15197. triA.c = d;
  15198. triB.a = b;
  15199. triB.b = c;
  15200. triB.c = d;
  15201. if ( face.vertexColors.length === 4 ) {
  15202. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  15203. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  15204. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15205. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  15206. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  15207. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15208. }
  15209. faces.push( triA, triB );
  15210. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15211. if ( geometry.faceVertexUvs[ j ].length ) {
  15212. var uvs = geometry.faceVertexUvs[ j ][ i ];
  15213. var uvA = uvs[ 0 ];
  15214. var uvB = uvs[ 1 ];
  15215. var uvC = uvs[ 2 ];
  15216. var uvD = uvs[ 3 ];
  15217. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  15218. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  15219. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  15220. }
  15221. }
  15222. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15223. if ( geometry.faceUvs[ j ].length ) {
  15224. var faceUv = geometry.faceUvs[ j ][ i ];
  15225. faceUvs[ j ].push( faceUv, faceUv );
  15226. }
  15227. }
  15228. } else {
  15229. faces.push( face );
  15230. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15231. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  15232. }
  15233. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15234. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15235. }
  15236. }
  15237. }
  15238. geometry.faces = faces;
  15239. geometry.faceUvs = faceUvs;
  15240. geometry.faceVertexUvs = faceVertexUvs;
  15241. geometry.computeCentroids();
  15242. geometry.computeFaceNormals();
  15243. geometry.computeVertexNormals();
  15244. if ( geometry.hasTangents ) geometry.computeTangents();
  15245. },
  15246. // Make all faces use unique vertices
  15247. // so that each face can be separated from others
  15248. explode: function( geometry ) {
  15249. var vertices = [];
  15250. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15251. var n = vertices.length;
  15252. var face = geometry.faces[ i ];
  15253. if ( face instanceof THREE.Face4 ) {
  15254. var a = face.a;
  15255. var b = face.b;
  15256. var c = face.c;
  15257. var d = face.d;
  15258. var va = geometry.vertices[ a ];
  15259. var vb = geometry.vertices[ b ];
  15260. var vc = geometry.vertices[ c ];
  15261. var vd = geometry.vertices[ d ];
  15262. vertices.push( va.clone() );
  15263. vertices.push( vb.clone() );
  15264. vertices.push( vc.clone() );
  15265. vertices.push( vd.clone() );
  15266. face.a = n;
  15267. face.b = n + 1;
  15268. face.c = n + 2;
  15269. face.d = n + 3;
  15270. } else {
  15271. var a = face.a;
  15272. var b = face.b;
  15273. var c = face.c;
  15274. var va = geometry.vertices[ a ];
  15275. var vb = geometry.vertices[ b ];
  15276. var vc = geometry.vertices[ c ];
  15277. vertices.push( va.clone() );
  15278. vertices.push( vb.clone() );
  15279. vertices.push( vc.clone() );
  15280. face.a = n;
  15281. face.b = n + 1;
  15282. face.c = n + 2;
  15283. }
  15284. }
  15285. geometry.vertices = vertices;
  15286. delete geometry.__tmpVertices;
  15287. },
  15288. // Break faces with edges longer than maxEdgeLength
  15289. // - not recursive
  15290. tessellate: function ( geometry, maxEdgeLength ) {
  15291. var i, il, face,
  15292. a, b, c, d,
  15293. va, vb, vc, vd,
  15294. dab, dbc, dac, dcd, dad,
  15295. m, m1, m2,
  15296. vm, vm1, vm2,
  15297. vnm, vnm1, vnm2,
  15298. vcm, vcm1, vcm2,
  15299. triA, triB,
  15300. quadA, quadB,
  15301. edge;
  15302. var faces = [];
  15303. var faceVertexUvs = [];
  15304. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15305. faceVertexUvs[ i ] = [];
  15306. }
  15307. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15308. face = geometry.faces[ i ];
  15309. if ( face instanceof THREE.Face3 ) {
  15310. a = face.a;
  15311. b = face.b;
  15312. c = face.c;
  15313. va = geometry.vertices[ a ];
  15314. vb = geometry.vertices[ b ];
  15315. vc = geometry.vertices[ c ];
  15316. dab = va.distanceTo( vb );
  15317. dbc = vb.distanceTo( vc );
  15318. dac = va.distanceTo( vc );
  15319. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  15320. m = geometry.vertices.length;
  15321. triA = face.clone();
  15322. triB = face.clone();
  15323. if ( dab >= dbc && dab >= dac ) {
  15324. vm = va.clone();
  15325. vm.lerpSelf( vb, 0.5 );
  15326. triA.a = a;
  15327. triA.b = m;
  15328. triA.c = c;
  15329. triB.a = m;
  15330. triB.b = b;
  15331. triB.c = c;
  15332. if ( face.vertexNormals.length === 3 ) {
  15333. vnm = face.vertexNormals[ 0 ].clone();
  15334. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  15335. triA.vertexNormals[ 1 ].copy( vnm );
  15336. triB.vertexNormals[ 0 ].copy( vnm );
  15337. }
  15338. if ( face.vertexColors.length === 3 ) {
  15339. vcm = face.vertexColors[ 0 ].clone();
  15340. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  15341. triA.vertexColors[ 1 ].copy( vcm );
  15342. triB.vertexColors[ 0 ].copy( vcm );
  15343. }
  15344. edge = 0;
  15345. } else if ( dbc >= dab && dbc >= dac ) {
  15346. vm = vb.clone();
  15347. vm.lerpSelf( vc, 0.5 );
  15348. triA.a = a;
  15349. triA.b = b;
  15350. triA.c = m;
  15351. triB.a = m;
  15352. triB.b = c;
  15353. triB.c = a;
  15354. if ( face.vertexNormals.length === 3 ) {
  15355. vnm = face.vertexNormals[ 1 ].clone();
  15356. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  15357. triA.vertexNormals[ 2 ].copy( vnm );
  15358. triB.vertexNormals[ 0 ].copy( vnm );
  15359. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  15360. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  15361. }
  15362. if ( face.vertexColors.length === 3 ) {
  15363. vcm = face.vertexColors[ 1 ].clone();
  15364. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  15365. triA.vertexColors[ 2 ].copy( vcm );
  15366. triB.vertexColors[ 0 ].copy( vcm );
  15367. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  15368. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  15369. }
  15370. edge = 1;
  15371. } else {
  15372. vm = va.clone();
  15373. vm.lerpSelf( vc, 0.5 );
  15374. triA.a = a;
  15375. triA.b = b;
  15376. triA.c = m;
  15377. triB.a = m;
  15378. triB.b = b;
  15379. triB.c = c;
  15380. if ( face.vertexNormals.length === 3 ) {
  15381. vnm = face.vertexNormals[ 0 ].clone();
  15382. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  15383. triA.vertexNormals[ 2 ].copy( vnm );
  15384. triB.vertexNormals[ 0 ].copy( vnm );
  15385. }
  15386. if ( face.vertexColors.length === 3 ) {
  15387. vcm = face.vertexColors[ 0 ].clone();
  15388. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  15389. triA.vertexColors[ 2 ].copy( vcm );
  15390. triB.vertexColors[ 0 ].copy( vcm );
  15391. }
  15392. edge = 2;
  15393. }
  15394. faces.push( triA, triB );
  15395. geometry.vertices.push( vm );
  15396. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  15397. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15398. if ( geometry.faceVertexUvs[ j ].length ) {
  15399. uvs = geometry.faceVertexUvs[ j ][ i ];
  15400. uvA = uvs[ 0 ];
  15401. uvB = uvs[ 1 ];
  15402. uvC = uvs[ 2 ];
  15403. // AB
  15404. if ( edge === 0 ) {
  15405. uvM = uvA.clone();
  15406. uvM.lerpSelf( uvB, 0.5 );
  15407. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  15408. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  15409. // BC
  15410. } else if ( edge === 1 ) {
  15411. uvM = uvB.clone();
  15412. uvM.lerpSelf( uvC, 0.5 );
  15413. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  15414. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  15415. // AC
  15416. } else {
  15417. uvM = uvA.clone();
  15418. uvM.lerpSelf( uvC, 0.5 );
  15419. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  15420. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  15421. }
  15422. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  15423. }
  15424. }
  15425. } else {
  15426. faces.push( face );
  15427. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15428. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15429. }
  15430. }
  15431. } else {
  15432. a = face.a;
  15433. b = face.b;
  15434. c = face.c;
  15435. d = face.d;
  15436. va = geometry.vertices[ a ];
  15437. vb = geometry.vertices[ b ];
  15438. vc = geometry.vertices[ c ];
  15439. vd = geometry.vertices[ d ];
  15440. dab = va.distanceTo( vb );
  15441. dbc = vb.distanceTo( vc );
  15442. dcd = vc.distanceTo( vd );
  15443. dad = va.distanceTo( vd );
  15444. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  15445. m1 = geometry.vertices.length;
  15446. m2 = geometry.vertices.length + 1;
  15447. quadA = face.clone();
  15448. quadB = face.clone();
  15449. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  15450. vm1 = va.clone();
  15451. vm1.lerpSelf( vb, 0.5 );
  15452. vm2 = vc.clone();
  15453. vm2.lerpSelf( vd, 0.5 );
  15454. quadA.a = a;
  15455. quadA.b = m1;
  15456. quadA.c = m2;
  15457. quadA.d = d;
  15458. quadB.a = m1;
  15459. quadB.b = b;
  15460. quadB.c = c;
  15461. quadB.d = m2;
  15462. if ( face.vertexNormals.length === 4 ) {
  15463. vnm1 = face.vertexNormals[ 0 ].clone();
  15464. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  15465. vnm2 = face.vertexNormals[ 2 ].clone();
  15466. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  15467. quadA.vertexNormals[ 1 ].copy( vnm1 );
  15468. quadA.vertexNormals[ 2 ].copy( vnm2 );
  15469. quadB.vertexNormals[ 0 ].copy( vnm1 );
  15470. quadB.vertexNormals[ 3 ].copy( vnm2 );
  15471. }
  15472. if ( face.vertexColors.length === 4 ) {
  15473. vcm1 = face.vertexColors[ 0 ].clone();
  15474. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  15475. vcm2 = face.vertexColors[ 2 ].clone();
  15476. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  15477. quadA.vertexColors[ 1 ].copy( vcm1 );
  15478. quadA.vertexColors[ 2 ].copy( vcm2 );
  15479. quadB.vertexColors[ 0 ].copy( vcm1 );
  15480. quadB.vertexColors[ 3 ].copy( vcm2 );
  15481. }
  15482. edge = 0;
  15483. } else {
  15484. vm1 = vb.clone();
  15485. vm1.lerpSelf( vc, 0.5 );
  15486. vm2 = vd.clone();
  15487. vm2.lerpSelf( va, 0.5 );
  15488. quadA.a = a;
  15489. quadA.b = b;
  15490. quadA.c = m1;
  15491. quadA.d = m2;
  15492. quadB.a = m2;
  15493. quadB.b = m1;
  15494. quadB.c = c;
  15495. quadB.d = d;
  15496. if ( face.vertexNormals.length === 4 ) {
  15497. vnm1 = face.vertexNormals[ 1 ].clone();
  15498. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  15499. vnm2 = face.vertexNormals[ 3 ].clone();
  15500. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  15501. quadA.vertexNormals[ 2 ].copy( vnm1 );
  15502. quadA.vertexNormals[ 3 ].copy( vnm2 );
  15503. quadB.vertexNormals[ 0 ].copy( vnm2 );
  15504. quadB.vertexNormals[ 1 ].copy( vnm1 );
  15505. }
  15506. if ( face.vertexColors.length === 4 ) {
  15507. vcm1 = face.vertexColors[ 1 ].clone();
  15508. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  15509. vcm2 = face.vertexColors[ 3 ].clone();
  15510. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  15511. quadA.vertexColors[ 2 ].copy( vcm1 );
  15512. quadA.vertexColors[ 3 ].copy( vcm2 );
  15513. quadB.vertexColors[ 0 ].copy( vcm2 );
  15514. quadB.vertexColors[ 1 ].copy( vcm1 );
  15515. }
  15516. edge = 1;
  15517. }
  15518. faces.push( quadA, quadB );
  15519. geometry.vertices.push( vm1, vm2 );
  15520. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  15521. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15522. if ( geometry.faceVertexUvs[ j ].length ) {
  15523. uvs = geometry.faceVertexUvs[ j ][ i ];
  15524. uvA = uvs[ 0 ];
  15525. uvB = uvs[ 1 ];
  15526. uvC = uvs[ 2 ];
  15527. uvD = uvs[ 3 ];
  15528. // AB + CD
  15529. if ( edge === 0 ) {
  15530. uvM1 = uvA.clone();
  15531. uvM1.lerpSelf( uvB, 0.5 );
  15532. uvM2 = uvC.clone();
  15533. uvM2.lerpSelf( uvD, 0.5 );
  15534. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  15535. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  15536. // BC + AD
  15537. } else {
  15538. uvM1 = uvB.clone();
  15539. uvM1.lerpSelf( uvC, 0.5 );
  15540. uvM2 = uvD.clone();
  15541. uvM2.lerpSelf( uvA, 0.5 );
  15542. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  15543. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  15544. }
  15545. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  15546. }
  15547. }
  15548. } else {
  15549. faces.push( face );
  15550. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15551. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15552. }
  15553. }
  15554. }
  15555. }
  15556. geometry.faces = faces;
  15557. geometry.faceVertexUvs = faceVertexUvs;
  15558. },
  15559. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  15560. var faces = geometry.faces;
  15561. var start = startFace || 0;
  15562. var end = endFace || faces.length - 1;
  15563. for ( var i = start; i <= end; i ++ ) {
  15564. faces[i].materialIndex = index;
  15565. }
  15566. }
  15567. };
  15568. THREE.GeometryUtils.random = THREE.Math.random16;
  15569. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  15570. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  15571. /**
  15572. * @author alteredq / http://alteredqualia.com/
  15573. * @author mrdoob / http://mrdoob.com/
  15574. */
  15575. THREE.ImageUtils = {
  15576. crossOrigin: 'anonymous',
  15577. loadTexture: function ( url, mapping, onLoad, onError ) {
  15578. var image = new Image();
  15579. var texture = new THREE.Texture( image, mapping );
  15580. var loader = new THREE.ImageLoader();
  15581. loader.addEventListener( 'load', function ( event ) {
  15582. texture.image = event.content;
  15583. texture.needsUpdate = true;
  15584. if ( onLoad ) onLoad( texture );
  15585. } );
  15586. loader.addEventListener( 'error', function ( event ) {
  15587. if ( onError ) onError( event.message );
  15588. } );
  15589. loader.crossOrigin = this.crossOrigin;
  15590. loader.load( url, image );
  15591. texture.sourceFile = url;
  15592. return texture;
  15593. },
  15594. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15595. var texture = new THREE.CompressedTexture();
  15596. texture.mapping = mapping;
  15597. var request = new XMLHttpRequest();
  15598. request.onload = function () {
  15599. var buffer = request.response;
  15600. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15601. texture.format = dds.format;
  15602. texture.mipmaps = dds.mipmaps;
  15603. texture.image.width = dds.width;
  15604. texture.image.height = dds.height;
  15605. // gl.generateMipmap fails for compressed textures
  15606. // mipmaps must be embedded in the DDS file
  15607. // or texture filters must not use mipmapping
  15608. texture.generateMipmaps = false;
  15609. texture.needsUpdate = true;
  15610. if ( onLoad ) onLoad( texture );
  15611. }
  15612. request.onerror = onError;
  15613. request.open( 'GET', url, true );
  15614. request.responseType = "arraybuffer";
  15615. request.send( null );
  15616. return texture;
  15617. },
  15618. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15619. var images = [];
  15620. images.loadCount = 0;
  15621. var texture = new THREE.Texture();
  15622. texture.image = images;
  15623. if ( mapping !== undefined ) texture.mapping = mapping;
  15624. // no flipping needed for cube textures
  15625. texture.flipY = false;
  15626. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15627. var cubeImage = new Image();
  15628. images[ i ] = cubeImage;
  15629. cubeImage.onload = function () {
  15630. images.loadCount += 1;
  15631. if ( images.loadCount === 6 ) {
  15632. texture.needsUpdate = true;
  15633. if ( onLoad ) onLoad( texture );
  15634. }
  15635. };
  15636. cubeImage.onerror = onError;
  15637. cubeImage.crossOrigin = this.crossOrigin;
  15638. cubeImage.src = array[ i ];
  15639. }
  15640. return texture;
  15641. },
  15642. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15643. var images = [];
  15644. images.loadCount = 0;
  15645. var texture = new THREE.CompressedTexture();
  15646. texture.image = images;
  15647. if ( mapping !== undefined ) texture.mapping = mapping;
  15648. // no flipping for cube textures
  15649. // (also flipping doesn't work for compressed textures )
  15650. texture.flipY = false;
  15651. // can't generate mipmaps for compressed textures
  15652. // mips must be embedded in DDS files
  15653. texture.generateMipmaps = false;
  15654. var generateCubeFaceCallback = function ( rq, img ) {
  15655. return function () {
  15656. var buffer = rq.response;
  15657. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15658. img.format = dds.format;
  15659. img.mipmaps = dds.mipmaps;
  15660. img.width = dds.width;
  15661. img.height = dds.height;
  15662. images.loadCount += 1;
  15663. if ( images.loadCount === 6 ) {
  15664. texture.format = dds.format;
  15665. texture.needsUpdate = true;
  15666. if ( onLoad ) onLoad( texture );
  15667. }
  15668. }
  15669. }
  15670. // compressed cubemap textures as 6 separate DDS files
  15671. if ( array instanceof Array ) {
  15672. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15673. var cubeImage = {};
  15674. images[ i ] = cubeImage;
  15675. var request = new XMLHttpRequest();
  15676. request.onload = generateCubeFaceCallback( request, cubeImage );
  15677. request.onerror = onError;
  15678. var url = array[ i ];
  15679. request.open( 'GET', url, true );
  15680. request.responseType = "arraybuffer";
  15681. request.send( null );
  15682. }
  15683. // compressed cubemap texture stored in a single DDS file
  15684. } else {
  15685. var url = array;
  15686. var request = new XMLHttpRequest();
  15687. request.onload = function( ) {
  15688. var buffer = request.response;
  15689. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15690. if ( dds.isCubemap ) {
  15691. var faces = dds.mipmaps.length / dds.mipmapCount;
  15692. for ( var f = 0; f < faces; f ++ ) {
  15693. images[ f ] = { mipmaps : [] };
  15694. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15695. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15696. images[ f ].format = dds.format;
  15697. images[ f ].width = dds.width;
  15698. images[ f ].height = dds.height;
  15699. }
  15700. }
  15701. texture.format = dds.format;
  15702. texture.needsUpdate = true;
  15703. if ( onLoad ) onLoad( texture );
  15704. }
  15705. }
  15706. request.onerror = onError;
  15707. request.open( 'GET', url, true );
  15708. request.responseType = "arraybuffer";
  15709. request.send( null );
  15710. }
  15711. return texture;
  15712. },
  15713. parseDDS: function ( buffer, loadMipmaps ) {
  15714. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15715. // Adapted from @toji's DDS utils
  15716. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15717. // All values and structures referenced from:
  15718. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15719. var DDS_MAGIC = 0x20534444;
  15720. var DDSD_CAPS = 0x1,
  15721. DDSD_HEIGHT = 0x2,
  15722. DDSD_WIDTH = 0x4,
  15723. DDSD_PITCH = 0x8,
  15724. DDSD_PIXELFORMAT = 0x1000,
  15725. DDSD_MIPMAPCOUNT = 0x20000,
  15726. DDSD_LINEARSIZE = 0x80000,
  15727. DDSD_DEPTH = 0x800000;
  15728. var DDSCAPS_COMPLEX = 0x8,
  15729. DDSCAPS_MIPMAP = 0x400000,
  15730. DDSCAPS_TEXTURE = 0x1000;
  15731. var DDSCAPS2_CUBEMAP = 0x200,
  15732. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15733. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15734. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15735. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15736. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15737. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15738. DDSCAPS2_VOLUME = 0x200000;
  15739. var DDPF_ALPHAPIXELS = 0x1,
  15740. DDPF_ALPHA = 0x2,
  15741. DDPF_FOURCC = 0x4,
  15742. DDPF_RGB = 0x40,
  15743. DDPF_YUV = 0x200,
  15744. DDPF_LUMINANCE = 0x20000;
  15745. function fourCCToInt32( value ) {
  15746. return value.charCodeAt(0) +
  15747. (value.charCodeAt(1) << 8) +
  15748. (value.charCodeAt(2) << 16) +
  15749. (value.charCodeAt(3) << 24);
  15750. }
  15751. function int32ToFourCC( value ) {
  15752. return String.fromCharCode(
  15753. value & 0xff,
  15754. (value >> 8) & 0xff,
  15755. (value >> 16) & 0xff,
  15756. (value >> 24) & 0xff
  15757. );
  15758. }
  15759. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15760. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15761. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15762. var headerLengthInt = 31; // The header length in 32 bit ints
  15763. // Offsets into the header array
  15764. var off_magic = 0;
  15765. var off_size = 1;
  15766. var off_flags = 2;
  15767. var off_height = 3;
  15768. var off_width = 4;
  15769. var off_mipmapCount = 7;
  15770. var off_pfFlags = 20;
  15771. var off_pfFourCC = 21;
  15772. var off_caps = 27;
  15773. var off_caps2 = 28;
  15774. var off_caps3 = 29;
  15775. var off_caps4 = 30;
  15776. // Parse header
  15777. var header = new Int32Array( buffer, 0, headerLengthInt );
  15778. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15779. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15780. return dds;
  15781. }
  15782. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15783. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15784. return dds;
  15785. }
  15786. var blockBytes;
  15787. var fourCC = header[ off_pfFourCC ];
  15788. switch ( fourCC ) {
  15789. case FOURCC_DXT1:
  15790. blockBytes = 8;
  15791. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15792. break;
  15793. case FOURCC_DXT3:
  15794. blockBytes = 16;
  15795. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15796. break;
  15797. case FOURCC_DXT5:
  15798. blockBytes = 16;
  15799. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15800. break;
  15801. default:
  15802. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15803. return dds;
  15804. }
  15805. dds.mipmapCount = 1;
  15806. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15807. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15808. }
  15809. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15810. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15811. dds.width = header[ off_width ];
  15812. dds.height = header[ off_height ];
  15813. var dataOffset = header[ off_size ] + 4;
  15814. // Extract mipmaps buffers
  15815. var width = dds.width;
  15816. var height = dds.height;
  15817. var faces = dds.isCubemap ? 6 : 1;
  15818. for ( var face = 0; face < faces; face ++ ) {
  15819. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15820. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  15821. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  15822. var mipmap = { "data": byteArray, "width": width, "height": height };
  15823. dds.mipmaps.push( mipmap );
  15824. dataOffset += dataLength;
  15825. width = Math.max( width * 0.5, 1 );
  15826. height = Math.max( height * 0.5, 1 );
  15827. }
  15828. width = dds.width;
  15829. height = dds.height;
  15830. }
  15831. return dds;
  15832. },
  15833. getNormalMap: function ( image, depth ) {
  15834. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15835. var cross = function ( a, b ) {
  15836. 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 ] ];
  15837. }
  15838. var subtract = function ( a, b ) {
  15839. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15840. }
  15841. var normalize = function ( a ) {
  15842. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15843. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15844. }
  15845. depth = depth | 1;
  15846. var width = image.width;
  15847. var height = image.height;
  15848. var canvas = document.createElement( 'canvas' );
  15849. canvas.width = width;
  15850. canvas.height = height;
  15851. var context = canvas.getContext( '2d' );
  15852. context.drawImage( image, 0, 0 );
  15853. var data = context.getImageData( 0, 0, width, height ).data;
  15854. var imageData = context.createImageData( width, height );
  15855. var output = imageData.data;
  15856. for ( var x = 0; x < width; x ++ ) {
  15857. for ( var y = 0; y < height; y ++ ) {
  15858. var ly = y - 1 < 0 ? 0 : y - 1;
  15859. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15860. var lx = x - 1 < 0 ? 0 : x - 1;
  15861. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15862. var points = [];
  15863. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15864. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15865. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15866. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15867. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15868. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15869. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15870. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15871. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15872. var normals = [];
  15873. var num_points = points.length;
  15874. for ( var i = 0; i < num_points; i ++ ) {
  15875. var v1 = points[ i ];
  15876. var v2 = points[ ( i + 1 ) % num_points ];
  15877. v1 = subtract( v1, origin );
  15878. v2 = subtract( v2, origin );
  15879. normals.push( normalize( cross( v1, v2 ) ) );
  15880. }
  15881. var normal = [ 0, 0, 0 ];
  15882. for ( var i = 0; i < normals.length; i ++ ) {
  15883. normal[ 0 ] += normals[ i ][ 0 ];
  15884. normal[ 1 ] += normals[ i ][ 1 ];
  15885. normal[ 2 ] += normals[ i ][ 2 ];
  15886. }
  15887. normal[ 0 ] /= normals.length;
  15888. normal[ 1 ] /= normals.length;
  15889. normal[ 2 ] /= normals.length;
  15890. var idx = ( y * width + x ) * 4;
  15891. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15892. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15893. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15894. output[ idx + 3 ] = 255;
  15895. }
  15896. }
  15897. context.putImageData( imageData, 0, 0 );
  15898. return canvas;
  15899. },
  15900. generateDataTexture: function ( width, height, color ) {
  15901. var size = width * height;
  15902. var data = new Uint8Array( 3 * size );
  15903. var r = Math.floor( color.r * 255 );
  15904. var g = Math.floor( color.g * 255 );
  15905. var b = Math.floor( color.b * 255 );
  15906. for ( var i = 0; i < size; i ++ ) {
  15907. data[ i * 3 ] = r;
  15908. data[ i * 3 + 1 ] = g;
  15909. data[ i * 3 + 2 ] = b;
  15910. }
  15911. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15912. texture.needsUpdate = true;
  15913. return texture;
  15914. }
  15915. };
  15916. /**
  15917. * @author alteredq / http://alteredqualia.com/
  15918. */
  15919. THREE.SceneUtils = {
  15920. createMultiMaterialObject: function ( geometry, materials ) {
  15921. var group = new THREE.Object3D();
  15922. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15923. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15924. }
  15925. return group;
  15926. },
  15927. detach : function ( child, parent, scene ) {
  15928. child.applyMatrix( parent.matrixWorld );
  15929. parent.remove( child );
  15930. scene.add( child );
  15931. },
  15932. attach: function ( child, scene, parent ) {
  15933. var matrixWorldInverse = new THREE.Matrix4();
  15934. matrixWorldInverse.getInverse( parent.matrixWorld );
  15935. child.applyMatrix( matrixWorldInverse );
  15936. scene.remove( child );
  15937. parent.add( child );
  15938. }
  15939. };
  15940. /**
  15941. * @author alteredq / http://alteredqualia.com/
  15942. * @author mrdoob / http://mrdoob.com/
  15943. *
  15944. * ShaderUtils currently contains:
  15945. *
  15946. * fresnel
  15947. * normal
  15948. * cube
  15949. *
  15950. */
  15951. THREE.ShaderUtils = {
  15952. lib: {
  15953. /* -------------------------------------------------------------------------
  15954. // Fresnel shader
  15955. // - based on Nvidia Cg tutorial
  15956. ------------------------------------------------------------------------- */
  15957. 'fresnel': {
  15958. uniforms: {
  15959. "mRefractionRatio": { type: "f", value: 1.02 },
  15960. "mFresnelBias": { type: "f", value: 0.1 },
  15961. "mFresnelPower": { type: "f", value: 2.0 },
  15962. "mFresnelScale": { type: "f", value: 1.0 },
  15963. "tCube": { type: "t", value: null }
  15964. },
  15965. fragmentShader: [
  15966. "uniform samplerCube tCube;",
  15967. "varying vec3 vReflect;",
  15968. "varying vec3 vRefract[3];",
  15969. "varying float vReflectionFactor;",
  15970. "void main() {",
  15971. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15972. "vec4 refractedColor = vec4( 1.0 );",
  15973. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  15974. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  15975. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  15976. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  15977. "}"
  15978. ].join("\n"),
  15979. vertexShader: [
  15980. "uniform float mRefractionRatio;",
  15981. "uniform float mFresnelBias;",
  15982. "uniform float mFresnelScale;",
  15983. "uniform float mFresnelPower;",
  15984. "varying vec3 vReflect;",
  15985. "varying vec3 vRefract[3];",
  15986. "varying float vReflectionFactor;",
  15987. "void main() {",
  15988. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  15989. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15990. "vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  15991. "vec3 I = worldPosition.xyz - cameraPosition;",
  15992. "vReflect = reflect( I, worldNormal );",
  15993. "vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );",
  15994. "vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );",
  15995. "vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );",
  15996. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );",
  15997. "gl_Position = projectionMatrix * mvPosition;",
  15998. "}"
  15999. ].join("\n")
  16000. },
  16001. /* -------------------------------------------------------------------------
  16002. // Normal map shader
  16003. // - Blinn-Phong
  16004. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  16005. // - point and directional lights (use with "lights: true" material option)
  16006. ------------------------------------------------------------------------- */
  16007. 'normal' : {
  16008. uniforms: THREE.UniformsUtils.merge( [
  16009. THREE.UniformsLib[ "fog" ],
  16010. THREE.UniformsLib[ "lights" ],
  16011. THREE.UniformsLib[ "shadowmap" ],
  16012. {
  16013. "enableAO" : { type: "i", value: 0 },
  16014. "enableDiffuse" : { type: "i", value: 0 },
  16015. "enableSpecular" : { type: "i", value: 0 },
  16016. "enableReflection": { type: "i", value: 0 },
  16017. "enableDisplacement": { type: "i", value: 0 },
  16018. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  16019. "tDiffuse" : { type: "t", value: null },
  16020. "tCube" : { type: "t", value: null },
  16021. "tNormal" : { type: "t", value: null },
  16022. "tSpecular" : { type: "t", value: null },
  16023. "tAO" : { type: "t", value: null },
  16024. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  16025. "uDisplacementBias": { type: "f", value: 0.0 },
  16026. "uDisplacementScale": { type: "f", value: 1.0 },
  16027. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  16028. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  16029. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  16030. "uShininess": { type: "f", value: 30 },
  16031. "uOpacity": { type: "f", value: 1 },
  16032. "useRefract": { type: "i", value: 0 },
  16033. "uRefractionRatio": { type: "f", value: 0.98 },
  16034. "uReflectivity": { type: "f", value: 0.5 },
  16035. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  16036. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  16037. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  16038. }
  16039. ] ),
  16040. fragmentShader: [
  16041. "uniform vec3 uAmbientColor;",
  16042. "uniform vec3 uDiffuseColor;",
  16043. "uniform vec3 uSpecularColor;",
  16044. "uniform float uShininess;",
  16045. "uniform float uOpacity;",
  16046. "uniform bool enableDiffuse;",
  16047. "uniform bool enableSpecular;",
  16048. "uniform bool enableAO;",
  16049. "uniform bool enableReflection;",
  16050. "uniform sampler2D tDiffuse;",
  16051. "uniform sampler2D tNormal;",
  16052. "uniform sampler2D tSpecular;",
  16053. "uniform sampler2D tAO;",
  16054. "uniform samplerCube tCube;",
  16055. "uniform vec2 uNormalScale;",
  16056. "uniform bool useRefract;",
  16057. "uniform float uRefractionRatio;",
  16058. "uniform float uReflectivity;",
  16059. "varying vec3 vTangent;",
  16060. "varying vec3 vBinormal;",
  16061. "varying vec3 vNormal;",
  16062. "varying vec2 vUv;",
  16063. "uniform vec3 ambientLightColor;",
  16064. "#if MAX_DIR_LIGHTS > 0",
  16065. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  16066. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  16067. "#endif",
  16068. "#if MAX_HEMI_LIGHTS > 0",
  16069. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  16070. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  16071. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  16072. "#endif",
  16073. "#if MAX_POINT_LIGHTS > 0",
  16074. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  16075. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  16076. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  16077. "#endif",
  16078. "#if MAX_SPOT_LIGHTS > 0",
  16079. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  16080. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  16081. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  16082. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  16083. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  16084. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  16085. "#endif",
  16086. "#ifdef WRAP_AROUND",
  16087. "uniform vec3 wrapRGB;",
  16088. "#endif",
  16089. "varying vec3 vWorldPosition;",
  16090. "varying vec3 vViewPosition;",
  16091. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  16092. THREE.ShaderChunk[ "fog_pars_fragment" ],
  16093. "void main() {",
  16094. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  16095. "vec3 specularTex = vec3( 1.0 );",
  16096. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  16097. "normalTex.xy *= uNormalScale;",
  16098. "normalTex = normalize( normalTex );",
  16099. "if( enableDiffuse ) {",
  16100. "#ifdef GAMMA_INPUT",
  16101. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  16102. "texelColor.xyz *= texelColor.xyz;",
  16103. "gl_FragColor = gl_FragColor * texelColor;",
  16104. "#else",
  16105. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  16106. "#endif",
  16107. "}",
  16108. "if( enableAO ) {",
  16109. "#ifdef GAMMA_INPUT",
  16110. "vec4 aoColor = texture2D( tAO, vUv );",
  16111. "aoColor.xyz *= aoColor.xyz;",
  16112. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  16113. "#else",
  16114. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  16115. "#endif",
  16116. "}",
  16117. "if( enableSpecular )",
  16118. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  16119. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  16120. "vec3 finalNormal = tsb * normalTex;",
  16121. "#ifdef FLIP_SIDED",
  16122. "finalNormal = -finalNormal;",
  16123. "#endif",
  16124. "vec3 normal = normalize( finalNormal );",
  16125. "vec3 viewPosition = normalize( vViewPosition );",
  16126. // point lights
  16127. "#if MAX_POINT_LIGHTS > 0",
  16128. "vec3 pointDiffuse = vec3( 0.0 );",
  16129. "vec3 pointSpecular = vec3( 0.0 );",
  16130. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  16131. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  16132. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  16133. "float pointDistance = 1.0;",
  16134. "if ( pointLightDistance[ i ] > 0.0 )",
  16135. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  16136. "pointVector = normalize( pointVector );",
  16137. // diffuse
  16138. "#ifdef WRAP_AROUND",
  16139. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  16140. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  16141. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  16142. "#else",
  16143. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  16144. "#endif",
  16145. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  16146. // specular
  16147. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  16148. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  16149. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  16150. "#ifdef PHYSICALLY_BASED_SHADING",
  16151. // 2.0 => 2.0001 is hack to work around ANGLE bug
  16152. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  16153. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  16154. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  16155. "#else",
  16156. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  16157. "#endif",
  16158. "}",
  16159. "#endif",
  16160. // spot lights
  16161. "#if MAX_SPOT_LIGHTS > 0",
  16162. "vec3 spotDiffuse = vec3( 0.0 );",
  16163. "vec3 spotSpecular = vec3( 0.0 );",
  16164. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  16165. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  16166. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  16167. "float spotDistance = 1.0;",
  16168. "if ( spotLightDistance[ i ] > 0.0 )",
  16169. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  16170. "spotVector = normalize( spotVector );",
  16171. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  16172. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  16173. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  16174. // diffuse
  16175. "#ifdef WRAP_AROUND",
  16176. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  16177. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  16178. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  16179. "#else",
  16180. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  16181. "#endif",
  16182. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  16183. // specular
  16184. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  16185. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  16186. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  16187. "#ifdef PHYSICALLY_BASED_SHADING",
  16188. // 2.0 => 2.0001 is hack to work around ANGLE bug
  16189. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  16190. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  16191. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  16192. "#else",
  16193. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  16194. "#endif",
  16195. "}",
  16196. "}",
  16197. "#endif",
  16198. // directional lights
  16199. "#if MAX_DIR_LIGHTS > 0",
  16200. "vec3 dirDiffuse = vec3( 0.0 );",
  16201. "vec3 dirSpecular = vec3( 0.0 );",
  16202. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  16203. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  16204. "vec3 dirVector = normalize( lDirection.xyz );",
  16205. // diffuse
  16206. "#ifdef WRAP_AROUND",
  16207. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  16208. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  16209. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  16210. "#else",
  16211. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  16212. "#endif",
  16213. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  16214. // specular
  16215. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  16216. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  16217. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  16218. "#ifdef PHYSICALLY_BASED_SHADING",
  16219. // 2.0 => 2.0001 is hack to work around ANGLE bug
  16220. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  16221. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  16222. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  16223. "#else",
  16224. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  16225. "#endif",
  16226. "}",
  16227. "#endif",
  16228. // hemisphere lights
  16229. "#if MAX_HEMI_LIGHTS > 0",
  16230. "vec3 hemiDiffuse = vec3( 0.0 );",
  16231. "vec3 hemiSpecular = vec3( 0.0 );" ,
  16232. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  16233. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  16234. "vec3 lVector = normalize( lDirection.xyz );",
  16235. // diffuse
  16236. "float dotProduct = dot( normal, lVector );",
  16237. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  16238. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  16239. "hemiDiffuse += uDiffuseColor * hemiColor;",
  16240. // specular (sky light)
  16241. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  16242. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  16243. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  16244. // specular (ground light)
  16245. "vec3 lVectorGround = -lVector;",
  16246. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  16247. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  16248. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  16249. "#ifdef PHYSICALLY_BASED_SHADING",
  16250. "float dotProductGround = dot( normal, lVectorGround );",
  16251. // 2.0 => 2.0001 is hack to work around ANGLE bug
  16252. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  16253. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  16254. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  16255. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  16256. "#else",
  16257. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  16258. "#endif",
  16259. "}",
  16260. "#endif",
  16261. // all lights contribution summation
  16262. "vec3 totalDiffuse = vec3( 0.0 );",
  16263. "vec3 totalSpecular = vec3( 0.0 );",
  16264. "#if MAX_DIR_LIGHTS > 0",
  16265. "totalDiffuse += dirDiffuse;",
  16266. "totalSpecular += dirSpecular;",
  16267. "#endif",
  16268. "#if MAX_HEMI_LIGHTS > 0",
  16269. "totalDiffuse += hemiDiffuse;",
  16270. "totalSpecular += hemiSpecular;",
  16271. "#endif",
  16272. "#if MAX_POINT_LIGHTS > 0",
  16273. "totalDiffuse += pointDiffuse;",
  16274. "totalSpecular += pointSpecular;",
  16275. "#endif",
  16276. "#if MAX_SPOT_LIGHTS > 0",
  16277. "totalDiffuse += spotDiffuse;",
  16278. "totalSpecular += spotSpecular;",
  16279. "#endif",
  16280. "#ifdef METAL",
  16281. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  16282. "#else",
  16283. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  16284. "#endif",
  16285. "if ( enableReflection ) {",
  16286. "vec3 vReflect;",
  16287. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  16288. "if ( useRefract ) {",
  16289. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  16290. "} else {",
  16291. "vReflect = reflect( cameraToVertex, normal );",
  16292. "}",
  16293. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  16294. "#ifdef GAMMA_INPUT",
  16295. "cubeColor.xyz *= cubeColor.xyz;",
  16296. "#endif",
  16297. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  16298. "}",
  16299. THREE.ShaderChunk[ "shadowmap_fragment" ],
  16300. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  16301. THREE.ShaderChunk[ "fog_fragment" ],
  16302. "}"
  16303. ].join("\n"),
  16304. vertexShader: [
  16305. "attribute vec4 tangent;",
  16306. "uniform vec2 uOffset;",
  16307. "uniform vec2 uRepeat;",
  16308. "uniform bool enableDisplacement;",
  16309. "#ifdef VERTEX_TEXTURES",
  16310. "uniform sampler2D tDisplacement;",
  16311. "uniform float uDisplacementScale;",
  16312. "uniform float uDisplacementBias;",
  16313. "#endif",
  16314. "varying vec3 vTangent;",
  16315. "varying vec3 vBinormal;",
  16316. "varying vec3 vNormal;",
  16317. "varying vec2 vUv;",
  16318. "varying vec3 vWorldPosition;",
  16319. "varying vec3 vViewPosition;",
  16320. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  16321. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  16322. "void main() {",
  16323. THREE.ShaderChunk[ "skinbase_vertex" ],
  16324. THREE.ShaderChunk[ "skinnormal_vertex" ],
  16325. // normal, tangent and binormal vectors
  16326. "#ifdef USE_SKINNING",
  16327. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  16328. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  16329. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  16330. "#else",
  16331. "vNormal = normalize( normalMatrix * normal );",
  16332. "vTangent = normalize( normalMatrix * tangent.xyz );",
  16333. "#endif",
  16334. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  16335. "vUv = uv * uRepeat + uOffset;",
  16336. // displacement mapping
  16337. "vec3 displacedPosition;",
  16338. "#ifdef VERTEX_TEXTURES",
  16339. "if ( enableDisplacement ) {",
  16340. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  16341. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  16342. "displacedPosition = position + normalize( normal ) * df;",
  16343. "} else {",
  16344. "#ifdef USE_SKINNING",
  16345. "vec4 skinVertex = vec4( position, 1.0 );",
  16346. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  16347. "skinned += boneMatY * skinVertex * skinWeight.y;",
  16348. "displacedPosition = skinned.xyz;",
  16349. "#else",
  16350. "displacedPosition = position;",
  16351. "#endif",
  16352. "}",
  16353. "#else",
  16354. "#ifdef USE_SKINNING",
  16355. "vec4 skinVertex = vec4( position, 1.0 );",
  16356. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  16357. "skinned += boneMatY * skinVertex * skinWeight.y;",
  16358. "displacedPosition = skinned.xyz;",
  16359. "#else",
  16360. "displacedPosition = position;",
  16361. "#endif",
  16362. "#endif",
  16363. //
  16364. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  16365. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  16366. "gl_Position = projectionMatrix * mvPosition;",
  16367. //
  16368. "vWorldPosition = worldPosition.xyz;",
  16369. "vViewPosition = -mvPosition.xyz;",
  16370. // shadows
  16371. "#ifdef USE_SHADOWMAP",
  16372. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  16373. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  16374. "}",
  16375. "#endif",
  16376. "}"
  16377. ].join("\n")
  16378. },
  16379. /* -------------------------------------------------------------------------
  16380. // Cube map shader
  16381. ------------------------------------------------------------------------- */
  16382. 'cube': {
  16383. uniforms: { "tCube": { type: "t", value: null },
  16384. "tFlip": { type: "f", value: -1 } },
  16385. vertexShader: [
  16386. "varying vec3 vWorldPosition;",
  16387. "void main() {",
  16388. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  16389. "vWorldPosition = worldPosition.xyz;",
  16390. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  16391. "}"
  16392. ].join("\n"),
  16393. fragmentShader: [
  16394. "uniform samplerCube tCube;",
  16395. "uniform float tFlip;",
  16396. "varying vec3 vWorldPosition;",
  16397. "void main() {",
  16398. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  16399. "}"
  16400. ].join("\n")
  16401. }
  16402. }
  16403. };
  16404. /**
  16405. * @author zz85 / http://www.lab4games.net/zz85/blog
  16406. * @author alteredq / http://alteredqualia.com/
  16407. *
  16408. * For Text operations in three.js (See TextGeometry)
  16409. *
  16410. * It uses techniques used in:
  16411. *
  16412. * typeface.js and canvastext
  16413. * For converting fonts and rendering with javascript
  16414. * http://typeface.neocracy.org
  16415. *
  16416. * Triangulation ported from AS3
  16417. * Simple Polygon Triangulation
  16418. * http://actionsnippet.com/?p=1462
  16419. *
  16420. * A Method to triangulate shapes with holes
  16421. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16422. *
  16423. */
  16424. THREE.FontUtils = {
  16425. faces : {},
  16426. // Just for now. face[weight][style]
  16427. face : "helvetiker",
  16428. weight: "normal",
  16429. style : "normal",
  16430. size : 150,
  16431. divisions : 10,
  16432. getFace : function() {
  16433. return this.faces[ this.face ][ this.weight ][ this.style ];
  16434. },
  16435. loadFace : function( data ) {
  16436. var family = data.familyName.toLowerCase();
  16437. var ThreeFont = this;
  16438. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16439. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16440. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16441. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16442. return data;
  16443. },
  16444. drawText : function( text ) {
  16445. var characterPts = [], allPts = [];
  16446. // RenderText
  16447. var i, p,
  16448. face = this.getFace(),
  16449. scale = this.size / face.resolution,
  16450. offset = 0,
  16451. chars = String( text ).split( '' ),
  16452. length = chars.length;
  16453. var fontPaths = [];
  16454. for ( i = 0; i < length; i ++ ) {
  16455. var path = new THREE.Path();
  16456. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16457. offset += ret.offset;
  16458. fontPaths.push( ret.path );
  16459. }
  16460. // get the width
  16461. var width = offset / 2;
  16462. //
  16463. // for ( p = 0; p < allPts.length; p++ ) {
  16464. //
  16465. // allPts[ p ].x -= width;
  16466. //
  16467. // }
  16468. //var extract = this.extractPoints( allPts, characterPts );
  16469. //extract.contour = allPts;
  16470. //extract.paths = fontPaths;
  16471. //extract.offset = width;
  16472. return { paths : fontPaths, offset : width };
  16473. },
  16474. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16475. var pts = [];
  16476. var i, i2, divisions,
  16477. outline, action, length,
  16478. scaleX, scaleY,
  16479. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16480. laste,
  16481. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16482. if ( !glyph ) return;
  16483. if ( glyph.o ) {
  16484. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16485. length = outline.length;
  16486. scaleX = scale;
  16487. scaleY = scale;
  16488. for ( i = 0; i < length; ) {
  16489. action = outline[ i ++ ];
  16490. //console.log( action );
  16491. switch( action ) {
  16492. case 'm':
  16493. // Move To
  16494. x = outline[ i++ ] * scaleX + offset;
  16495. y = outline[ i++ ] * scaleY;
  16496. path.moveTo( x, y );
  16497. break;
  16498. case 'l':
  16499. // Line To
  16500. x = outline[ i++ ] * scaleX + offset;
  16501. y = outline[ i++ ] * scaleY;
  16502. path.lineTo(x,y);
  16503. break;
  16504. case 'q':
  16505. // QuadraticCurveTo
  16506. cpx = outline[ i++ ] * scaleX + offset;
  16507. cpy = outline[ i++ ] * scaleY;
  16508. cpx1 = outline[ i++ ] * scaleX + offset;
  16509. cpy1 = outline[ i++ ] * scaleY;
  16510. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16511. laste = pts[ pts.length - 1 ];
  16512. if ( laste ) {
  16513. cpx0 = laste.x;
  16514. cpy0 = laste.y;
  16515. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16516. var t = i2 / divisions;
  16517. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16518. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16519. }
  16520. }
  16521. break;
  16522. case 'b':
  16523. // Cubic Bezier Curve
  16524. cpx = outline[ i++ ] * scaleX + offset;
  16525. cpy = outline[ i++ ] * scaleY;
  16526. cpx1 = outline[ i++ ] * scaleX + offset;
  16527. cpy1 = outline[ i++ ] * -scaleY;
  16528. cpx2 = outline[ i++ ] * scaleX + offset;
  16529. cpy2 = outline[ i++ ] * -scaleY;
  16530. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16531. laste = pts[ pts.length - 1 ];
  16532. if ( laste ) {
  16533. cpx0 = laste.x;
  16534. cpy0 = laste.y;
  16535. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16536. var t = i2 / divisions;
  16537. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16538. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16539. }
  16540. }
  16541. break;
  16542. }
  16543. }
  16544. }
  16545. return { offset: glyph.ha*scale, path:path};
  16546. }
  16547. };
  16548. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16549. // Parameters
  16550. parameters = parameters || {};
  16551. var size = parameters.size !== undefined ? parameters.size : 100;
  16552. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16553. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16554. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16555. var style = parameters.style !== undefined ? parameters.style : "normal";
  16556. THREE.FontUtils.size = size;
  16557. THREE.FontUtils.divisions = curveSegments;
  16558. THREE.FontUtils.face = font;
  16559. THREE.FontUtils.weight = weight;
  16560. THREE.FontUtils.style = style;
  16561. // Get a Font data json object
  16562. var data = THREE.FontUtils.drawText( text );
  16563. var paths = data.paths;
  16564. var shapes = [];
  16565. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16566. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16567. }
  16568. return shapes;
  16569. };
  16570. /**
  16571. * This code is a quick port of code written in C++ which was submitted to
  16572. * flipcode.com by John W. Ratcliff // July 22, 2000
  16573. * See original code and more information here:
  16574. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16575. *
  16576. * ported to actionscript by Zevan Rosser
  16577. * www.actionsnippet.com
  16578. *
  16579. * ported to javascript by Joshua Koo
  16580. * http://www.lab4games.net/zz85/blog
  16581. *
  16582. */
  16583. ( function( namespace ) {
  16584. var EPSILON = 0.0000000001;
  16585. // takes in an contour array and returns
  16586. var process = function( contour, indices ) {
  16587. var n = contour.length;
  16588. if ( n < 3 ) return null;
  16589. var result = [],
  16590. verts = [],
  16591. vertIndices = [];
  16592. /* we want a counter-clockwise polygon in verts */
  16593. var u, v, w;
  16594. if ( area( contour ) > 0.0 ) {
  16595. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16596. } else {
  16597. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16598. }
  16599. var nv = n;
  16600. /* remove nv - 2 vertices, creating 1 triangle every time */
  16601. var count = 2 * nv; /* error detection */
  16602. for( v = nv - 1; nv > 2; ) {
  16603. /* if we loop, it is probably a non-simple polygon */
  16604. if ( ( count-- ) <= 0 ) {
  16605. //** Triangulate: ERROR - probable bad polygon!
  16606. //throw ( "Warning, unable to triangulate polygon!" );
  16607. //return null;
  16608. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16609. console.log( "Warning, unable to triangulate polygon!" );
  16610. if ( indices ) return vertIndices;
  16611. return result;
  16612. }
  16613. /* three consecutive vertices in current polygon, <u,v,w> */
  16614. u = v; if ( nv <= u ) u = 0; /* previous */
  16615. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16616. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16617. if ( snip( contour, u, v, w, nv, verts ) ) {
  16618. var a, b, c, s, t;
  16619. /* true names of the vertices */
  16620. a = verts[ u ];
  16621. b = verts[ v ];
  16622. c = verts[ w ];
  16623. /* output Triangle */
  16624. result.push( [ contour[ a ],
  16625. contour[ b ],
  16626. contour[ c ] ] );
  16627. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16628. /* remove v from the remaining polygon */
  16629. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16630. verts[ s ] = verts[ t ];
  16631. }
  16632. nv--;
  16633. /* reset error detection counter */
  16634. count = 2 * nv;
  16635. }
  16636. }
  16637. if ( indices ) return vertIndices;
  16638. return result;
  16639. };
  16640. // calculate area of the contour polygon
  16641. var area = function ( contour ) {
  16642. var n = contour.length;
  16643. var a = 0.0;
  16644. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16645. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16646. }
  16647. return a * 0.5;
  16648. };
  16649. var snip = function ( contour, u, v, w, n, verts ) {
  16650. var p;
  16651. var ax, ay, bx, by;
  16652. var cx, cy, px, py;
  16653. ax = contour[ verts[ u ] ].x;
  16654. ay = contour[ verts[ u ] ].y;
  16655. bx = contour[ verts[ v ] ].x;
  16656. by = contour[ verts[ v ] ].y;
  16657. cx = contour[ verts[ w ] ].x;
  16658. cy = contour[ verts[ w ] ].y;
  16659. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16660. var aX, aY, bX, bY, cX, cY;
  16661. var apx, apy, bpx, bpy, cpx, cpy;
  16662. var cCROSSap, bCROSScp, aCROSSbp;
  16663. aX = cx - bx; aY = cy - by;
  16664. bX = ax - cx; bY = ay - cy;
  16665. cX = bx - ax; cY = by - ay;
  16666. for ( p = 0; p < n; p++ ) {
  16667. if( (p === u) || (p === v) || (p === w) ) continue;
  16668. px = contour[ verts[ p ] ].x
  16669. py = contour[ verts[ p ] ].y
  16670. apx = px - ax; apy = py - ay;
  16671. bpx = px - bx; bpy = py - by;
  16672. cpx = px - cx; cpy = py - cy;
  16673. // see if p is inside triangle abc
  16674. aCROSSbp = aX*bpy - aY*bpx;
  16675. cCROSSap = cX*apy - cY*apx;
  16676. bCROSScp = bX*cpy - bY*cpx;
  16677. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16678. }
  16679. return true;
  16680. };
  16681. namespace.Triangulate = process;
  16682. namespace.Triangulate.area = area;
  16683. return namespace;
  16684. })(THREE.FontUtils);
  16685. // To use the typeface.js face files, hook up the API
  16686. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  16687. * @author zz85 / http://www.lab4games.net/zz85/blog
  16688. * Extensible curve object
  16689. *
  16690. * Some common of Curve methods
  16691. * .getPoint(t), getTangent(t)
  16692. * .getPointAt(u), getTagentAt(u)
  16693. * .getPoints(), .getSpacedPoints()
  16694. * .getLength()
  16695. * .updateArcLengths()
  16696. *
  16697. * This file contains following classes:
  16698. *
  16699. * -- 2d classes --
  16700. * THREE.Curve
  16701. * THREE.LineCurve
  16702. * THREE.QuadraticBezierCurve
  16703. * THREE.CubicBezierCurve
  16704. * THREE.SplineCurve
  16705. * THREE.ArcCurve
  16706. * THREE.EllipseCurve
  16707. *
  16708. * -- 3d classes --
  16709. * THREE.LineCurve3
  16710. * THREE.QuadraticBezierCurve3
  16711. * THREE.CubicBezierCurve3
  16712. * THREE.SplineCurve3
  16713. * THREE.ClosedSplineCurve3
  16714. *
  16715. * A series of curves can be represented as a THREE.CurvePath
  16716. *
  16717. **/
  16718. /**************************************************************
  16719. * Abstract Curve base class
  16720. **************************************************************/
  16721. THREE.Curve = function () {
  16722. };
  16723. // Virtual base class method to overwrite and implement in subclasses
  16724. // - t [0 .. 1]
  16725. THREE.Curve.prototype.getPoint = function ( t ) {
  16726. console.log( "Warning, getPoint() not implemented!" );
  16727. return null;
  16728. };
  16729. // Get point at relative position in curve according to arc length
  16730. // - u [0 .. 1]
  16731. THREE.Curve.prototype.getPointAt = function ( u ) {
  16732. var t = this.getUtoTmapping( u );
  16733. return this.getPoint( t );
  16734. };
  16735. // Get sequence of points using getPoint( t )
  16736. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16737. if ( !divisions ) divisions = 5;
  16738. var d, pts = [];
  16739. for ( d = 0; d <= divisions; d ++ ) {
  16740. pts.push( this.getPoint( d / divisions ) );
  16741. }
  16742. return pts;
  16743. };
  16744. // Get sequence of points using getPointAt( u )
  16745. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16746. if ( !divisions ) divisions = 5;
  16747. var d, pts = [];
  16748. for ( d = 0; d <= divisions; d ++ ) {
  16749. pts.push( this.getPointAt( d / divisions ) );
  16750. }
  16751. return pts;
  16752. };
  16753. // Get total curve arc length
  16754. THREE.Curve.prototype.getLength = function () {
  16755. var lengths = this.getLengths();
  16756. return lengths[ lengths.length - 1 ];
  16757. };
  16758. // Get list of cumulative segment lengths
  16759. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16760. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16761. if ( this.cacheArcLengths
  16762. && ( this.cacheArcLengths.length == divisions + 1 )
  16763. && !this.needsUpdate) {
  16764. //console.log( "cached", this.cacheArcLengths );
  16765. return this.cacheArcLengths;
  16766. }
  16767. this.needsUpdate = false;
  16768. var cache = [];
  16769. var current, last = this.getPoint( 0 );
  16770. var p, sum = 0;
  16771. cache.push( 0 );
  16772. for ( p = 1; p <= divisions; p ++ ) {
  16773. current = this.getPoint ( p / divisions );
  16774. sum += current.distanceTo( last );
  16775. cache.push( sum );
  16776. last = current;
  16777. }
  16778. this.cacheArcLengths = cache;
  16779. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16780. };
  16781. THREE.Curve.prototype.updateArcLengths = function() {
  16782. this.needsUpdate = true;
  16783. this.getLengths();
  16784. };
  16785. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16786. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16787. var arcLengths = this.getLengths();
  16788. var i = 0, il = arcLengths.length;
  16789. var targetArcLength; // The targeted u distance value to get
  16790. if ( distance ) {
  16791. targetArcLength = distance;
  16792. } else {
  16793. targetArcLength = u * arcLengths[ il - 1 ];
  16794. }
  16795. //var time = Date.now();
  16796. // binary search for the index with largest value smaller than target u distance
  16797. var low = 0, high = il - 1, comparison;
  16798. while ( low <= high ) {
  16799. 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
  16800. comparison = arcLengths[ i ] - targetArcLength;
  16801. if ( comparison < 0 ) {
  16802. low = i + 1;
  16803. continue;
  16804. } else if ( comparison > 0 ) {
  16805. high = i - 1;
  16806. continue;
  16807. } else {
  16808. high = i;
  16809. break;
  16810. // DONE
  16811. }
  16812. }
  16813. i = high;
  16814. //console.log('b' , i, low, high, Date.now()- time);
  16815. if ( arcLengths[ i ] == targetArcLength ) {
  16816. var t = i / ( il - 1 );
  16817. return t;
  16818. }
  16819. // we could get finer grain at lengths, or use simple interpolatation between two points
  16820. var lengthBefore = arcLengths[ i ];
  16821. var lengthAfter = arcLengths[ i + 1 ];
  16822. var segmentLength = lengthAfter - lengthBefore;
  16823. // determine where we are between the 'before' and 'after' points
  16824. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16825. // add that fractional amount to t
  16826. var t = ( i + segmentFraction ) / ( il -1 );
  16827. return t;
  16828. };
  16829. // Returns a unit vector tangent at t
  16830. // In case any sub curve does not implement its tangent derivation,
  16831. // 2 points a small delta apart will be used to find its gradient
  16832. // which seems to give a reasonable approximation
  16833. THREE.Curve.prototype.getTangent = function( t ) {
  16834. var delta = 0.0001;
  16835. var t1 = t - delta;
  16836. var t2 = t + delta;
  16837. // Capping in case of danger
  16838. if ( t1 < 0 ) t1 = 0;
  16839. if ( t2 > 1 ) t2 = 1;
  16840. var pt1 = this.getPoint( t1 );
  16841. var pt2 = this.getPoint( t2 );
  16842. var vec = pt2.clone().subSelf(pt1);
  16843. return vec.normalize();
  16844. };
  16845. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16846. var t = this.getUtoTmapping( u );
  16847. return this.getTangent( t );
  16848. };
  16849. /**************************************************************
  16850. * Line
  16851. **************************************************************/
  16852. THREE.LineCurve = function ( v1, v2 ) {
  16853. this.v1 = v1;
  16854. this.v2 = v2;
  16855. };
  16856. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16857. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16858. var point = this.v2.clone().subSelf(this.v1);
  16859. point.multiplyScalar( t ).addSelf( this.v1 );
  16860. return point;
  16861. };
  16862. // Line curve is linear, so we can overwrite default getPointAt
  16863. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16864. return this.getPoint( u );
  16865. };
  16866. THREE.LineCurve.prototype.getTangent = function( t ) {
  16867. var tangent = this.v2.clone().subSelf(this.v1);
  16868. return tangent.normalize();
  16869. };
  16870. /**************************************************************
  16871. * Quadratic Bezier curve
  16872. **************************************************************/
  16873. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16874. this.v0 = v0;
  16875. this.v1 = v1;
  16876. this.v2 = v2;
  16877. };
  16878. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16879. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16880. var tx, ty;
  16881. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16882. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16883. return new THREE.Vector2( tx, ty );
  16884. };
  16885. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16886. var tx, ty;
  16887. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16888. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16889. // returns unit vector
  16890. var tangent = new THREE.Vector2( tx, ty );
  16891. tangent.normalize();
  16892. return tangent;
  16893. };
  16894. /**************************************************************
  16895. * Cubic Bezier curve
  16896. **************************************************************/
  16897. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16898. this.v0 = v0;
  16899. this.v1 = v1;
  16900. this.v2 = v2;
  16901. this.v3 = v3;
  16902. };
  16903. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16904. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16905. var tx, ty;
  16906. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16907. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16908. return new THREE.Vector2( tx, ty );
  16909. };
  16910. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16911. var tx, ty;
  16912. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16913. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16914. var tangent = new THREE.Vector2( tx, ty );
  16915. tangent.normalize();
  16916. return tangent;
  16917. };
  16918. /**************************************************************
  16919. * Spline curve
  16920. **************************************************************/
  16921. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16922. this.points = (points == undefined) ? [] : points;
  16923. };
  16924. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16925. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16926. var v = new THREE.Vector2();
  16927. var c = [];
  16928. var points = this.points, point, intPoint, weight;
  16929. point = ( points.length - 1 ) * t;
  16930. intPoint = Math.floor( point );
  16931. weight = point - intPoint;
  16932. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16933. c[ 1 ] = intPoint;
  16934. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16935. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16936. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16937. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16938. return v;
  16939. };
  16940. /**************************************************************
  16941. * Ellipse curve
  16942. **************************************************************/
  16943. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16944. aStartAngle, aEndAngle,
  16945. aClockwise ) {
  16946. this.aX = aX;
  16947. this.aY = aY;
  16948. this.xRadius = xRadius;
  16949. this.yRadius = yRadius;
  16950. this.aStartAngle = aStartAngle;
  16951. this.aEndAngle = aEndAngle;
  16952. this.aClockwise = aClockwise;
  16953. };
  16954. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16955. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16956. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16957. if ( !this.aClockwise ) {
  16958. t = 1 - t;
  16959. }
  16960. var angle = this.aStartAngle + t * deltaAngle;
  16961. var tx = this.aX + this.xRadius * Math.cos( angle );
  16962. var ty = this.aY + this.yRadius * Math.sin( angle );
  16963. return new THREE.Vector2( tx, ty );
  16964. };
  16965. /**************************************************************
  16966. * Arc curve
  16967. **************************************************************/
  16968. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16969. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16970. };
  16971. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16972. /**************************************************************
  16973. * Utils
  16974. **************************************************************/
  16975. THREE.Curve.Utils = {
  16976. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16977. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16978. },
  16979. // Puay Bing, thanks for helping with this derivative!
  16980. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16981. return -3 * p0 * (1 - t) * (1 - t) +
  16982. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16983. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16984. 3 * t * t * p3;
  16985. },
  16986. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16987. // To check if my formulas are correct
  16988. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16989. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16990. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16991. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16992. return h00 + h10 + h01 + h11;
  16993. },
  16994. // Catmull-Rom
  16995. interpolate: function( p0, p1, p2, p3, t ) {
  16996. var v0 = ( p2 - p0 ) * 0.5;
  16997. var v1 = ( p3 - p1 ) * 0.5;
  16998. var t2 = t * t;
  16999. var t3 = t * t2;
  17000. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17001. }
  17002. };
  17003. // TODO: Transformation for Curves?
  17004. /**************************************************************
  17005. * 3D Curves
  17006. **************************************************************/
  17007. // A Factory method for creating new curve subclasses
  17008. THREE.Curve.create = function ( constructor, getPointFunc ) {
  17009. constructor.prototype = Object.create( THREE.Curve.prototype );
  17010. constructor.prototype.getPoint = getPointFunc;
  17011. return constructor;
  17012. };
  17013. /**************************************************************
  17014. * Line3D
  17015. **************************************************************/
  17016. THREE.LineCurve3 = THREE.Curve.create(
  17017. function ( v1, v2 ) {
  17018. this.v1 = v1;
  17019. this.v2 = v2;
  17020. },
  17021. function ( t ) {
  17022. var r = new THREE.Vector3();
  17023. r.sub( this.v2, this.v1 ); // diff
  17024. r.multiplyScalar( t );
  17025. r.addSelf( this.v1 );
  17026. return r;
  17027. }
  17028. );
  17029. /**************************************************************
  17030. * Quadratic Bezier 3D curve
  17031. **************************************************************/
  17032. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17033. function ( v0, v1, v2 ) {
  17034. this.v0 = v0;
  17035. this.v1 = v1;
  17036. this.v2 = v2;
  17037. },
  17038. function ( t ) {
  17039. var tx, ty, tz;
  17040. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17041. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17042. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17043. return new THREE.Vector3( tx, ty, tz );
  17044. }
  17045. );
  17046. /**************************************************************
  17047. * Cubic Bezier 3D curve
  17048. **************************************************************/
  17049. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17050. function ( v0, v1, v2, v3 ) {
  17051. this.v0 = v0;
  17052. this.v1 = v1;
  17053. this.v2 = v2;
  17054. this.v3 = v3;
  17055. },
  17056. function ( t ) {
  17057. var tx, ty, tz;
  17058. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17059. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17060. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17061. return new THREE.Vector3( tx, ty, tz );
  17062. }
  17063. );
  17064. /**************************************************************
  17065. * Spline 3D curve
  17066. **************************************************************/
  17067. THREE.SplineCurve3 = THREE.Curve.create(
  17068. function ( points /* array of Vector3 */) {
  17069. this.points = (points == undefined) ? [] : points;
  17070. },
  17071. function ( t ) {
  17072. var v = new THREE.Vector3();
  17073. var c = [];
  17074. var points = this.points, point, intPoint, weight;
  17075. point = ( points.length - 1 ) * t;
  17076. intPoint = Math.floor( point );
  17077. weight = point - intPoint;
  17078. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17079. c[ 1 ] = intPoint;
  17080. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17081. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17082. var pt0 = points[ c[0] ],
  17083. pt1 = points[ c[1] ],
  17084. pt2 = points[ c[2] ],
  17085. pt3 = points[ c[3] ];
  17086. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  17087. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  17088. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  17089. return v;
  17090. }
  17091. );
  17092. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  17093. // var v = new THREE.Vector3();
  17094. // var c = [];
  17095. // var points = this.points, point, intPoint, weight;
  17096. // point = ( points.length - 1 ) * t;
  17097. // intPoint = Math.floor( point );
  17098. // weight = point - intPoint;
  17099. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17100. // c[ 1 ] = intPoint;
  17101. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17102. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17103. // var pt0 = points[ c[0] ],
  17104. // pt1 = points[ c[1] ],
  17105. // pt2 = points[ c[2] ],
  17106. // pt3 = points[ c[3] ];
  17107. // // t = weight;
  17108. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  17109. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  17110. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  17111. // return v;
  17112. // }
  17113. /**************************************************************
  17114. * Closed Spline 3D curve
  17115. **************************************************************/
  17116. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17117. function ( points /* array of Vector3 */) {
  17118. this.points = (points == undefined) ? [] : points;
  17119. },
  17120. function ( t ) {
  17121. var v = new THREE.Vector3();
  17122. var c = [];
  17123. var points = this.points, point, intPoint, weight;
  17124. point = ( points.length - 0 ) * t;
  17125. // This needs to be from 0-length +1
  17126. intPoint = Math.floor( point );
  17127. weight = point - intPoint;
  17128. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17129. c[ 0 ] = ( intPoint - 1 ) % points.length;
  17130. c[ 1 ] = ( intPoint ) % points.length;
  17131. c[ 2 ] = ( intPoint + 1 ) % points.length;
  17132. c[ 3 ] = ( intPoint + 2 ) % points.length;
  17133. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17134. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17135. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  17136. return v;
  17137. }
  17138. );
  17139. /**
  17140. * @author zz85 / http://www.lab4games.net/zz85/blog
  17141. *
  17142. **/
  17143. /**************************************************************
  17144. * Curved Path - a curve path is simply a array of connected
  17145. * curves, but retains the api of a curve
  17146. **************************************************************/
  17147. THREE.CurvePath = function () {
  17148. this.curves = [];
  17149. this.bends = [];
  17150. this.autoClose = false; // Automatically closes the path
  17151. };
  17152. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  17153. THREE.CurvePath.prototype.add = function ( curve ) {
  17154. this.curves.push( curve );
  17155. };
  17156. THREE.CurvePath.prototype.checkConnection = function() {
  17157. // TODO
  17158. // If the ending of curve is not connected to the starting
  17159. // or the next curve, then, this is not a real path
  17160. };
  17161. THREE.CurvePath.prototype.closePath = function() {
  17162. // TODO Test
  17163. // and verify for vector3 (needs to implement equals)
  17164. // Add a line curve if start and end of lines are not connected
  17165. var startPoint = this.curves[0].getPoint(0);
  17166. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  17167. if (!startPoint.equals(endPoint)) {
  17168. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  17169. }
  17170. };
  17171. // To get accurate point with reference to
  17172. // entire path distance at time t,
  17173. // following has to be done:
  17174. // 1. Length of each sub path have to be known
  17175. // 2. Locate and identify type of curve
  17176. // 3. Get t for the curve
  17177. // 4. Return curve.getPointAt(t')
  17178. THREE.CurvePath.prototype.getPoint = function( t ) {
  17179. var d = t * this.getLength();
  17180. var curveLengths = this.getCurveLengths();
  17181. var i = 0, diff, curve;
  17182. // To think about boundaries points.
  17183. while ( i < curveLengths.length ) {
  17184. if ( curveLengths[ i ] >= d ) {
  17185. diff = curveLengths[ i ] - d;
  17186. curve = this.curves[ i ];
  17187. var u = 1 - diff / curve.getLength();
  17188. return curve.getPointAt( u );
  17189. break;
  17190. }
  17191. i ++;
  17192. }
  17193. return null;
  17194. // loop where sum != 0, sum > d , sum+1 <d
  17195. };
  17196. /*
  17197. THREE.CurvePath.prototype.getTangent = function( t ) {
  17198. };*/
  17199. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17200. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17201. // getPoint() depends on getLength
  17202. THREE.CurvePath.prototype.getLength = function() {
  17203. var lens = this.getCurveLengths();
  17204. return lens[ lens.length - 1 ];
  17205. };
  17206. // Compute lengths and cache them
  17207. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17208. THREE.CurvePath.prototype.getCurveLengths = function() {
  17209. // We use cache values if curves and cache array are same length
  17210. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  17211. return this.cacheLengths;
  17212. };
  17213. // Get length of subsurve
  17214. // Push sums into cached array
  17215. var lengths = [], sums = 0;
  17216. var i, il = this.curves.length;
  17217. for ( i = 0; i < il; i ++ ) {
  17218. sums += this.curves[ i ].getLength();
  17219. lengths.push( sums );
  17220. }
  17221. this.cacheLengths = lengths;
  17222. return lengths;
  17223. };
  17224. // Returns min and max coordinates, as well as centroid
  17225. THREE.CurvePath.prototype.getBoundingBox = function () {
  17226. var points = this.getPoints();
  17227. var maxX, maxY, maxZ;
  17228. var minX, minY, minZ;
  17229. maxX = maxY = Number.NEGATIVE_INFINITY;
  17230. minX = minY = Number.POSITIVE_INFINITY;
  17231. var p, i, il, sum;
  17232. var v3 = points[0] instanceof THREE.Vector3;
  17233. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  17234. for ( i = 0, il = points.length; i < il; i ++ ) {
  17235. p = points[ i ];
  17236. if ( p.x > maxX ) maxX = p.x;
  17237. else if ( p.x < minX ) minX = p.x;
  17238. if ( p.y > maxY ) maxY = p.y;
  17239. else if ( p.y < minY ) minY = p.y;
  17240. if (v3) {
  17241. if ( p.z > maxZ ) maxZ = p.z;
  17242. else if ( p.z < minZ ) minZ = p.z;
  17243. }
  17244. sum.addSelf( p );
  17245. }
  17246. var ret = {
  17247. minX: minX,
  17248. minY: minY,
  17249. maxX: maxX,
  17250. maxY: maxY,
  17251. centroid: sum.divideScalar( il )
  17252. };
  17253. if (v3) {
  17254. ret.maxZ = maxZ;
  17255. ret.minZ = minZ;
  17256. }
  17257. return ret;
  17258. };
  17259. /**************************************************************
  17260. * Create Geometries Helpers
  17261. **************************************************************/
  17262. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17263. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17264. var pts = this.getPoints( divisions, true );
  17265. return this.createGeometry( pts );
  17266. };
  17267. // Generate geometry from equidistance sampling along the path
  17268. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17269. var pts = this.getSpacedPoints( divisions, true );
  17270. return this.createGeometry( pts );
  17271. };
  17272. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17273. var geometry = new THREE.Geometry();
  17274. for ( var i = 0; i < points.length; i ++ ) {
  17275. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17276. }
  17277. return geometry;
  17278. };
  17279. /**************************************************************
  17280. * Bend / Wrap Helper Methods
  17281. **************************************************************/
  17282. // Wrap path / Bend modifiers?
  17283. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17284. this.bends.push( bendpath );
  17285. };
  17286. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17287. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17288. var i, il;
  17289. if ( !bends ) {
  17290. bends = this.bends;
  17291. }
  17292. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17293. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17294. }
  17295. return oldPts;
  17296. };
  17297. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17298. var oldPts = this.getSpacedPoints( segments );
  17299. var i, il;
  17300. if ( !bends ) {
  17301. bends = this.bends;
  17302. }
  17303. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17304. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17305. }
  17306. return oldPts;
  17307. };
  17308. // This returns getPoints() bend/wrapped around the contour of a path.
  17309. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17310. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17311. var bounds = this.getBoundingBox();
  17312. var i, il, p, oldX, oldY, xNorm;
  17313. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17314. p = oldPts[ i ];
  17315. oldX = p.x;
  17316. oldY = p.y;
  17317. xNorm = oldX / bounds.maxX;
  17318. // If using actual distance, for length > path, requires line extrusions
  17319. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17320. xNorm = path.getUtoTmapping( xNorm, oldX );
  17321. // check for out of bounds?
  17322. var pathPt = path.getPoint( xNorm );
  17323. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  17324. p.x = pathPt.x + normal.x;
  17325. p.y = pathPt.y + normal.y;
  17326. }
  17327. return oldPts;
  17328. };
  17329. /**
  17330. * @author alteredq / http://alteredqualia.com/
  17331. */
  17332. THREE.Gyroscope = function () {
  17333. THREE.Object3D.call( this );
  17334. };
  17335. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17336. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17337. this.matrixAutoUpdate && this.updateMatrix();
  17338. // update matrixWorld
  17339. if ( this.matrixWorldNeedsUpdate || force ) {
  17340. if ( this.parent ) {
  17341. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  17342. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  17343. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  17344. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  17345. } else {
  17346. this.matrixWorld.copy( this.matrix );
  17347. }
  17348. this.matrixWorldNeedsUpdate = false;
  17349. force = true;
  17350. }
  17351. // update children
  17352. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17353. this.children[ i ].updateMatrixWorld( force );
  17354. }
  17355. };
  17356. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17357. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17358. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  17359. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  17360. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17361. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17362. /**
  17363. * @author zz85 / http://www.lab4games.net/zz85/blog
  17364. * Creates free form 2d path using series of points, lines or curves.
  17365. *
  17366. **/
  17367. THREE.Path = function ( points ) {
  17368. THREE.CurvePath.call(this);
  17369. this.actions = [];
  17370. if ( points ) {
  17371. this.fromPoints( points );
  17372. }
  17373. };
  17374. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17375. THREE.PathActions = {
  17376. MOVE_TO: 'moveTo',
  17377. LINE_TO: 'lineTo',
  17378. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17379. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17380. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17381. ARC: 'arc', // Circle
  17382. ELLIPSE: 'ellipse'
  17383. };
  17384. // TODO Clean up PATH API
  17385. // Create path using straight lines to connect all points
  17386. // - vectors: array of Vector2
  17387. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17388. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17389. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17390. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17391. };
  17392. };
  17393. // startPath() endPath()?
  17394. THREE.Path.prototype.moveTo = function ( x, y ) {
  17395. var args = Array.prototype.slice.call( arguments );
  17396. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17397. };
  17398. THREE.Path.prototype.lineTo = function ( x, y ) {
  17399. var args = Array.prototype.slice.call( arguments );
  17400. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17401. var x0 = lastargs[ lastargs.length - 2 ];
  17402. var y0 = lastargs[ lastargs.length - 1 ];
  17403. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17404. this.curves.push( curve );
  17405. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17406. };
  17407. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17408. var args = Array.prototype.slice.call( arguments );
  17409. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17410. var x0 = lastargs[ lastargs.length - 2 ];
  17411. var y0 = lastargs[ lastargs.length - 1 ];
  17412. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17413. new THREE.Vector2( aCPx, aCPy ),
  17414. new THREE.Vector2( aX, aY ) );
  17415. this.curves.push( curve );
  17416. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17417. };
  17418. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17419. aCP2x, aCP2y,
  17420. aX, aY ) {
  17421. var args = Array.prototype.slice.call( arguments );
  17422. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17423. var x0 = lastargs[ lastargs.length - 2 ];
  17424. var y0 = lastargs[ lastargs.length - 1 ];
  17425. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17426. new THREE.Vector2( aCP1x, aCP1y ),
  17427. new THREE.Vector2( aCP2x, aCP2y ),
  17428. new THREE.Vector2( aX, aY ) );
  17429. this.curves.push( curve );
  17430. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17431. };
  17432. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17433. var args = Array.prototype.slice.call( arguments );
  17434. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17435. var x0 = lastargs[ lastargs.length - 2 ];
  17436. var y0 = lastargs[ lastargs.length - 1 ];
  17437. //---
  17438. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17439. Array.prototype.push.apply( npts, pts );
  17440. var curve = new THREE.SplineCurve( npts );
  17441. this.curves.push( curve );
  17442. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17443. };
  17444. // FUTURE: Change the API or follow canvas API?
  17445. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17446. aStartAngle, aEndAngle, aClockwise ) {
  17447. var lastargs = this.actions[ this.actions.length - 1].args;
  17448. var x0 = lastargs[ lastargs.length - 2 ];
  17449. var y0 = lastargs[ lastargs.length - 1 ];
  17450. this.absarc(aX + x0, aY + y0, aRadius,
  17451. aStartAngle, aEndAngle, aClockwise );
  17452. };
  17453. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17454. aStartAngle, aEndAngle, aClockwise ) {
  17455. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17456. };
  17457. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17458. aStartAngle, aEndAngle, aClockwise ) {
  17459. var lastargs = this.actions[ this.actions.length - 1].args;
  17460. var x0 = lastargs[ lastargs.length - 2 ];
  17461. var y0 = lastargs[ lastargs.length - 1 ];
  17462. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17463. aStartAngle, aEndAngle, aClockwise );
  17464. };
  17465. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17466. aStartAngle, aEndAngle, aClockwise ) {
  17467. var args = Array.prototype.slice.call( arguments );
  17468. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17469. aStartAngle, aEndAngle, aClockwise );
  17470. this.curves.push( curve );
  17471. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17472. args.push(lastPoint.x);
  17473. args.push(lastPoint.y);
  17474. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17475. };
  17476. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17477. if ( ! divisions ) divisions = 40;
  17478. var points = [];
  17479. for ( var i = 0; i < divisions; i ++ ) {
  17480. points.push( this.getPoint( i / divisions ) );
  17481. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17482. }
  17483. // if ( closedPath ) {
  17484. //
  17485. // points.push( points[ 0 ] );
  17486. //
  17487. // }
  17488. return points;
  17489. };
  17490. /* Return an array of vectors based on contour of the path */
  17491. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17492. if (this.useSpacedPoints) {
  17493. console.log('tata');
  17494. return this.getSpacedPoints( divisions, closedPath );
  17495. }
  17496. divisions = divisions || 12;
  17497. var points = [];
  17498. var i, il, item, action, args;
  17499. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17500. laste, j,
  17501. t, tx, ty;
  17502. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17503. item = this.actions[ i ];
  17504. action = item.action;
  17505. args = item.args;
  17506. switch( action ) {
  17507. case THREE.PathActions.MOVE_TO:
  17508. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17509. break;
  17510. case THREE.PathActions.LINE_TO:
  17511. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17512. break;
  17513. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17514. cpx = args[ 2 ];
  17515. cpy = args[ 3 ];
  17516. cpx1 = args[ 0 ];
  17517. cpy1 = args[ 1 ];
  17518. if ( points.length > 0 ) {
  17519. laste = points[ points.length - 1 ];
  17520. cpx0 = laste.x;
  17521. cpy0 = laste.y;
  17522. } else {
  17523. laste = this.actions[ i - 1 ].args;
  17524. cpx0 = laste[ laste.length - 2 ];
  17525. cpy0 = laste[ laste.length - 1 ];
  17526. }
  17527. for ( j = 1; j <= divisions; j ++ ) {
  17528. t = j / divisions;
  17529. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17530. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17531. points.push( new THREE.Vector2( tx, ty ) );
  17532. }
  17533. break;
  17534. case THREE.PathActions.BEZIER_CURVE_TO:
  17535. cpx = args[ 4 ];
  17536. cpy = args[ 5 ];
  17537. cpx1 = args[ 0 ];
  17538. cpy1 = args[ 1 ];
  17539. cpx2 = args[ 2 ];
  17540. cpy2 = args[ 3 ];
  17541. if ( points.length > 0 ) {
  17542. laste = points[ points.length - 1 ];
  17543. cpx0 = laste.x;
  17544. cpy0 = laste.y;
  17545. } else {
  17546. laste = this.actions[ i - 1 ].args;
  17547. cpx0 = laste[ laste.length - 2 ];
  17548. cpy0 = laste[ laste.length - 1 ];
  17549. }
  17550. for ( j = 1; j <= divisions; j ++ ) {
  17551. t = j / divisions;
  17552. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17553. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17554. points.push( new THREE.Vector2( tx, ty ) );
  17555. }
  17556. break;
  17557. case THREE.PathActions.CSPLINE_THRU:
  17558. laste = this.actions[ i - 1 ].args;
  17559. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17560. var spts = [ last ];
  17561. var n = divisions * args[ 0 ].length;
  17562. spts = spts.concat( args[ 0 ] );
  17563. var spline = new THREE.SplineCurve( spts );
  17564. for ( j = 1; j <= n; j ++ ) {
  17565. points.push( spline.getPointAt( j / n ) ) ;
  17566. }
  17567. break;
  17568. case THREE.PathActions.ARC:
  17569. var aX = args[ 0 ], aY = args[ 1 ],
  17570. aRadius = args[ 2 ],
  17571. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17572. aClockwise = !!args[ 5 ];
  17573. var deltaAngle = aEndAngle - aStartAngle;
  17574. var angle;
  17575. var tdivisions = divisions * 2;
  17576. for ( j = 1; j <= tdivisions; j ++ ) {
  17577. t = j / tdivisions;
  17578. if ( ! aClockwise ) {
  17579. t = 1 - t;
  17580. }
  17581. angle = aStartAngle + t * deltaAngle;
  17582. tx = aX + aRadius * Math.cos( angle );
  17583. ty = aY + aRadius * Math.sin( angle );
  17584. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17585. points.push( new THREE.Vector2( tx, ty ) );
  17586. }
  17587. //console.log(points);
  17588. break;
  17589. case THREE.PathActions.ELLIPSE:
  17590. var aX = args[ 0 ], aY = args[ 1 ],
  17591. xRadius = args[ 2 ],
  17592. yRadius = args[ 3 ],
  17593. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17594. aClockwise = !!args[ 6 ];
  17595. var deltaAngle = aEndAngle - aStartAngle;
  17596. var angle;
  17597. var tdivisions = divisions * 2;
  17598. for ( j = 1; j <= tdivisions; j ++ ) {
  17599. t = j / tdivisions;
  17600. if ( ! aClockwise ) {
  17601. t = 1 - t;
  17602. }
  17603. angle = aStartAngle + t * deltaAngle;
  17604. tx = aX + xRadius * Math.cos( angle );
  17605. ty = aY + yRadius * Math.sin( angle );
  17606. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17607. points.push( new THREE.Vector2( tx, ty ) );
  17608. }
  17609. //console.log(points);
  17610. break;
  17611. } // end switch
  17612. }
  17613. // Normalize to remove the closing point by default.
  17614. var lastPoint = points[ points.length - 1];
  17615. var EPSILON = 0.0000000001;
  17616. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17617. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17618. points.splice( points.length - 1, 1);
  17619. if ( closedPath ) {
  17620. points.push( points[ 0 ] );
  17621. }
  17622. return points;
  17623. };
  17624. // Breaks path into shapes
  17625. THREE.Path.prototype.toShapes = function() {
  17626. var i, il, item, action, args;
  17627. var subPaths = [], lastPath = new THREE.Path();
  17628. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17629. item = this.actions[ i ];
  17630. args = item.args;
  17631. action = item.action;
  17632. if ( action == THREE.PathActions.MOVE_TO ) {
  17633. if ( lastPath.actions.length != 0 ) {
  17634. subPaths.push( lastPath );
  17635. lastPath = new THREE.Path();
  17636. }
  17637. }
  17638. lastPath[ action ].apply( lastPath, args );
  17639. }
  17640. if ( lastPath.actions.length != 0 ) {
  17641. subPaths.push( lastPath );
  17642. }
  17643. // console.log(subPaths);
  17644. if ( subPaths.length == 0 ) return [];
  17645. var tmpPath, tmpShape, shapes = [];
  17646. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17647. // console.log("Holes first", holesFirst);
  17648. if ( subPaths.length == 1) {
  17649. tmpPath = subPaths[0];
  17650. tmpShape = new THREE.Shape();
  17651. tmpShape.actions = tmpPath.actions;
  17652. tmpShape.curves = tmpPath.curves;
  17653. shapes.push( tmpShape );
  17654. return shapes;
  17655. };
  17656. if ( holesFirst ) {
  17657. tmpShape = new THREE.Shape();
  17658. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17659. tmpPath = subPaths[ i ];
  17660. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17661. tmpShape.actions = tmpPath.actions;
  17662. tmpShape.curves = tmpPath.curves;
  17663. shapes.push( tmpShape );
  17664. tmpShape = new THREE.Shape();
  17665. //console.log('cw', i);
  17666. } else {
  17667. tmpShape.holes.push( tmpPath );
  17668. //console.log('ccw', i);
  17669. }
  17670. }
  17671. } else {
  17672. // Shapes first
  17673. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17674. tmpPath = subPaths[ i ];
  17675. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17676. if ( tmpShape ) shapes.push( tmpShape );
  17677. tmpShape = new THREE.Shape();
  17678. tmpShape.actions = tmpPath.actions;
  17679. tmpShape.curves = tmpPath.curves;
  17680. } else {
  17681. tmpShape.holes.push( tmpPath );
  17682. }
  17683. }
  17684. shapes.push( tmpShape );
  17685. }
  17686. //console.log("shape", shapes);
  17687. return shapes;
  17688. };
  17689. /**
  17690. * @author zz85 / http://www.lab4games.net/zz85/blog
  17691. * Defines a 2d shape plane using paths.
  17692. **/
  17693. // STEP 1 Create a path.
  17694. // STEP 2 Turn path into shape.
  17695. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17696. // STEP 3a - Extract points from each shape, turn to vertices
  17697. // STEP 3b - Triangulate each shape, add faces.
  17698. THREE.Shape = function ( ) {
  17699. THREE.Path.apply( this, arguments );
  17700. this.holes = [];
  17701. };
  17702. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17703. // Convenience method to return ExtrudeGeometry
  17704. THREE.Shape.prototype.extrude = function ( options ) {
  17705. var extruded = new THREE.ExtrudeGeometry( this, options );
  17706. return extruded;
  17707. };
  17708. // Convenience method to return ShapeGeometry
  17709. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17710. var geometry = new THREE.ShapeGeometry( this, options );
  17711. return geometry;
  17712. };
  17713. // Get points of holes
  17714. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17715. var i, il = this.holes.length, holesPts = [];
  17716. for ( i = 0; i < il; i ++ ) {
  17717. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17718. }
  17719. return holesPts;
  17720. };
  17721. // Get points of holes (spaced by regular distance)
  17722. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17723. var i, il = this.holes.length, holesPts = [];
  17724. for ( i = 0; i < il; i ++ ) {
  17725. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17726. }
  17727. return holesPts;
  17728. };
  17729. // Get points of shape and holes (keypoints based on segments parameter)
  17730. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17731. return {
  17732. shape: this.getTransformedPoints( divisions ),
  17733. holes: this.getPointsHoles( divisions )
  17734. };
  17735. };
  17736. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17737. if (this.useSpacedPoints) {
  17738. return this.extractAllSpacedPoints(divisions);
  17739. }
  17740. return this.extractAllPoints(divisions);
  17741. };
  17742. //
  17743. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17744. //
  17745. // return {
  17746. //
  17747. // shape: this.transform( bend, divisions ),
  17748. // holes: this.getPointsHoles( divisions, bend )
  17749. //
  17750. // };
  17751. //
  17752. // };
  17753. // Get points of shape and holes (spaced by regular distance)
  17754. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17755. return {
  17756. shape: this.getTransformedSpacedPoints( divisions ),
  17757. holes: this.getSpacedPointsHoles( divisions )
  17758. };
  17759. };
  17760. /**************************************************************
  17761. * Utils
  17762. **************************************************************/
  17763. THREE.Shape.Utils = {
  17764. /*
  17765. contour - array of vector2 for contour
  17766. holes - array of array of vector2
  17767. */
  17768. removeHoles: function ( contour, holes ) {
  17769. var shape = contour.concat(); // work on this shape
  17770. var allpoints = shape.concat();
  17771. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17772. var prevShapeVert, nextShapeVert,
  17773. prevHoleVert, nextHoleVert,
  17774. holeIndex, shapeIndex,
  17775. shapeId, shapeGroup,
  17776. h, h2,
  17777. hole, shortest, d,
  17778. p, pts1, pts2,
  17779. tmpShape1, tmpShape2,
  17780. tmpHole1, tmpHole2,
  17781. verts = [];
  17782. for ( h = 0; h < holes.length; h ++ ) {
  17783. hole = holes[ h ];
  17784. /*
  17785. shapeholes[ h ].concat(); // preserves original
  17786. holes.push( hole );
  17787. */
  17788. Array.prototype.push.apply( allpoints, hole );
  17789. shortest = Number.POSITIVE_INFINITY;
  17790. // Find the shortest pair of pts between shape and hole
  17791. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17792. // Using distanceToSquared() intead of distanceTo() should speed a little
  17793. // since running square roots operations are reduced.
  17794. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17795. pts1 = hole[ h2 ];
  17796. var dist = [];
  17797. for ( p = 0; p < shape.length; p++ ) {
  17798. pts2 = shape[ p ];
  17799. d = pts1.distanceToSquared( pts2 );
  17800. dist.push( d );
  17801. if ( d < shortest ) {
  17802. shortest = d;
  17803. holeIndex = h2;
  17804. shapeIndex = p;
  17805. }
  17806. }
  17807. }
  17808. //console.log("shortest", shortest, dist);
  17809. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17810. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17811. var areaapts = [
  17812. hole[ holeIndex ],
  17813. shape[ shapeIndex ],
  17814. shape[ prevShapeVert ]
  17815. ];
  17816. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17817. var areabpts = [
  17818. hole[ holeIndex ],
  17819. hole[ prevHoleVert ],
  17820. shape[ shapeIndex ]
  17821. ];
  17822. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17823. var shapeOffset = 1;
  17824. var holeOffset = -1;
  17825. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17826. shapeIndex += shapeOffset;
  17827. holeIndex += holeOffset;
  17828. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17829. shapeIndex %= shape.length;
  17830. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17831. holeIndex %= hole.length;
  17832. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17833. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17834. areaapts = [
  17835. hole[ holeIndex ],
  17836. shape[ shapeIndex ],
  17837. shape[ prevShapeVert ]
  17838. ];
  17839. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17840. areabpts = [
  17841. hole[ holeIndex ],
  17842. hole[ prevHoleVert ],
  17843. shape[ shapeIndex ]
  17844. ];
  17845. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17846. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17847. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17848. // In case areas are not correct.
  17849. //console.log("USE THIS");
  17850. shapeIndex = oldShapeIndex;
  17851. holeIndex = oldHoleIndex ;
  17852. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17853. shapeIndex %= shape.length;
  17854. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17855. holeIndex %= hole.length;
  17856. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17857. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17858. } else {
  17859. //console.log("USE THAT ")
  17860. }
  17861. tmpShape1 = shape.slice( 0, shapeIndex );
  17862. tmpShape2 = shape.slice( shapeIndex );
  17863. tmpHole1 = hole.slice( holeIndex );
  17864. tmpHole2 = hole.slice( 0, holeIndex );
  17865. // Should check orders here again?
  17866. var trianglea = [
  17867. hole[ holeIndex ],
  17868. shape[ shapeIndex ],
  17869. shape[ prevShapeVert ]
  17870. ];
  17871. var triangleb = [
  17872. hole[ holeIndex ] ,
  17873. hole[ prevHoleVert ],
  17874. shape[ shapeIndex ]
  17875. ];
  17876. verts.push( trianglea );
  17877. verts.push( triangleb );
  17878. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17879. }
  17880. return {
  17881. shape:shape, /* shape with no holes */
  17882. isolatedPts: verts, /* isolated faces */
  17883. allpoints: allpoints
  17884. }
  17885. },
  17886. triangulateShape: function ( contour, holes ) {
  17887. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17888. var shape = shapeWithoutHoles.shape,
  17889. allpoints = shapeWithoutHoles.allpoints,
  17890. isolatedPts = shapeWithoutHoles.isolatedPts;
  17891. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17892. // 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.
  17893. //console.log( "triangles",triangles, triangles.length );
  17894. //console.log( "allpoints",allpoints, allpoints.length );
  17895. var i, il, f, face,
  17896. key, index,
  17897. allPointsMap = {},
  17898. isolatedPointsMap = {};
  17899. // prepare all points map
  17900. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17901. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17902. if ( allPointsMap[ key ] !== undefined ) {
  17903. console.log( "Duplicate point", key );
  17904. }
  17905. allPointsMap[ key ] = i;
  17906. }
  17907. // check all face vertices against all points map
  17908. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17909. face = triangles[ i ];
  17910. for ( f = 0; f < 3; f ++ ) {
  17911. key = face[ f ].x + ":" + face[ f ].y;
  17912. index = allPointsMap[ key ];
  17913. if ( index !== undefined ) {
  17914. face[ f ] = index;
  17915. }
  17916. }
  17917. }
  17918. // check isolated points vertices against all points map
  17919. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17920. face = isolatedPts[ i ];
  17921. for ( f = 0; f < 3; f ++ ) {
  17922. key = face[ f ].x + ":" + face[ f ].y;
  17923. index = allPointsMap[ key ];
  17924. if ( index !== undefined ) {
  17925. face[ f ] = index;
  17926. }
  17927. }
  17928. }
  17929. return triangles.concat( isolatedPts );
  17930. }, // end triangulate shapes
  17931. /*
  17932. triangulate2 : function( pts, holes ) {
  17933. // For use with Poly2Tri.js
  17934. var allpts = pts.concat();
  17935. var shape = [];
  17936. for (var p in pts) {
  17937. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17938. }
  17939. var swctx = new js.poly2tri.SweepContext(shape);
  17940. for (var h in holes) {
  17941. var aHole = holes[h];
  17942. var newHole = []
  17943. for (i in aHole) {
  17944. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17945. allpts.push(aHole[i]);
  17946. }
  17947. swctx.AddHole(newHole);
  17948. }
  17949. var find;
  17950. var findIndexForPt = function (pt) {
  17951. find = new THREE.Vector2(pt.x, pt.y);
  17952. var p;
  17953. for (p=0, pl = allpts.length; p<pl; p++) {
  17954. if (allpts[p].equals(find)) return p;
  17955. }
  17956. return -1;
  17957. };
  17958. // triangulate
  17959. js.poly2tri.sweep.Triangulate(swctx);
  17960. var triangles = swctx.GetTriangles();
  17961. var tr ;
  17962. var facesPts = [];
  17963. for (var t in triangles) {
  17964. tr = triangles[t];
  17965. facesPts.push([
  17966. findIndexForPt(tr.GetPoint(0)),
  17967. findIndexForPt(tr.GetPoint(1)),
  17968. findIndexForPt(tr.GetPoint(2))
  17969. ]);
  17970. }
  17971. // console.log(facesPts);
  17972. // console.log("triangles", triangles.length, triangles);
  17973. // Returns array of faces with 3 element each
  17974. return facesPts;
  17975. },
  17976. */
  17977. isClockWise: function ( pts ) {
  17978. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17979. },
  17980. // Bezier Curves formulas obtained from
  17981. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17982. // Quad Bezier Functions
  17983. b2p0: function ( t, p ) {
  17984. var k = 1 - t;
  17985. return k * k * p;
  17986. },
  17987. b2p1: function ( t, p ) {
  17988. return 2 * ( 1 - t ) * t * p;
  17989. },
  17990. b2p2: function ( t, p ) {
  17991. return t * t * p;
  17992. },
  17993. b2: function ( t, p0, p1, p2 ) {
  17994. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17995. },
  17996. // Cubic Bezier Functions
  17997. b3p0: function ( t, p ) {
  17998. var k = 1 - t;
  17999. return k * k * k * p;
  18000. },
  18001. b3p1: function ( t, p ) {
  18002. var k = 1 - t;
  18003. return 3 * k * k * t * p;
  18004. },
  18005. b3p2: function ( t, p ) {
  18006. var k = 1 - t;
  18007. return 3 * k * t * t * p;
  18008. },
  18009. b3p3: function ( t, p ) {
  18010. return t * t * t * p;
  18011. },
  18012. b3: function ( t, p0, p1, p2, p3 ) {
  18013. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  18014. }
  18015. };
  18016. /**
  18017. * @author mikael emtinger / http://gomo.se/
  18018. */
  18019. THREE.AnimationHandler = (function() {
  18020. var playing = [];
  18021. var library = {};
  18022. var that = {};
  18023. //--- update ---
  18024. that.update = function( deltaTimeMS ) {
  18025. for( var i = 0; i < playing.length; i ++ )
  18026. playing[ i ].update( deltaTimeMS );
  18027. };
  18028. //--- add ---
  18029. that.addToUpdate = function( animation ) {
  18030. if ( playing.indexOf( animation ) === -1 )
  18031. playing.push( animation );
  18032. };
  18033. //--- remove ---
  18034. that.removeFromUpdate = function( animation ) {
  18035. var index = playing.indexOf( animation );
  18036. if( index !== -1 )
  18037. playing.splice( index, 1 );
  18038. };
  18039. //--- add ---
  18040. that.add = function( data ) {
  18041. if ( library[ data.name ] !== undefined )
  18042. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18043. library[ data.name ] = data;
  18044. initData( data );
  18045. };
  18046. //--- get ---
  18047. that.get = function( name ) {
  18048. if ( typeof name === "string" ) {
  18049. if ( library[ name ] ) {
  18050. return library[ name ];
  18051. } else {
  18052. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  18053. return null;
  18054. }
  18055. } else {
  18056. // todo: add simple tween library
  18057. }
  18058. };
  18059. //--- parse ---
  18060. that.parse = function( root ) {
  18061. // setup hierarchy
  18062. var hierarchy = [];
  18063. if ( root instanceof THREE.SkinnedMesh ) {
  18064. for( var b = 0; b < root.bones.length; b++ ) {
  18065. hierarchy.push( root.bones[ b ] );
  18066. }
  18067. } else {
  18068. parseRecurseHierarchy( root, hierarchy );
  18069. }
  18070. return hierarchy;
  18071. };
  18072. var parseRecurseHierarchy = function( root, hierarchy ) {
  18073. hierarchy.push( root );
  18074. for( var c = 0; c < root.children.length; c++ )
  18075. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18076. }
  18077. //--- init data ---
  18078. var initData = function( data ) {
  18079. if( data.initialized === true )
  18080. return;
  18081. // loop through all keys
  18082. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  18083. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18084. // remove minus times
  18085. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  18086. data.hierarchy[ h ].keys[ k ].time = 0;
  18087. // create quaternions
  18088. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18089. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18090. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18091. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  18092. }
  18093. }
  18094. // prepare morph target keys
  18095. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18096. // get all used
  18097. var usedMorphTargets = {};
  18098. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18099. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18100. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18101. usedMorphTargets[ morphTargetName ] = -1;
  18102. }
  18103. }
  18104. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18105. // set all used on all frames
  18106. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18107. var influences = {};
  18108. for ( var morphTargetName in usedMorphTargets ) {
  18109. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18110. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18111. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18112. break;
  18113. }
  18114. }
  18115. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18116. influences[ morphTargetName ] = 0;
  18117. }
  18118. }
  18119. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18120. }
  18121. }
  18122. // remove all keys that are on the same time
  18123. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18124. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18125. data.hierarchy[ h ].keys.splice( k, 1 );
  18126. k --;
  18127. }
  18128. }
  18129. // set index
  18130. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18131. data.hierarchy[ h ].keys[ k ].index = k;
  18132. }
  18133. }
  18134. // JIT
  18135. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  18136. data.JIT = {};
  18137. data.JIT.hierarchy = [];
  18138. for( var h = 0; h < data.hierarchy.length; h ++ )
  18139. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  18140. // done
  18141. data.initialized = true;
  18142. };
  18143. // interpolation types
  18144. that.LINEAR = 0;
  18145. that.CATMULLROM = 1;
  18146. that.CATMULLROM_FORWARD = 2;
  18147. return that;
  18148. }());
  18149. /**
  18150. * @author mikael emtinger / http://gomo.se/
  18151. * @author mrdoob / http://mrdoob.com/
  18152. * @author alteredq / http://alteredqualia.com/
  18153. */
  18154. THREE.Animation = function ( root, name, interpolationType ) {
  18155. this.root = root;
  18156. this.data = THREE.AnimationHandler.get( name );
  18157. this.hierarchy = THREE.AnimationHandler.parse( root );
  18158. this.currentTime = 0;
  18159. this.timeScale = 1;
  18160. this.isPlaying = false;
  18161. this.isPaused = true;
  18162. this.loop = true;
  18163. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  18164. this.points = [];
  18165. this.target = new THREE.Vector3();
  18166. };
  18167. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  18168. if ( this.isPlaying === false ) {
  18169. this.isPlaying = true;
  18170. this.loop = loop !== undefined ? loop : true;
  18171. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18172. // reset key cache
  18173. var h, hl = this.hierarchy.length,
  18174. object;
  18175. for ( h = 0; h < hl; h ++ ) {
  18176. object = this.hierarchy[ h ];
  18177. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18178. object.useQuaternion = true;
  18179. }
  18180. object.matrixAutoUpdate = true;
  18181. if ( object.animationCache === undefined ) {
  18182. object.animationCache = {};
  18183. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  18184. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  18185. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18186. }
  18187. var prevKey = object.animationCache.prevKey;
  18188. var nextKey = object.animationCache.nextKey;
  18189. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  18190. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  18191. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  18192. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  18193. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  18194. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  18195. }
  18196. this.update( 0 );
  18197. }
  18198. this.isPaused = false;
  18199. THREE.AnimationHandler.addToUpdate( this );
  18200. };
  18201. THREE.Animation.prototype.pause = function() {
  18202. if ( this.isPaused === true ) {
  18203. THREE.AnimationHandler.addToUpdate( this );
  18204. } else {
  18205. THREE.AnimationHandler.removeFromUpdate( this );
  18206. }
  18207. this.isPaused = !this.isPaused;
  18208. };
  18209. THREE.Animation.prototype.stop = function() {
  18210. this.isPlaying = false;
  18211. this.isPaused = false;
  18212. THREE.AnimationHandler.removeFromUpdate( this );
  18213. };
  18214. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  18215. // early out
  18216. if ( this.isPlaying === false ) return;
  18217. // vars
  18218. var types = [ "pos", "rot", "scl" ];
  18219. var type;
  18220. var scale;
  18221. var vector;
  18222. var prevXYZ, nextXYZ;
  18223. var prevKey, nextKey;
  18224. var object;
  18225. var animationCache;
  18226. var frame;
  18227. var JIThierarchy = this.data.JIT.hierarchy;
  18228. var currentTime, unloopedCurrentTime;
  18229. var currentPoint, forwardPoint, angle;
  18230. this.currentTime += deltaTimeMS * this.timeScale;
  18231. unloopedCurrentTime = this.currentTime;
  18232. currentTime = this.currentTime = this.currentTime % this.data.length;
  18233. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18234. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18235. object = this.hierarchy[ h ];
  18236. animationCache = object.animationCache;
  18237. // loop through pos/rot/scl
  18238. for ( var t = 0; t < 3; t ++ ) {
  18239. // get keys
  18240. type = types[ t ];
  18241. prevKey = animationCache.prevKey[ type ];
  18242. nextKey = animationCache.nextKey[ type ];
  18243. // switch keys?
  18244. if ( nextKey.time <= unloopedCurrentTime ) {
  18245. // did we loop?
  18246. if ( currentTime < unloopedCurrentTime ) {
  18247. if ( this.loop ) {
  18248. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18249. nextKey = this.getNextKeyWith( type, h, 1 );
  18250. while( nextKey.time < currentTime ) {
  18251. prevKey = nextKey;
  18252. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18253. }
  18254. } else {
  18255. this.stop();
  18256. return;
  18257. }
  18258. } else {
  18259. do {
  18260. prevKey = nextKey;
  18261. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18262. } while( nextKey.time < currentTime )
  18263. }
  18264. animationCache.prevKey[ type ] = prevKey;
  18265. animationCache.nextKey[ type ] = nextKey;
  18266. }
  18267. object.matrixAutoUpdate = true;
  18268. object.matrixWorldNeedsUpdate = true;
  18269. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18270. prevXYZ = prevKey[ type ];
  18271. nextXYZ = nextKey[ type ];
  18272. // check scale error
  18273. if ( scale < 0 || scale > 1 ) {
  18274. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18275. scale = scale < 0 ? 0 : 1;
  18276. }
  18277. // interpolate
  18278. if ( type === "pos" ) {
  18279. vector = object.position;
  18280. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18281. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18282. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18283. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18284. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18285. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18286. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18287. this.points[ 1 ] = prevXYZ;
  18288. this.points[ 2 ] = nextXYZ;
  18289. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18290. scale = scale * 0.33 + 0.33;
  18291. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18292. vector.x = currentPoint[ 0 ];
  18293. vector.y = currentPoint[ 1 ];
  18294. vector.z = currentPoint[ 2 ];
  18295. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18296. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18297. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18298. this.target.subSelf( vector );
  18299. this.target.y = 0;
  18300. this.target.normalize();
  18301. angle = Math.atan2( this.target.x, this.target.z );
  18302. object.rotation.set( 0, angle, 0 );
  18303. }
  18304. }
  18305. } else if ( type === "rot" ) {
  18306. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18307. } else if ( type === "scl" ) {
  18308. vector = object.scale;
  18309. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18310. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18311. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18312. }
  18313. }
  18314. }
  18315. };
  18316. // Catmull-Rom spline
  18317. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18318. var c = [], v3 = [],
  18319. point, intPoint, weight, w2, w3,
  18320. pa, pb, pc, pd;
  18321. point = ( points.length - 1 ) * scale;
  18322. intPoint = Math.floor( point );
  18323. weight = point - intPoint;
  18324. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18325. c[ 1 ] = intPoint;
  18326. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18327. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18328. pa = points[ c[ 0 ] ];
  18329. pb = points[ c[ 1 ] ];
  18330. pc = points[ c[ 2 ] ];
  18331. pd = points[ c[ 3 ] ];
  18332. w2 = weight * weight;
  18333. w3 = weight * w2;
  18334. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18335. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18336. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18337. return v3;
  18338. };
  18339. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18340. var v0 = ( p2 - p0 ) * 0.5,
  18341. v1 = ( p3 - p1 ) * 0.5;
  18342. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18343. };
  18344. // Get next key with
  18345. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18346. var keys = this.data.hierarchy[ h ].keys;
  18347. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18348. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18349. key = key < keys.length - 1 ? key : keys.length - 1;
  18350. } else {
  18351. key = key % keys.length;
  18352. }
  18353. for ( ; key < keys.length; key++ ) {
  18354. if ( keys[ key ][ type ] !== undefined ) {
  18355. return keys[ key ];
  18356. }
  18357. }
  18358. return this.data.hierarchy[ h ].keys[ 0 ];
  18359. };
  18360. // Get previous key with
  18361. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18362. var keys = this.data.hierarchy[ h ].keys;
  18363. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18364. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18365. key = key > 0 ? key : 0;
  18366. } else {
  18367. key = key >= 0 ? key : key + keys.length;
  18368. }
  18369. for ( ; key >= 0; key -- ) {
  18370. if ( keys[ key ][ type ] !== undefined ) {
  18371. return keys[ key ];
  18372. }
  18373. }
  18374. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18375. };
  18376. /**
  18377. * @author mikael emtinger / http://gomo.se/
  18378. * @author mrdoob / http://mrdoob.com/
  18379. * @author alteredq / http://alteredqualia.com/
  18380. * @author khang duong
  18381. * @author erik kitson
  18382. */
  18383. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18384. this.root = root;
  18385. this.data = THREE.AnimationHandler.get( data );
  18386. this.hierarchy = THREE.AnimationHandler.parse( root );
  18387. this.currentTime = 0;
  18388. this.timeScale = 0.001;
  18389. this.isPlaying = false;
  18390. this.isPaused = true;
  18391. this.loop = true;
  18392. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18393. // initialize to first keyframes
  18394. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18395. var keys = this.data.hierarchy[h].keys,
  18396. sids = this.data.hierarchy[h].sids,
  18397. obj = this.hierarchy[h];
  18398. if ( keys.length && sids ) {
  18399. for ( var s = 0; s < sids.length; s++ ) {
  18400. var sid = sids[ s ],
  18401. next = this.getNextKeyWith( sid, h, 0 );
  18402. if ( next ) {
  18403. next.apply( sid );
  18404. }
  18405. }
  18406. obj.matrixAutoUpdate = false;
  18407. this.data.hierarchy[h].node.updateMatrix();
  18408. obj.matrixWorldNeedsUpdate = true;
  18409. }
  18410. }
  18411. };
  18412. // Play
  18413. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18414. if( !this.isPlaying ) {
  18415. this.isPlaying = true;
  18416. this.loop = loop !== undefined ? loop : true;
  18417. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18418. this.startTimeMs = startTimeMS;
  18419. this.startTime = 10000000;
  18420. this.endTime = -this.startTime;
  18421. // reset key cache
  18422. var h, hl = this.hierarchy.length,
  18423. object,
  18424. node;
  18425. for ( h = 0; h < hl; h++ ) {
  18426. object = this.hierarchy[ h ];
  18427. node = this.data.hierarchy[ h ];
  18428. object.useQuaternion = true;
  18429. if ( node.animationCache === undefined ) {
  18430. node.animationCache = {};
  18431. node.animationCache.prevKey = null;
  18432. node.animationCache.nextKey = null;
  18433. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18434. }
  18435. var keys = this.data.hierarchy[h].keys;
  18436. if (keys.length) {
  18437. node.animationCache.prevKey = keys[ 0 ];
  18438. node.animationCache.nextKey = keys[ 1 ];
  18439. this.startTime = Math.min( keys[0].time, this.startTime );
  18440. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18441. }
  18442. }
  18443. this.update( 0 );
  18444. }
  18445. this.isPaused = false;
  18446. THREE.AnimationHandler.addToUpdate( this );
  18447. };
  18448. // Pause
  18449. THREE.KeyFrameAnimation.prototype.pause = function() {
  18450. if( this.isPaused ) {
  18451. THREE.AnimationHandler.addToUpdate( this );
  18452. } else {
  18453. THREE.AnimationHandler.removeFromUpdate( this );
  18454. }
  18455. this.isPaused = !this.isPaused;
  18456. };
  18457. // Stop
  18458. THREE.KeyFrameAnimation.prototype.stop = function() {
  18459. this.isPlaying = false;
  18460. this.isPaused = false;
  18461. THREE.AnimationHandler.removeFromUpdate( this );
  18462. // reset JIT matrix and remove cache
  18463. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18464. var obj = this.hierarchy[ h ];
  18465. var node = this.data.hierarchy[ h ];
  18466. if ( node.animationCache !== undefined ) {
  18467. var original = node.animationCache.originalMatrix;
  18468. if( obj instanceof THREE.Bone ) {
  18469. original.copy( obj.skinMatrix );
  18470. obj.skinMatrix = original;
  18471. } else {
  18472. original.copy( obj.matrix );
  18473. obj.matrix = original;
  18474. }
  18475. delete node.animationCache;
  18476. }
  18477. }
  18478. };
  18479. // Update
  18480. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18481. // early out
  18482. if( !this.isPlaying ) return;
  18483. // vars
  18484. var prevKey, nextKey;
  18485. var object;
  18486. var node;
  18487. var frame;
  18488. var JIThierarchy = this.data.JIT.hierarchy;
  18489. var currentTime, unloopedCurrentTime;
  18490. var looped;
  18491. // update
  18492. this.currentTime += deltaTimeMS * this.timeScale;
  18493. unloopedCurrentTime = this.currentTime;
  18494. currentTime = this.currentTime = this.currentTime % this.data.length;
  18495. // if looped around, the current time should be based on the startTime
  18496. if ( currentTime < this.startTimeMs ) {
  18497. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18498. }
  18499. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18500. looped = currentTime < unloopedCurrentTime;
  18501. if ( looped && !this.loop ) {
  18502. // Set the animation to the last keyframes and stop
  18503. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18504. var keys = this.data.hierarchy[h].keys,
  18505. sids = this.data.hierarchy[h].sids,
  18506. end = keys.length-1,
  18507. obj = this.hierarchy[h];
  18508. if ( keys.length ) {
  18509. for ( var s = 0; s < sids.length; s++ ) {
  18510. var sid = sids[ s ],
  18511. prev = this.getPrevKeyWith( sid, h, end );
  18512. if ( prev ) {
  18513. prev.apply( sid );
  18514. }
  18515. }
  18516. this.data.hierarchy[h].node.updateMatrix();
  18517. obj.matrixWorldNeedsUpdate = true;
  18518. }
  18519. }
  18520. this.stop();
  18521. return;
  18522. }
  18523. // check pre-infinity
  18524. if ( currentTime < this.startTime ) {
  18525. return;
  18526. }
  18527. // update
  18528. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18529. object = this.hierarchy[ h ];
  18530. node = this.data.hierarchy[ h ];
  18531. var keys = node.keys,
  18532. animationCache = node.animationCache;
  18533. // use JIT?
  18534. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18535. if( object instanceof THREE.Bone ) {
  18536. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18537. object.matrixWorldNeedsUpdate = false;
  18538. } else {
  18539. object.matrix = JIThierarchy[ h ][ frame ];
  18540. object.matrixWorldNeedsUpdate = true;
  18541. }
  18542. // use interpolation
  18543. } else if ( keys.length ) {
  18544. // make sure so original matrix and not JIT matrix is set
  18545. if ( this.JITCompile && animationCache ) {
  18546. if( object instanceof THREE.Bone ) {
  18547. object.skinMatrix = animationCache.originalMatrix;
  18548. } else {
  18549. object.matrix = animationCache.originalMatrix;
  18550. }
  18551. }
  18552. prevKey = animationCache.prevKey;
  18553. nextKey = animationCache.nextKey;
  18554. if ( prevKey && nextKey ) {
  18555. // switch keys?
  18556. if ( nextKey.time <= unloopedCurrentTime ) {
  18557. // did we loop?
  18558. if ( looped && this.loop ) {
  18559. prevKey = keys[ 0 ];
  18560. nextKey = keys[ 1 ];
  18561. while ( nextKey.time < currentTime ) {
  18562. prevKey = nextKey;
  18563. nextKey = keys[ prevKey.index + 1 ];
  18564. }
  18565. } else if ( !looped ) {
  18566. var lastIndex = keys.length - 1;
  18567. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18568. prevKey = nextKey;
  18569. nextKey = keys[ prevKey.index + 1 ];
  18570. }
  18571. }
  18572. animationCache.prevKey = prevKey;
  18573. animationCache.nextKey = nextKey;
  18574. }
  18575. if(nextKey.time >= currentTime)
  18576. prevKey.interpolate( nextKey, currentTime );
  18577. else
  18578. prevKey.interpolate( nextKey, nextKey.time);
  18579. }
  18580. this.data.hierarchy[h].node.updateMatrix();
  18581. object.matrixWorldNeedsUpdate = true;
  18582. }
  18583. }
  18584. // update JIT?
  18585. if ( this.JITCompile ) {
  18586. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18587. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18588. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18589. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18590. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18591. } else {
  18592. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18593. }
  18594. }
  18595. }
  18596. }
  18597. };
  18598. // Get next key with
  18599. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18600. var keys = this.data.hierarchy[ h ].keys;
  18601. key = key % keys.length;
  18602. for ( ; key < keys.length; key++ ) {
  18603. if ( keys[ key ].hasTarget( sid ) ) {
  18604. return keys[ key ];
  18605. }
  18606. }
  18607. return keys[ 0 ];
  18608. };
  18609. // Get previous key with
  18610. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18611. var keys = this.data.hierarchy[ h ].keys;
  18612. key = key >= 0 ? key : key + keys.length;
  18613. for ( ; key >= 0; key-- ) {
  18614. if ( keys[ key ].hasTarget( sid ) ) {
  18615. return keys[ key ];
  18616. }
  18617. }
  18618. return keys[ keys.length - 1 ];
  18619. };
  18620. /**
  18621. * Camera for rendering cube maps
  18622. * - renders scene into axis-aligned cube
  18623. *
  18624. * @author alteredq / http://alteredqualia.com/
  18625. */
  18626. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18627. THREE.Object3D.call( this );
  18628. var fov = 90, aspect = 1;
  18629. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18630. cameraPX.up.set( 0, -1, 0 );
  18631. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18632. this.add( cameraPX );
  18633. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18634. cameraNX.up.set( 0, -1, 0 );
  18635. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18636. this.add( cameraNX );
  18637. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18638. cameraPY.up.set( 0, 0, 1 );
  18639. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18640. this.add( cameraPY );
  18641. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18642. cameraNY.up.set( 0, 0, -1 );
  18643. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18644. this.add( cameraNY );
  18645. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18646. cameraPZ.up.set( 0, -1, 0 );
  18647. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18648. this.add( cameraPZ );
  18649. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18650. cameraNZ.up.set( 0, -1, 0 );
  18651. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18652. this.add( cameraNZ );
  18653. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18654. this.updateCubeMap = function ( renderer, scene ) {
  18655. var renderTarget = this.renderTarget;
  18656. var generateMipmaps = renderTarget.generateMipmaps;
  18657. renderTarget.generateMipmaps = false;
  18658. renderTarget.activeCubeFace = 0;
  18659. renderer.render( scene, cameraPX, renderTarget );
  18660. renderTarget.activeCubeFace = 1;
  18661. renderer.render( scene, cameraNX, renderTarget );
  18662. renderTarget.activeCubeFace = 2;
  18663. renderer.render( scene, cameraPY, renderTarget );
  18664. renderTarget.activeCubeFace = 3;
  18665. renderer.render( scene, cameraNY, renderTarget );
  18666. renderTarget.activeCubeFace = 4;
  18667. renderer.render( scene, cameraPZ, renderTarget );
  18668. renderTarget.generateMipmaps = generateMipmaps;
  18669. renderTarget.activeCubeFace = 5;
  18670. renderer.render( scene, cameraNZ, renderTarget );
  18671. };
  18672. };
  18673. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18674. /*
  18675. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18676. *
  18677. * A general perpose camera, for setting FOV, Lens Focal Length,
  18678. * and switching between perspective and orthographic views easily.
  18679. * Use this only if you do not wish to manage
  18680. * both a Orthographic and Perspective Camera
  18681. *
  18682. */
  18683. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18684. THREE.Camera.call( this );
  18685. this.fov = fov;
  18686. this.left = -width / 2;
  18687. this.right = width / 2
  18688. this.top = height / 2;
  18689. this.bottom = -height / 2;
  18690. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18691. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18692. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18693. this.zoom = 1;
  18694. this.toPerspective();
  18695. var aspect = width/height;
  18696. };
  18697. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18698. THREE.CombinedCamera.prototype.toPerspective = function () {
  18699. // Switches to the Perspective Camera
  18700. this.near = this.cameraP.near;
  18701. this.far = this.cameraP.far;
  18702. this.cameraP.fov = this.fov / this.zoom ;
  18703. this.cameraP.updateProjectionMatrix();
  18704. this.projectionMatrix = this.cameraP.projectionMatrix;
  18705. this.inPerspectiveMode = true;
  18706. this.inOrthographicMode = false;
  18707. };
  18708. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18709. // Switches to the Orthographic camera estimating viewport from Perspective
  18710. var fov = this.fov;
  18711. var aspect = this.cameraP.aspect;
  18712. var near = this.cameraP.near;
  18713. var far = this.cameraP.far;
  18714. // The size that we set is the mid plane of the viewing frustum
  18715. var hyperfocus = ( near + far ) / 2;
  18716. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18717. var planeHeight = 2 * halfHeight;
  18718. var planeWidth = planeHeight * aspect;
  18719. var halfWidth = planeWidth / 2;
  18720. halfHeight /= this.zoom;
  18721. halfWidth /= this.zoom;
  18722. this.cameraO.left = -halfWidth;
  18723. this.cameraO.right = halfWidth;
  18724. this.cameraO.top = halfHeight;
  18725. this.cameraO.bottom = -halfHeight;
  18726. // this.cameraO.left = -farHalfWidth;
  18727. // this.cameraO.right = farHalfWidth;
  18728. // this.cameraO.top = farHalfHeight;
  18729. // this.cameraO.bottom = -farHalfHeight;
  18730. // this.cameraO.left = this.left / this.zoom;
  18731. // this.cameraO.right = this.right / this.zoom;
  18732. // this.cameraO.top = this.top / this.zoom;
  18733. // this.cameraO.bottom = this.bottom / this.zoom;
  18734. this.cameraO.updateProjectionMatrix();
  18735. this.near = this.cameraO.near;
  18736. this.far = this.cameraO.far;
  18737. this.projectionMatrix = this.cameraO.projectionMatrix;
  18738. this.inPerspectiveMode = false;
  18739. this.inOrthographicMode = true;
  18740. };
  18741. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18742. this.cameraP.aspect = width / height;
  18743. this.left = -width / 2;
  18744. this.right = width / 2
  18745. this.top = height / 2;
  18746. this.bottom = -height / 2;
  18747. };
  18748. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18749. this.fov = fov;
  18750. if ( this.inPerspectiveMode ) {
  18751. this.toPerspective();
  18752. } else {
  18753. this.toOrthographic();
  18754. }
  18755. };
  18756. // For mantaining similar API with PerspectiveCamera
  18757. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18758. if ( this.inPerspectiveMode ) {
  18759. this.toPerspective();
  18760. } else {
  18761. this.toPerspective();
  18762. this.toOrthographic();
  18763. }
  18764. };
  18765. /*
  18766. * Uses Focal Length (in mm) to estimate and set FOV
  18767. * 35mm (fullframe) camera is used if frame size is not specified;
  18768. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18769. */
  18770. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18771. if ( frameHeight === undefined ) frameHeight = 24;
  18772. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18773. this.setFov( fov );
  18774. return fov;
  18775. };
  18776. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18777. this.zoom = zoom;
  18778. if ( this.inPerspectiveMode ) {
  18779. this.toPerspective();
  18780. } else {
  18781. this.toOrthographic();
  18782. }
  18783. };
  18784. THREE.CombinedCamera.prototype.toFrontView = function() {
  18785. this.rotation.x = 0;
  18786. this.rotation.y = 0;
  18787. this.rotation.z = 0;
  18788. // should we be modifing the matrix instead?
  18789. this.rotationAutoUpdate = false;
  18790. };
  18791. THREE.CombinedCamera.prototype.toBackView = function() {
  18792. this.rotation.x = 0;
  18793. this.rotation.y = Math.PI;
  18794. this.rotation.z = 0;
  18795. this.rotationAutoUpdate = false;
  18796. };
  18797. THREE.CombinedCamera.prototype.toLeftView = function() {
  18798. this.rotation.x = 0;
  18799. this.rotation.y = - Math.PI / 2;
  18800. this.rotation.z = 0;
  18801. this.rotationAutoUpdate = false;
  18802. };
  18803. THREE.CombinedCamera.prototype.toRightView = function() {
  18804. this.rotation.x = 0;
  18805. this.rotation.y = Math.PI / 2;
  18806. this.rotation.z = 0;
  18807. this.rotationAutoUpdate = false;
  18808. };
  18809. THREE.CombinedCamera.prototype.toTopView = function() {
  18810. this.rotation.x = - Math.PI / 2;
  18811. this.rotation.y = 0;
  18812. this.rotation.z = 0;
  18813. this.rotationAutoUpdate = false;
  18814. };
  18815. THREE.CombinedCamera.prototype.toBottomView = function() {
  18816. this.rotation.x = Math.PI / 2;
  18817. this.rotation.y = 0;
  18818. this.rotation.z = 0;
  18819. this.rotationAutoUpdate = false;
  18820. };
  18821. /**
  18822. * @author alteredq / http://alteredqualia.com/
  18823. *
  18824. * - 3d asterisk shape (for line pieces THREE.Line)
  18825. */
  18826. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  18827. THREE.Geometry.call( this );
  18828. var sd = innerRadius;
  18829. var ed = outerRadius;
  18830. var sd2 = 0.707 * sd;
  18831. var ed2 = 0.707 * ed;
  18832. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  18833. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  18834. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  18835. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  18836. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  18837. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  18838. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  18839. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  18840. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  18841. ];
  18842. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  18843. var x = rays[ i ][ 0 ];
  18844. var y = rays[ i ][ 1 ];
  18845. var z = rays[ i ][ 2 ];
  18846. this.vertices.push( new THREE.Vector3( x, y, z ) );
  18847. }
  18848. };
  18849. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  18850. * @author hughes
  18851. */
  18852. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18853. THREE.Geometry.call( this );
  18854. radius = radius || 50;
  18855. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18856. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18857. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18858. var i, uvs = [],
  18859. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18860. this.vertices.push(center);
  18861. uvs.push( centerUV );
  18862. for ( i = 0; i <= segments; i ++ ) {
  18863. var vertex = new THREE.Vector3();
  18864. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  18865. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  18866. this.vertices.push( vertex );
  18867. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  18868. }
  18869. var n = new THREE.Vector3( 0, 0, -1 );
  18870. for ( i = 1; i <= segments; i ++ ) {
  18871. var v1 = i;
  18872. var v2 = i + 1 ;
  18873. var v3 = 0;
  18874. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18875. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18876. }
  18877. this.computeCentroids();
  18878. this.computeFaceNormals();
  18879. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18880. };
  18881. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18882. /**
  18883. * @author mrdoob / http://mrdoob.com/
  18884. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18885. */
  18886. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18887. THREE.Geometry.call( this );
  18888. var scope = this;
  18889. this.width = width;
  18890. this.height = height;
  18891. this.depth = depth;
  18892. this.widthSegments = widthSegments || 1;
  18893. this.heightSegments = heightSegments || 1;
  18894. this.depthSegments = depthSegments || 1;
  18895. var width_half = this.width / 2;
  18896. var height_half = this.height / 2;
  18897. var depth_half = this.depth / 2;
  18898. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18899. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18900. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18901. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18902. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18903. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18904. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18905. var w, ix, iy,
  18906. gridX = scope.widthSegments,
  18907. gridY = scope.heightSegments,
  18908. width_half = width / 2,
  18909. height_half = height / 2,
  18910. offset = scope.vertices.length;
  18911. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18912. w = 'z';
  18913. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18914. w = 'y';
  18915. gridY = scope.depthSegments;
  18916. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18917. w = 'x';
  18918. gridX = scope.depthSegments;
  18919. }
  18920. var gridX1 = gridX + 1,
  18921. gridY1 = gridY + 1,
  18922. segment_width = width / gridX,
  18923. segment_height = height / gridY,
  18924. normal = new THREE.Vector3();
  18925. normal[ w ] = depth > 0 ? 1 : - 1;
  18926. for ( iy = 0; iy < gridY1; iy ++ ) {
  18927. for ( ix = 0; ix < gridX1; ix ++ ) {
  18928. var vector = new THREE.Vector3();
  18929. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18930. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18931. vector[ w ] = depth;
  18932. scope.vertices.push( vector );
  18933. }
  18934. }
  18935. for ( iy = 0; iy < gridY; iy++ ) {
  18936. for ( ix = 0; ix < gridX; ix++ ) {
  18937. var a = ix + gridX1 * iy;
  18938. var b = ix + gridX1 * ( iy + 1 );
  18939. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18940. var d = ( ix + 1 ) + gridX1 * iy;
  18941. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18942. face.normal.copy( normal );
  18943. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18944. face.materialIndex = materialIndex;
  18945. scope.faces.push( face );
  18946. scope.faceVertexUvs[ 0 ].push( [
  18947. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18948. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18949. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18950. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18951. ] );
  18952. }
  18953. }
  18954. }
  18955. this.computeCentroids();
  18956. this.mergeVertices();
  18957. };
  18958. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18959. /**
  18960. * @author mrdoob / http://mrdoob.com/
  18961. */
  18962. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18963. THREE.Geometry.call( this );
  18964. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18965. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18966. height = height !== undefined ? height : 100;
  18967. var heightHalf = height / 2;
  18968. var segmentsX = radiusSegments || 8;
  18969. var segmentsY = heightSegments || 1;
  18970. var x, y, vertices = [], uvs = [];
  18971. for ( y = 0; y <= segmentsY; y ++ ) {
  18972. var verticesRow = [];
  18973. var uvsRow = [];
  18974. var v = y / segmentsY;
  18975. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18976. for ( x = 0; x <= segmentsX; x ++ ) {
  18977. var u = x / segmentsX;
  18978. var vertex = new THREE.Vector3();
  18979. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18980. vertex.y = - v * height + heightHalf;
  18981. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18982. this.vertices.push( vertex );
  18983. verticesRow.push( this.vertices.length - 1 );
  18984. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18985. }
  18986. vertices.push( verticesRow );
  18987. uvs.push( uvsRow );
  18988. }
  18989. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18990. var na, nb;
  18991. for ( x = 0; x < segmentsX; x ++ ) {
  18992. if ( radiusTop !== 0 ) {
  18993. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18994. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18995. } else {
  18996. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18997. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18998. }
  18999. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19000. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19001. for ( y = 0; y < segmentsY; y ++ ) {
  19002. var v1 = vertices[ y ][ x ];
  19003. var v2 = vertices[ y + 1 ][ x ];
  19004. var v3 = vertices[ y + 1 ][ x + 1 ];
  19005. var v4 = vertices[ y ][ x + 1 ];
  19006. var n1 = na.clone();
  19007. var n2 = na.clone();
  19008. var n3 = nb.clone();
  19009. var n4 = nb.clone();
  19010. var uv1 = uvs[ y ][ x ].clone();
  19011. var uv2 = uvs[ y + 1 ][ x ].clone();
  19012. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19013. var uv4 = uvs[ y ][ x + 1 ].clone();
  19014. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19015. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19016. }
  19017. }
  19018. // top cap
  19019. if ( !openEnded && radiusTop > 0 ) {
  19020. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19021. for ( x = 0; x < segmentsX; x ++ ) {
  19022. var v1 = vertices[ 0 ][ x ];
  19023. var v2 = vertices[ 0 ][ x + 1 ];
  19024. var v3 = this.vertices.length - 1;
  19025. var n1 = new THREE.Vector3( 0, 1, 0 );
  19026. var n2 = new THREE.Vector3( 0, 1, 0 );
  19027. var n3 = new THREE.Vector3( 0, 1, 0 );
  19028. var uv1 = uvs[ 0 ][ x ].clone();
  19029. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19030. var uv3 = new THREE.Vector2( uv2.u, 0 );
  19031. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19032. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19033. }
  19034. }
  19035. // bottom cap
  19036. if ( !openEnded && radiusBottom > 0 ) {
  19037. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19038. for ( x = 0; x < segmentsX; x ++ ) {
  19039. var v1 = vertices[ y ][ x + 1 ];
  19040. var v2 = vertices[ y ][ x ];
  19041. var v3 = this.vertices.length - 1;
  19042. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19043. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19044. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19045. var uv1 = uvs[ y ][ x + 1 ].clone();
  19046. var uv2 = uvs[ y ][ x ].clone();
  19047. var uv3 = new THREE.Vector2( uv2.u, 1 );
  19048. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19049. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19050. }
  19051. }
  19052. this.computeCentroids();
  19053. this.computeFaceNormals();
  19054. }
  19055. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19056. /**
  19057. * @author zz85 / http://www.lab4games.net/zz85/blog
  19058. *
  19059. * Creates extruded geometry from a path shape.
  19060. *
  19061. * parameters = {
  19062. *
  19063. * size: <float>, // size of the text
  19064. * height: <float>, // thickness to extrude text
  19065. * curveSegments: <int>, // number of points on the curves
  19066. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19067. * amount: <int>, // Amount
  19068. *
  19069. * bevelEnabled: <bool>, // turn on bevel
  19070. * bevelThickness: <float>, // how deep into text bevel goes
  19071. * bevelSize: <float>, // how far from text outline is bevel
  19072. * bevelSegments: <int>, // number of bevel layers
  19073. *
  19074. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19075. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19076. *
  19077. * material: <int> // material index for front and back faces
  19078. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19079. * uvGenerator: <Object> // object that provides UV generator functions
  19080. *
  19081. * }
  19082. **/
  19083. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19084. if ( typeof( shapes ) === "undefined" ) {
  19085. shapes = [];
  19086. return;
  19087. }
  19088. THREE.Geometry.call( this );
  19089. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19090. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19091. this.addShapeList( shapes, options );
  19092. this.computeCentroids();
  19093. this.computeFaceNormals();
  19094. // can't really use automatic vertex normals
  19095. // as then front and back sides get smoothed too
  19096. // should do separate smoothing just for sides
  19097. //this.computeVertexNormals();
  19098. //console.log( "took", ( Date.now() - startTime ) );
  19099. };
  19100. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19101. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19102. var sl = shapes.length;
  19103. for ( var s = 0; s < sl; s ++ ) {
  19104. var shape = shapes[ s ];
  19105. this.addShape( shape, options );
  19106. }
  19107. };
  19108. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19109. var amount = options.amount !== undefined ? options.amount : 100;
  19110. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19111. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19112. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19113. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19114. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19115. var steps = options.steps !== undefined ? options.steps : 1;
  19116. var extrudePath = options.extrudePath;
  19117. var extrudePts, extrudeByPath = false;
  19118. var material = options.material;
  19119. var extrudeMaterial = options.extrudeMaterial;
  19120. // Use default WorldUVGenerator if no UV generators are specified.
  19121. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19122. var shapebb = this.shapebb;
  19123. //shapebb = shape.getBoundingBox();
  19124. var splineTube, binormal, normal, position2;
  19125. if ( extrudePath ) {
  19126. extrudePts = extrudePath.getSpacedPoints( steps );
  19127. extrudeByPath = true;
  19128. bevelEnabled = false; // bevels not supported for path extrusion
  19129. // SETUP TNB variables
  19130. // Reuse TNB from TubeGeomtry for now.
  19131. // TODO1 - have a .isClosed in spline?
  19132. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19133. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19134. binormal = new THREE.Vector3();
  19135. normal = new THREE.Vector3();
  19136. position2 = new THREE.Vector3();
  19137. }
  19138. // Safeguards if bevels are not enabled
  19139. if ( ! bevelEnabled ) {
  19140. bevelSegments = 0;
  19141. bevelThickness = 0;
  19142. bevelSize = 0;
  19143. }
  19144. // Variables initalization
  19145. var ahole, h, hl; // looping of holes
  19146. var scope = this;
  19147. var bevelPoints = [];
  19148. var shapesOffset = this.vertices.length;
  19149. var shapePoints = shape.extractPoints( curveSegments );
  19150. var vertices = shapePoints.shape;
  19151. var holes = shapePoints.holes;
  19152. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19153. if ( reverse ) {
  19154. vertices = vertices.reverse();
  19155. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19156. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19157. ahole = holes[ h ];
  19158. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19159. holes[ h ] = ahole.reverse();
  19160. }
  19161. }
  19162. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19163. }
  19164. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19165. /* Vertices */
  19166. var contour = vertices; // vertices has all points but contour has only points of circumference
  19167. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19168. ahole = holes[ h ];
  19169. vertices = vertices.concat( ahole );
  19170. }
  19171. function scalePt2 ( pt, vec, size ) {
  19172. if ( !vec ) console.log( "die" );
  19173. return vec.clone().multiplyScalar( size ).addSelf( pt );
  19174. }
  19175. var b, bs, t, z,
  19176. vert, vlen = vertices.length,
  19177. face, flen = faces.length,
  19178. cont, clen = contour.length;
  19179. // Find directions for point movement
  19180. var RAD_TO_DEGREES = 180 / Math.PI;
  19181. function getBevelVec( pt_i, pt_j, pt_k ) {
  19182. // Algorithm 2
  19183. return getBevelVec2( pt_i, pt_j, pt_k );
  19184. }
  19185. function getBevelVec1( pt_i, pt_j, pt_k ) {
  19186. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  19187. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  19188. if ( anglea > angleb ) {
  19189. angleb += Math.PI * 2;
  19190. }
  19191. var anglec = ( anglea + angleb ) / 2;
  19192. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  19193. var x = - Math.cos( anglec );
  19194. var y = - Math.sin( anglec );
  19195. var vec = new THREE.Vector2( x, y ); //.normalize();
  19196. return vec;
  19197. }
  19198. function getBevelVec2( pt_i, pt_j, pt_k ) {
  19199. var a = THREE.ExtrudeGeometry.__v1,
  19200. b = THREE.ExtrudeGeometry.__v2,
  19201. v_hat = THREE.ExtrudeGeometry.__v3,
  19202. w_hat = THREE.ExtrudeGeometry.__v4,
  19203. p = THREE.ExtrudeGeometry.__v5,
  19204. q = THREE.ExtrudeGeometry.__v6,
  19205. v, w,
  19206. v_dot_w_hat, q_sub_p_dot_w_hat,
  19207. s, intersection;
  19208. // good reading for line-line intersection
  19209. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  19210. // define a as vector j->i
  19211. // define b as vectot k->i
  19212. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  19213. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  19214. // get unit vectors
  19215. v = a.normalize();
  19216. w = b.normalize();
  19217. // normals from pt i
  19218. v_hat.set( -v.y, v.x );
  19219. w_hat.set( w.y, -w.x );
  19220. // pts from i
  19221. p.copy( pt_i ).addSelf( v_hat );
  19222. q.copy( pt_i ).addSelf( w_hat );
  19223. if ( p.equals( q ) ) {
  19224. //console.log("Warning: lines are straight");
  19225. return w_hat.clone();
  19226. }
  19227. // Points from j, k. helps prevents points cross overover most of the time
  19228. p.copy( pt_j ).addSelf( v_hat );
  19229. q.copy( pt_k ).addSelf( w_hat );
  19230. v_dot_w_hat = v.dot( w_hat );
  19231. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  19232. // We should not reach these conditions
  19233. if ( v_dot_w_hat === 0 ) {
  19234. console.log( "Either infinite or no solutions!" );
  19235. if ( q_sub_p_dot_w_hat === 0 ) {
  19236. console.log( "Its finite solutions." );
  19237. } else {
  19238. console.log( "Too bad, no solutions." );
  19239. }
  19240. }
  19241. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  19242. if ( s < 0 ) {
  19243. // in case of emergecy, revert to algorithm 1.
  19244. return getBevelVec1( pt_i, pt_j, pt_k );
  19245. }
  19246. intersection = v.multiplyScalar( s ).addSelf( p );
  19247. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  19248. }
  19249. var contourMovements = [];
  19250. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19251. if ( j === il ) j = 0;
  19252. if ( k === il ) k = 0;
  19253. // (j)---(i)---(k)
  19254. // console.log('i,j,k', i, j , k)
  19255. var pt_i = contour[ i ];
  19256. var pt_j = contour[ j ];
  19257. var pt_k = contour[ k ];
  19258. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19259. }
  19260. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19261. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19262. ahole = holes[ h ];
  19263. oneHoleMovements = [];
  19264. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19265. if ( j === il ) j = 0;
  19266. if ( k === il ) k = 0;
  19267. // (j)---(i)---(k)
  19268. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19269. }
  19270. holesMovements.push( oneHoleMovements );
  19271. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19272. }
  19273. // Loop bevelSegments, 1 for the front, 1 for the back
  19274. for ( b = 0; b < bevelSegments; b ++ ) {
  19275. //for ( b = bevelSegments; b > 0; b -- ) {
  19276. t = b / bevelSegments;
  19277. z = bevelThickness * ( 1 - t );
  19278. //z = bevelThickness * t;
  19279. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19280. //bs = bevelSize * t ; // linear
  19281. // contract shape
  19282. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19283. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19284. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19285. v( vert.x, vert.y, - z );
  19286. }
  19287. // expand holes
  19288. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19289. ahole = holes[ h ];
  19290. oneHoleMovements = holesMovements[ h ];
  19291. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19292. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19293. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19294. v( vert.x, vert.y, -z );
  19295. }
  19296. }
  19297. }
  19298. bs = bevelSize;
  19299. // Back facing vertices
  19300. for ( i = 0; i < vlen; i ++ ) {
  19301. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19302. if ( !extrudeByPath ) {
  19303. v( vert.x, vert.y, 0 );
  19304. } else {
  19305. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19306. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19307. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19308. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  19309. v( position2.x, position2.y, position2.z );
  19310. }
  19311. }
  19312. // Add stepped vertices...
  19313. // Including front facing vertices
  19314. var s;
  19315. for ( s = 1; s <= steps; s ++ ) {
  19316. for ( i = 0; i < vlen; i ++ ) {
  19317. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19318. if ( !extrudeByPath ) {
  19319. v( vert.x, vert.y, amount / steps * s );
  19320. } else {
  19321. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19322. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19323. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19324. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  19325. v( position2.x, position2.y, position2.z );
  19326. }
  19327. }
  19328. }
  19329. // Add bevel segments planes
  19330. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19331. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19332. t = b / bevelSegments;
  19333. z = bevelThickness * ( 1 - t );
  19334. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19335. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19336. // contract shape
  19337. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19338. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19339. v( vert.x, vert.y, amount + z );
  19340. }
  19341. // expand holes
  19342. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19343. ahole = holes[ h ];
  19344. oneHoleMovements = holesMovements[ h ];
  19345. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19346. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19347. if ( !extrudeByPath ) {
  19348. v( vert.x, vert.y, amount + z );
  19349. } else {
  19350. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19351. }
  19352. }
  19353. }
  19354. }
  19355. /* Faces */
  19356. // Top and bottom faces
  19357. buildLidFaces();
  19358. // Sides faces
  19359. buildSideFaces();
  19360. ///// Internal functions
  19361. function buildLidFaces() {
  19362. if ( bevelEnabled ) {
  19363. var layer = 0 ; // steps + 1
  19364. var offset = vlen * layer;
  19365. // Bottom faces
  19366. for ( i = 0; i < flen; i ++ ) {
  19367. face = faces[ i ];
  19368. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19369. }
  19370. layer = steps + bevelSegments * 2;
  19371. offset = vlen * layer;
  19372. // Top faces
  19373. for ( i = 0; i < flen; i ++ ) {
  19374. face = faces[ i ];
  19375. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19376. }
  19377. } else {
  19378. // Bottom faces
  19379. for ( i = 0; i < flen; i++ ) {
  19380. face = faces[ i ];
  19381. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19382. }
  19383. // Top faces
  19384. for ( i = 0; i < flen; i ++ ) {
  19385. face = faces[ i ];
  19386. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19387. }
  19388. }
  19389. }
  19390. // Create faces for the z-sides of the shape
  19391. function buildSideFaces() {
  19392. var layeroffset = 0;
  19393. sidewalls( contour, layeroffset );
  19394. layeroffset += contour.length;
  19395. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19396. ahole = holes[ h ];
  19397. sidewalls( ahole, layeroffset );
  19398. //, true
  19399. layeroffset += ahole.length;
  19400. }
  19401. }
  19402. function sidewalls( contour, layeroffset ) {
  19403. var j, k;
  19404. i = contour.length;
  19405. while ( --i >= 0 ) {
  19406. j = i;
  19407. k = i - 1;
  19408. if ( k < 0 ) k = contour.length - 1;
  19409. //console.log('b', i,j, i-1, k,vertices.length);
  19410. var s = 0, sl = steps + bevelSegments * 2;
  19411. for ( s = 0; s < sl; s ++ ) {
  19412. var slen1 = vlen * s;
  19413. var slen2 = vlen * ( s + 1 );
  19414. var a = layeroffset + j + slen1,
  19415. b = layeroffset + k + slen1,
  19416. c = layeroffset + k + slen2,
  19417. d = layeroffset + j + slen2;
  19418. f4( a, b, c, d, contour, s, sl, j, k );
  19419. }
  19420. }
  19421. }
  19422. function v( x, y, z ) {
  19423. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19424. }
  19425. function f3( a, b, c, isBottom ) {
  19426. a += shapesOffset;
  19427. b += shapesOffset;
  19428. c += shapesOffset;
  19429. // normal, color, material
  19430. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19431. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19432. scope.faceVertexUvs[ 0 ].push( uvs );
  19433. }
  19434. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19435. a += shapesOffset;
  19436. b += shapesOffset;
  19437. c += shapesOffset;
  19438. d += shapesOffset;
  19439. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19440. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19441. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19442. scope.faceVertexUvs[ 0 ].push( uvs );
  19443. }
  19444. };
  19445. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19446. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19447. var ax = geometry.vertices[ indexA ].x,
  19448. ay = geometry.vertices[ indexA ].y,
  19449. bx = geometry.vertices[ indexB ].x,
  19450. by = geometry.vertices[ indexB ].y,
  19451. cx = geometry.vertices[ indexC ].x,
  19452. cy = geometry.vertices[ indexC ].y;
  19453. return [
  19454. new THREE.Vector2( ax, ay ),
  19455. new THREE.Vector2( bx, by ),
  19456. new THREE.Vector2( cx, cy )
  19457. ];
  19458. },
  19459. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19460. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19461. },
  19462. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19463. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19464. contourIndex1, contourIndex2 ) {
  19465. var ax = geometry.vertices[ indexA ].x,
  19466. ay = geometry.vertices[ indexA ].y,
  19467. az = geometry.vertices[ indexA ].z,
  19468. bx = geometry.vertices[ indexB ].x,
  19469. by = geometry.vertices[ indexB ].y,
  19470. bz = geometry.vertices[ indexB ].z,
  19471. cx = geometry.vertices[ indexC ].x,
  19472. cy = geometry.vertices[ indexC ].y,
  19473. cz = geometry.vertices[ indexC ].z,
  19474. dx = geometry.vertices[ indexD ].x,
  19475. dy = geometry.vertices[ indexD ].y,
  19476. dz = geometry.vertices[ indexD ].z;
  19477. if ( Math.abs( ay - by ) < 0.01 ) {
  19478. return [
  19479. new THREE.Vector2( ax, 1 - az ),
  19480. new THREE.Vector2( bx, 1 - bz ),
  19481. new THREE.Vector2( cx, 1 - cz ),
  19482. new THREE.Vector2( dx, 1 - dz )
  19483. ];
  19484. } else {
  19485. return [
  19486. new THREE.Vector2( ay, 1 - az ),
  19487. new THREE.Vector2( by, 1 - bz ),
  19488. new THREE.Vector2( cy, 1 - cz ),
  19489. new THREE.Vector2( dy, 1 - dz )
  19490. ];
  19491. }
  19492. }
  19493. };
  19494. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19495. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19496. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19497. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19498. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19499. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19500. /**
  19501. * @author jonobr1 / http://jonobr1.com
  19502. *
  19503. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19504. * ExtrudeGeometry.
  19505. *
  19506. * parameters = {
  19507. *
  19508. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19509. *
  19510. * material: <int> // material index for front and back faces
  19511. * uvGenerator: <Object> // object that provides UV generator functions
  19512. *
  19513. * }
  19514. **/
  19515. THREE.ShapeGeometry = function ( shapes, options ) {
  19516. THREE.Geometry.call( this );
  19517. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19518. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19519. this.addShapeList( shapes, options );
  19520. this.computeCentroids();
  19521. this.computeFaceNormals();
  19522. };
  19523. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19524. /**
  19525. * Add an array of shapes to THREE.ShapeGeometry.
  19526. */
  19527. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19528. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19529. this.addShape( shapes[ i ], options );
  19530. }
  19531. return this;
  19532. };
  19533. /**
  19534. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19535. */
  19536. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19537. if ( options === undefined ) options = {};
  19538. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19539. var material = options.material;
  19540. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19541. var shapebb = this.shapebb;
  19542. //
  19543. var i, l, hole, s;
  19544. var shapesOffset = this.vertices.length;
  19545. var shapePoints = shape.extractPoints( curveSegments );
  19546. var vertices = shapePoints.shape;
  19547. var holes = shapePoints.holes;
  19548. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19549. if ( reverse ) {
  19550. vertices = vertices.reverse();
  19551. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19552. for ( i = 0, l = holes.length; i < l; i++ ) {
  19553. hole = holes[ i ];
  19554. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19555. holes[ i ] = hole.reverse();
  19556. }
  19557. }
  19558. reverse = false;
  19559. }
  19560. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19561. // Vertices
  19562. var contour = vertices;
  19563. for ( i = 0, l = holes.length; i < l; i++ ) {
  19564. hole = holes[ i ];
  19565. vertices = vertices.concat( hole );
  19566. }
  19567. //
  19568. var vert, vlen = vertices.length;
  19569. var face, flen = faces.length;
  19570. var cont, clen = contour.length;
  19571. for ( i = 0; i < vlen; i++ ) {
  19572. vert = vertices[ i ];
  19573. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19574. }
  19575. for ( i = 0; i < flen; i++ ) {
  19576. face = faces[ i ];
  19577. var a = face[ 0 ] + shapesOffset;
  19578. var b = face[ 1 ] + shapesOffset;
  19579. var c = face[ 2 ] + shapesOffset;
  19580. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19581. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19582. }
  19583. };
  19584. /**
  19585. * @author astrodud / http://astrodud.isgreat.org/
  19586. * @author zz85 / https://github.com/zz85
  19587. */
  19588. THREE.LatheGeometry = function ( points, steps, angle ) {
  19589. THREE.Geometry.call( this );
  19590. var _steps = steps || 12;
  19591. var _angle = angle || 2 * Math.PI;
  19592. var _newV = [];
  19593. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  19594. for ( var j = 0; j < points.length; j ++ ) {
  19595. _newV[ j ] = points[ j ].clone();
  19596. this.vertices.push( _newV[ j ] );
  19597. }
  19598. var i, il = _steps + 1;
  19599. for ( i = 0; i < il; i ++ ) {
  19600. for ( var j = 0; j < _newV.length; j ++ ) {
  19601. _newV[ j ] = _newV[ j ].clone().applyMatrix4( _matrix );
  19602. this.vertices.push( _newV[ j ] );
  19603. }
  19604. }
  19605. for ( i = 0; i < _steps; i ++ ) {
  19606. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  19607. var a = i * kl + k;
  19608. var b = ( ( i + 1 ) % il ) * kl + k;
  19609. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  19610. var d = i * kl + ( k + 1 ) % kl;
  19611. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19612. this.faceVertexUvs[ 0 ].push( [
  19613. new THREE.Vector2( 1 - i / _steps, k / kl ),
  19614. new THREE.Vector2( 1 - ( i + 1 ) / _steps, k / kl ),
  19615. new THREE.Vector2( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  19616. new THREE.Vector2( 1 - i / _steps, ( k + 1 ) / kl )
  19617. ] );
  19618. }
  19619. }
  19620. this.computeCentroids();
  19621. this.computeFaceNormals();
  19622. this.computeVertexNormals();
  19623. };
  19624. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19625. /**
  19626. * @author mrdoob / http://mrdoob.com/
  19627. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19628. */
  19629. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19630. THREE.Geometry.call( this );
  19631. this.width = width;
  19632. this.height = height;
  19633. this.widthSegments = widthSegments || 1;
  19634. this.heightSegments = heightSegments || 1;
  19635. var ix, iz;
  19636. var width_half = width / 2;
  19637. var height_half = height / 2;
  19638. var gridX = this.widthSegments;
  19639. var gridZ = this.heightSegments;
  19640. var gridX1 = gridX + 1;
  19641. var gridZ1 = gridZ + 1;
  19642. var segment_width = this.width / gridX;
  19643. var segment_height = this.height / gridZ;
  19644. var normal = new THREE.Vector3( 0, 0, 1 );
  19645. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19646. for ( ix = 0; ix < gridX1; ix ++ ) {
  19647. var x = ix * segment_width - width_half;
  19648. var y = iz * segment_height - height_half;
  19649. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19650. }
  19651. }
  19652. for ( iz = 0; iz < gridZ; iz ++ ) {
  19653. for ( ix = 0; ix < gridX; ix ++ ) {
  19654. var a = ix + gridX1 * iz;
  19655. var b = ix + gridX1 * ( iz + 1 );
  19656. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19657. var d = ( ix + 1 ) + gridX1 * iz;
  19658. var face = new THREE.Face4( a, b, c, d );
  19659. face.normal.copy( normal );
  19660. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19661. this.faces.push( face );
  19662. this.faceVertexUvs[ 0 ].push( [
  19663. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19664. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19665. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19666. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19667. ] );
  19668. }
  19669. }
  19670. this.computeCentroids();
  19671. };
  19672. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19673. /**
  19674. * @author mrdoob / http://mrdoob.com/
  19675. */
  19676. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19677. THREE.Geometry.call( this );
  19678. this.radius = radius || 50;
  19679. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19680. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19681. phiStart = phiStart !== undefined ? phiStart : 0;
  19682. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19683. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19684. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19685. var x, y, vertices = [], uvs = [];
  19686. for ( y = 0; y <= this.heightSegments; y ++ ) {
  19687. var verticesRow = [];
  19688. var uvsRow = [];
  19689. for ( x = 0; x <= this.widthSegments; x ++ ) {
  19690. var u = x / this.widthSegments;
  19691. var v = y / this.heightSegments;
  19692. var vertex = new THREE.Vector3();
  19693. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19694. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  19695. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19696. this.vertices.push( vertex );
  19697. verticesRow.push( this.vertices.length - 1 );
  19698. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19699. }
  19700. vertices.push( verticesRow );
  19701. uvs.push( uvsRow );
  19702. }
  19703. for ( y = 0; y < this.heightSegments; y ++ ) {
  19704. for ( x = 0; x < this.widthSegments; x ++ ) {
  19705. var v1 = vertices[ y ][ x + 1 ];
  19706. var v2 = vertices[ y ][ x ];
  19707. var v3 = vertices[ y + 1 ][ x ];
  19708. var v4 = vertices[ y + 1 ][ x + 1 ];
  19709. var n1 = this.vertices[ v1 ].clone().normalize();
  19710. var n2 = this.vertices[ v2 ].clone().normalize();
  19711. var n3 = this.vertices[ v3 ].clone().normalize();
  19712. var n4 = this.vertices[ v4 ].clone().normalize();
  19713. var uv1 = uvs[ y ][ x + 1 ].clone();
  19714. var uv2 = uvs[ y ][ x ].clone();
  19715. var uv3 = uvs[ y + 1 ][ x ].clone();
  19716. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19717. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19718. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19719. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19720. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19721. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19722. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19723. } else {
  19724. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19725. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19726. }
  19727. }
  19728. }
  19729. this.computeCentroids();
  19730. this.computeFaceNormals();
  19731. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19732. };
  19733. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19734. /**
  19735. * @author zz85 / http://www.lab4games.net/zz85/blog
  19736. * @author alteredq / http://alteredqualia.com/
  19737. *
  19738. * For creating 3D text geometry in three.js
  19739. *
  19740. * Text = 3D Text
  19741. *
  19742. * parameters = {
  19743. * size: <float>, // size of the text
  19744. * height: <float>, // thickness to extrude text
  19745. * curveSegments: <int>, // number of points on the curves
  19746. *
  19747. * font: <string>, // font name
  19748. * weight: <string>, // font weight (normal, bold)
  19749. * style: <string>, // font style (normal, italics)
  19750. *
  19751. * bevelEnabled: <bool>, // turn on bevel
  19752. * bevelThickness: <float>, // how deep into text bevel goes
  19753. * bevelSize: <float>, // how far from text outline is bevel
  19754. * }
  19755. *
  19756. */
  19757. /* Usage Examples
  19758. // TextGeometry wrapper
  19759. var text3d = new TextGeometry( text, options );
  19760. // Complete manner
  19761. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19762. var text3d = new ExtrudeGeometry( textShapes, options );
  19763. */
  19764. THREE.TextGeometry = function ( text, parameters ) {
  19765. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19766. // translate parameters to ExtrudeGeometry API
  19767. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19768. // defaults
  19769. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19770. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19771. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19772. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19773. };
  19774. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19775. /**
  19776. * @author oosmoxiecode
  19777. * @author mrdoob / http://mrdoob.com/
  19778. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19779. */
  19780. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19781. THREE.Geometry.call( this );
  19782. var scope = this;
  19783. this.radius = radius || 100;
  19784. this.tube = tube || 40;
  19785. this.radialSegments = radialSegments || 8;
  19786. this.tubularSegments = tubularSegments || 6;
  19787. this.arc = arc || Math.PI * 2;
  19788. var center = new THREE.Vector3(), uvs = [], normals = [];
  19789. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19790. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19791. var u = i / this.tubularSegments * this.arc;
  19792. var v = j / this.radialSegments * Math.PI * 2;
  19793. center.x = this.radius * Math.cos( u );
  19794. center.y = this.radius * Math.sin( u );
  19795. var vertex = new THREE.Vector3();
  19796. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19797. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19798. vertex.z = this.tube * Math.sin( v );
  19799. this.vertices.push( vertex );
  19800. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19801. normals.push( vertex.clone().subSelf( center ).normalize() );
  19802. }
  19803. }
  19804. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19805. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19806. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19807. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19808. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19809. var d = ( this.tubularSegments + 1 ) * j + i;
  19810. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19811. face.normal.addSelf( normals[ a ] );
  19812. face.normal.addSelf( normals[ b ] );
  19813. face.normal.addSelf( normals[ c ] );
  19814. face.normal.addSelf( normals[ d ] );
  19815. face.normal.normalize();
  19816. this.faces.push( face );
  19817. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19818. }
  19819. }
  19820. this.computeCentroids();
  19821. };
  19822. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19823. /**
  19824. * @author oosmoxiecode
  19825. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19826. */
  19827. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19828. THREE.Geometry.call( this );
  19829. var scope = this;
  19830. this.radius = radius || 100;
  19831. this.tube = tube || 40;
  19832. this.radialSegments = radialSegments || 64;
  19833. this.tubularSegments = tubularSegments || 8;
  19834. this.p = p || 2;
  19835. this.q = q || 3;
  19836. this.heightScale = heightScale || 1;
  19837. this.grid = new Array( this.radialSegments );
  19838. var tang = new THREE.Vector3();
  19839. var n = new THREE.Vector3();
  19840. var bitan = new THREE.Vector3();
  19841. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19842. this.grid[ i ] = new Array( this.tubularSegments );
  19843. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19844. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19845. var v = j / this.tubularSegments * 2 * Math.PI;
  19846. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19847. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19848. var cx, cy;
  19849. tang.sub( p2, p1 );
  19850. n.add( p2, p1 );
  19851. bitan.cross( tang, n );
  19852. n.cross( bitan, tang );
  19853. bitan.normalize();
  19854. n.normalize();
  19855. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19856. cy = this.tube * Math.sin( v );
  19857. p1.x += cx * n.x + cy * bitan.x;
  19858. p1.y += cx * n.y + cy * bitan.y;
  19859. p1.z += cx * n.z + cy * bitan.z;
  19860. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19861. }
  19862. }
  19863. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19864. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19865. var ip = ( i + 1 ) % this.radialSegments;
  19866. var jp = ( j + 1 ) % this.tubularSegments;
  19867. var a = this.grid[ i ][ j ];
  19868. var b = this.grid[ ip ][ j ];
  19869. var c = this.grid[ ip ][ jp ];
  19870. var d = this.grid[ i ][ jp ];
  19871. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19872. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19873. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19874. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19875. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19876. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19877. }
  19878. }
  19879. this.computeCentroids();
  19880. this.computeFaceNormals();
  19881. this.computeVertexNormals();
  19882. function vert( x, y, z ) {
  19883. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19884. }
  19885. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19886. var cu = Math.cos( u );
  19887. var cv = Math.cos( v );
  19888. var su = Math.sin( u );
  19889. var quOverP = in_q / in_p * u;
  19890. var cs = Math.cos( quOverP );
  19891. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19892. var ty = radius * ( 2 + cs ) * su * 0.5;
  19893. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19894. return new THREE.Vector3( tx, ty, tz );
  19895. }
  19896. };
  19897. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19898. /**
  19899. * @author WestLangley / https://github.com/WestLangley
  19900. * @author zz85 / https://github.com/zz85
  19901. * @author miningold / https://github.com/miningold
  19902. *
  19903. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19904. *
  19905. * Creates a tube which extrudes along a 3d spline
  19906. *
  19907. * Uses parallel transport frames as described in
  19908. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19909. */
  19910. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19911. THREE.Geometry.call( this );
  19912. this.path = path;
  19913. this.segments = segments || 64;
  19914. this.radius = radius || 1;
  19915. this.radiusSegments = radiusSegments || 8;
  19916. this.closed = closed || false;
  19917. if ( debug ) this.debug = new THREE.Object3D();
  19918. this.grid = [];
  19919. var scope = this,
  19920. tangent,
  19921. normal,
  19922. binormal,
  19923. numpoints = this.segments + 1,
  19924. x, y, z,
  19925. tx, ty, tz,
  19926. u, v,
  19927. cx, cy,
  19928. pos, pos2 = new THREE.Vector3(),
  19929. i, j,
  19930. ip, jp,
  19931. a, b, c, d,
  19932. uva, uvb, uvc, uvd;
  19933. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19934. tangents = frames.tangents,
  19935. normals = frames.normals,
  19936. binormals = frames.binormals;
  19937. // proxy internals
  19938. this.tangents = tangents;
  19939. this.normals = normals;
  19940. this.binormals = binormals;
  19941. function vert( x, y, z ) {
  19942. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19943. }
  19944. // consruct the grid
  19945. for ( i = 0; i < numpoints; i++ ) {
  19946. this.grid[ i ] = [];
  19947. u = i / ( numpoints - 1 );
  19948. pos = path.getPointAt( u );
  19949. tangent = tangents[ i ];
  19950. normal = normals[ i ];
  19951. binormal = binormals[ i ];
  19952. if ( this.debug ) {
  19953. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19954. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19955. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19956. }
  19957. for ( j = 0; j < this.radiusSegments; j++ ) {
  19958. v = j / this.radiusSegments * 2 * Math.PI;
  19959. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19960. cy = this.radius * Math.sin( v );
  19961. pos2.copy( pos );
  19962. pos2.x += cx * normal.x + cy * binormal.x;
  19963. pos2.y += cx * normal.y + cy * binormal.y;
  19964. pos2.z += cx * normal.z + cy * binormal.z;
  19965. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19966. }
  19967. }
  19968. // construct the mesh
  19969. for ( i = 0; i < this.segments; i++ ) {
  19970. for ( j = 0; j < this.radiusSegments; j++ ) {
  19971. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19972. jp = (j + 1) % this.radiusSegments;
  19973. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19974. b = this.grid[ ip ][ j ];
  19975. c = this.grid[ ip ][ jp ];
  19976. d = this.grid[ i ][ jp ];
  19977. uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
  19978. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19979. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19980. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19981. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19982. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19983. }
  19984. }
  19985. this.computeCentroids();
  19986. this.computeFaceNormals();
  19987. this.computeVertexNormals();
  19988. };
  19989. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19990. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19991. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19992. var tangent = new THREE.Vector3(),
  19993. normal = new THREE.Vector3(),
  19994. binormal = new THREE.Vector3(),
  19995. tangents = [],
  19996. normals = [],
  19997. binormals = [],
  19998. vec = new THREE.Vector3(),
  19999. mat = new THREE.Matrix4(),
  20000. numpoints = segments + 1,
  20001. theta,
  20002. epsilon = 0.0001,
  20003. smallest,
  20004. tx, ty, tz,
  20005. i, u, v;
  20006. // expose internals
  20007. this.tangents = tangents;
  20008. this.normals = normals;
  20009. this.binormals = binormals;
  20010. // compute the tangent vectors for each segment on the path
  20011. for ( i = 0; i < numpoints; i++ ) {
  20012. u = i / ( numpoints - 1 );
  20013. tangents[ i ] = path.getTangentAt( u );
  20014. tangents[ i ].normalize();
  20015. }
  20016. initialNormal3();
  20017. function initialNormal1(lastBinormal) {
  20018. // fixed start binormal. Has dangers of 0 vectors
  20019. normals[ 0 ] = new THREE.Vector3();
  20020. binormals[ 0 ] = new THREE.Vector3();
  20021. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20022. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  20023. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  20024. }
  20025. function initialNormal2() {
  20026. // This uses the Frenet-Serret formula for deriving binormal
  20027. var t2 = path.getTangentAt( epsilon );
  20028. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  20029. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  20030. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20031. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  20032. }
  20033. function initialNormal3() {
  20034. // select an initial normal vector perpenicular to the first tangent vector,
  20035. // and in the direction of the smallest tangent xyz component
  20036. normals[ 0 ] = new THREE.Vector3();
  20037. binormals[ 0 ] = new THREE.Vector3();
  20038. smallest = Number.MAX_VALUE;
  20039. tx = Math.abs( tangents[ 0 ].x );
  20040. ty = Math.abs( tangents[ 0 ].y );
  20041. tz = Math.abs( tangents[ 0 ].z );
  20042. if ( tx <= smallest ) {
  20043. smallest = tx;
  20044. normal.set( 1, 0, 0 );
  20045. }
  20046. if ( ty <= smallest ) {
  20047. smallest = ty;
  20048. normal.set( 0, 1, 0 );
  20049. }
  20050. if ( tz <= smallest ) {
  20051. normal.set( 0, 0, 1 );
  20052. }
  20053. vec.cross( tangents[ 0 ], normal ).normalize();
  20054. normals[ 0 ].cross( tangents[ 0 ], vec );
  20055. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  20056. }
  20057. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20058. for ( i = 1; i < numpoints; i++ ) {
  20059. normals[ i ] = normals[ i-1 ].clone();
  20060. binormals[ i ] = binormals[ i-1 ].clone();
  20061. vec.cross( tangents[ i-1 ], tangents[ i ] );
  20062. if ( vec.length() > epsilon ) {
  20063. vec.normalize();
  20064. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  20065. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20066. }
  20067. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  20068. }
  20069. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20070. if ( closed ) {
  20071. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  20072. theta /= ( numpoints - 1 );
  20073. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20074. theta = -theta;
  20075. }
  20076. for ( i = 1; i < numpoints; i++ ) {
  20077. // twist a little...
  20078. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20079. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  20080. }
  20081. }
  20082. };
  20083. /**
  20084. * @author clockworkgeek / https://github.com/clockworkgeek
  20085. * @author timothypratley / https://github.com/timothypratley
  20086. */
  20087. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  20088. THREE.Geometry.call( this );
  20089. radius = radius || 1;
  20090. detail = detail || 0;
  20091. var that = this;
  20092. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20093. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  20094. }
  20095. var midpoints = [], p = this.vertices;
  20096. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20097. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  20098. }
  20099. this.mergeVertices();
  20100. // Apply radius
  20101. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20102. this.vertices[ i ].multiplyScalar( radius );
  20103. }
  20104. // Project vector onto sphere's surface
  20105. function prepare( vector ) {
  20106. var vertex = vector.normalize().clone();
  20107. vertex.index = that.vertices.push( vertex ) - 1;
  20108. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20109. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20110. var v = inclination( vector ) / Math.PI + 0.5;
  20111. vertex.uv = new THREE.Vector2( u, 1 - v );
  20112. return vertex;
  20113. }
  20114. // Approximate a curved face with recursively sub-divided triangles.
  20115. function make( v1, v2, v3, detail ) {
  20116. if ( detail < 1 ) {
  20117. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20118. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  20119. face.normal = face.centroid.clone().normalize();
  20120. that.faces.push( face );
  20121. var azi = azimuth( face.centroid );
  20122. that.faceVertexUvs[ 0 ].push( [
  20123. correctUV( v1.uv, v1, azi ),
  20124. correctUV( v2.uv, v2, azi ),
  20125. correctUV( v3.uv, v3, azi )
  20126. ] );
  20127. } else {
  20128. detail -= 1;
  20129. // split triangle into 4 smaller triangles
  20130. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  20131. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  20132. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  20133. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  20134. }
  20135. }
  20136. function midpoint( v1, v2 ) {
  20137. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  20138. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  20139. var mid = midpoints[ v1.index ][ v2.index ];
  20140. if ( mid === undefined ) {
  20141. // generate mean point and project to surface with prepare()
  20142. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  20143. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  20144. );
  20145. }
  20146. return mid;
  20147. }
  20148. // Angle around the Y axis, counter-clockwise when looking from above.
  20149. function azimuth( vector ) {
  20150. return Math.atan2( vector.z, -vector.x );
  20151. }
  20152. // Angle above the XZ plane.
  20153. function inclination( vector ) {
  20154. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20155. }
  20156. // Texture fixing helper. Spheres have some odd behaviours.
  20157. function correctUV( uv, vector, azimuth ) {
  20158. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20159. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20160. return uv;
  20161. }
  20162. this.computeCentroids();
  20163. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20164. };
  20165. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20166. /**
  20167. * @author timothypratley / https://github.com/timothypratley
  20168. */
  20169. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20170. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20171. var vertices = [
  20172. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20173. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20174. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20175. ];
  20176. var faces = [
  20177. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20178. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20179. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20180. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20181. ];
  20182. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20183. };
  20184. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20185. /**
  20186. * @author timothypratley / https://github.com/timothypratley
  20187. */
  20188. THREE.OctahedronGeometry = function ( radius, detail ) {
  20189. var vertices = [
  20190. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20191. ];
  20192. var faces = [
  20193. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20194. ];
  20195. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20196. };
  20197. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20198. /**
  20199. * @author timothypratley / https://github.com/timothypratley
  20200. */
  20201. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20202. var vertices = [
  20203. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20204. ];
  20205. var faces = [
  20206. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20207. ];
  20208. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20209. };
  20210. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20211. /**
  20212. * @author zz85 / https://github.com/zz85
  20213. * Parametric Surfaces Geometry
  20214. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20215. *
  20216. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  20217. *
  20218. */
  20219. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  20220. THREE.Geometry.call( this );
  20221. var verts = this.vertices;
  20222. var faces = this.faces;
  20223. var uvs = this.faceVertexUvs[ 0 ];
  20224. useTris = (useTris === undefined) ? false : useTris;
  20225. var i, il, j, p;
  20226. var u, v;
  20227. var stackCount = stacks + 1;
  20228. var sliceCount = slices + 1;
  20229. for ( i = 0; i <= stacks; i ++ ) {
  20230. v = i / stacks;
  20231. for ( j = 0; j <= slices; j ++ ) {
  20232. u = j / slices;
  20233. p = func( u, v );
  20234. verts.push( p );
  20235. }
  20236. }
  20237. var a, b, c, d;
  20238. var uva, uvb, uvc, uvd;
  20239. for ( i = 0; i < stacks; i ++ ) {
  20240. for ( j = 0; j < slices; j ++ ) {
  20241. a = i * sliceCount + j;
  20242. b = i * sliceCount + j + 1;
  20243. c = (i + 1) * sliceCount + j;
  20244. d = (i + 1) * sliceCount + j + 1;
  20245. uva = new THREE.Vector2( j / slices, i / stacks );
  20246. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20247. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20248. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20249. if ( useTris ) {
  20250. faces.push( new THREE.Face3( a, b, c ) );
  20251. faces.push( new THREE.Face3( b, d, c ) );
  20252. uvs.push( [ uva, uvb, uvc ] );
  20253. uvs.push( [ uvb, uvd, uvc ] );
  20254. } else {
  20255. faces.push( new THREE.Face4( a, b, d, c ) );
  20256. uvs.push( [ uva, uvb, uvd, uvc ] );
  20257. }
  20258. }
  20259. }
  20260. // console.log(this);
  20261. // magic bullet
  20262. // var diff = this.mergeVertices();
  20263. // console.log('removed ', diff, ' vertices by merging');
  20264. this.computeCentroids();
  20265. this.computeFaceNormals();
  20266. this.computeVertexNormals();
  20267. };
  20268. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20269. /**
  20270. * @author qiao / https://github.com/qiao
  20271. * @fileoverview This is a convex hull generator using the incremental method.
  20272. * The complexity is O(n^2) where n is the number of vertices.
  20273. * O(nlogn) algorithms do exist, but they are much more complicated.
  20274. *
  20275. * Benchmark:
  20276. *
  20277. * Platform: CPU: P7350 @2.00GHz Engine: V8
  20278. *
  20279. * Num Vertices Time(ms)
  20280. *
  20281. * 10 1
  20282. * 20 3
  20283. * 30 19
  20284. * 40 48
  20285. * 50 107
  20286. */
  20287. THREE.ConvexGeometry = function( vertices ) {
  20288. THREE.Geometry.call( this );
  20289. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  20290. for ( var i = 3; i < vertices.length; i++ ) {
  20291. addPoint( i );
  20292. }
  20293. function addPoint( vertexId ) {
  20294. var vertex = vertices[ vertexId ].clone();
  20295. var mag = vertex.length();
  20296. vertex.x += mag * randomOffset();
  20297. vertex.y += mag * randomOffset();
  20298. vertex.z += mag * randomOffset();
  20299. var hole = [];
  20300. for ( var f = 0; f < faces.length; ) {
  20301. var face = faces[ f ];
  20302. // for each face, if the vertex can see it,
  20303. // then we try to add the face's edges into the hole.
  20304. if ( visible( face, vertex ) ) {
  20305. for ( var e = 0; e < 3; e++ ) {
  20306. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  20307. var boundary = true;
  20308. // remove duplicated edges.
  20309. for ( var h = 0; h < hole.length; h++ ) {
  20310. if ( equalEdge( hole[ h ], edge ) ) {
  20311. hole[ h ] = hole[ hole.length - 1 ];
  20312. hole.pop();
  20313. boundary = false;
  20314. break;
  20315. }
  20316. }
  20317. if ( boundary ) {
  20318. hole.push( edge );
  20319. }
  20320. }
  20321. // remove faces[ f ]
  20322. faces[ f ] = faces[ faces.length - 1 ];
  20323. faces.pop();
  20324. } else { // not visible
  20325. f++;
  20326. }
  20327. }
  20328. // construct the new faces formed by the edges of the hole and the vertex
  20329. for ( var h = 0; h < hole.length; h++ ) {
  20330. faces.push( [
  20331. hole[ h ][ 0 ],
  20332. hole[ h ][ 1 ],
  20333. vertexId
  20334. ] );
  20335. }
  20336. }
  20337. /**
  20338. * Whether the face is visible from the vertex
  20339. */
  20340. function visible( face, vertex ) {
  20341. var va = vertices[ face[ 0 ] ];
  20342. var vb = vertices[ face[ 1 ] ];
  20343. var vc = vertices[ face[ 2 ] ];
  20344. var n = normal( va, vb, vc );
  20345. // distance from face to origin
  20346. var dist = n.dot( va );
  20347. return n.dot( vertex ) >= dist;
  20348. }
  20349. /**
  20350. * Face normal
  20351. */
  20352. function normal( va, vb, vc ) {
  20353. var cb = new THREE.Vector3();
  20354. var ab = new THREE.Vector3();
  20355. cb.sub( vc, vb );
  20356. ab.sub( va, vb );
  20357. cb.crossSelf( ab );
  20358. cb.normalize();
  20359. return cb;
  20360. }
  20361. /**
  20362. * Detect whether two edges are equal.
  20363. * Note that when constructing the convex hull, two same edges can only
  20364. * be of the negative direction.
  20365. */
  20366. function equalEdge( ea, eb ) {
  20367. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20368. }
  20369. /**
  20370. * Create a random offset between -1e-6 and 1e-6.
  20371. */
  20372. function randomOffset() {
  20373. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20374. }
  20375. /**
  20376. * XXX: Not sure if this is the correct approach. Need someone to review.
  20377. */
  20378. function vertexUv( vertex ) {
  20379. var mag = vertex.length();
  20380. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  20381. }
  20382. // Push vertices into `this.vertices`, skipping those inside the hull
  20383. var id = 0;
  20384. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20385. for ( var i = 0; i < faces.length; i++ ) {
  20386. var face = faces[ i ];
  20387. for ( var j = 0; j < 3; j++ ) {
  20388. if ( newId[ face[ j ] ] === undefined ) {
  20389. newId[ face[ j ] ] = id++;
  20390. this.vertices.push( vertices[ face[ j ] ] );
  20391. }
  20392. face[ j ] = newId[ face[ j ] ];
  20393. }
  20394. }
  20395. // Convert faces into instances of THREE.Face3
  20396. for ( var i = 0; i < faces.length; i++ ) {
  20397. this.faces.push( new THREE.Face3(
  20398. faces[ i ][ 0 ],
  20399. faces[ i ][ 1 ],
  20400. faces[ i ][ 2 ]
  20401. ) );
  20402. }
  20403. // Compute UVs
  20404. for ( var i = 0; i < this.faces.length; i++ ) {
  20405. var face = this.faces[ i ];
  20406. this.faceVertexUvs[ 0 ].push( [
  20407. vertexUv( this.vertices[ face.a ] ),
  20408. vertexUv( this.vertices[ face.b ] ),
  20409. vertexUv( this.vertices[ face.c ])
  20410. ] );
  20411. }
  20412. this.computeCentroids();
  20413. this.computeFaceNormals();
  20414. this.computeVertexNormals();
  20415. };
  20416. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20417. /**
  20418. * @author sroucheray / http://sroucheray.org/
  20419. * @author mrdoob / http://mrdoob.com/
  20420. */
  20421. THREE.AxisHelper = function ( size ) {
  20422. var geometry = new THREE.Geometry();
  20423. geometry.vertices.push(
  20424. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  20425. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  20426. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  20427. );
  20428. geometry.colors.push(
  20429. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20430. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20431. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20432. );
  20433. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20434. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20435. };
  20436. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20437. /**
  20438. * @author WestLangley / http://github.com/WestLangley
  20439. * @author zz85 / https://github.com/zz85
  20440. *
  20441. * Creates an arrow for visualizing directions
  20442. *
  20443. * Parameters:
  20444. * dir - Vector3
  20445. * origin - Vector3
  20446. * length - Number
  20447. * hex - color in hex value
  20448. */
  20449. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20450. THREE.Object3D.call( this );
  20451. if ( hex === undefined ) hex = 0xffff00;
  20452. if ( length === undefined ) length = 20;
  20453. var lineGeometry = new THREE.Geometry();
  20454. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20455. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20456. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20457. this.add( this.line );
  20458. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20459. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20460. this.cone.position.set( 0, 1, 0 );
  20461. this.add( this.cone );
  20462. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  20463. this.setDirection( dir );
  20464. this.setLength( length );
  20465. };
  20466. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20467. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  20468. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  20469. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  20470. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  20471. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  20472. };
  20473. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20474. this.scale.set( length, length, length );
  20475. };
  20476. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20477. this.line.material.color.setHex( hex );
  20478. this.cone.material.color.setHex( hex );
  20479. };
  20480. /**
  20481. * @author alteredq / http://alteredqualia.com/
  20482. *
  20483. * - shows frustum, line of sight and up of the camera
  20484. * - suitable for fast updates
  20485. * - based on frustum visualization in lightgl.js shadowmap example
  20486. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20487. */
  20488. THREE.CameraHelper = function ( camera ) {
  20489. THREE.Line.call( this );
  20490. var scope = this;
  20491. this.geometry = new THREE.Geometry();
  20492. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20493. this.type = THREE.LinePieces;
  20494. this.matrixWorld = camera.matrixWorld;
  20495. this.matrixAutoUpdate = false;
  20496. this.pointMap = {};
  20497. // colors
  20498. var hexFrustum = 0xffaa00;
  20499. var hexCone = 0xff0000;
  20500. var hexUp = 0x00aaff;
  20501. var hexTarget = 0xffffff;
  20502. var hexCross = 0x333333;
  20503. // near
  20504. addLine( "n1", "n2", hexFrustum );
  20505. addLine( "n2", "n4", hexFrustum );
  20506. addLine( "n4", "n3", hexFrustum );
  20507. addLine( "n3", "n1", hexFrustum );
  20508. // far
  20509. addLine( "f1", "f2", hexFrustum );
  20510. addLine( "f2", "f4", hexFrustum );
  20511. addLine( "f4", "f3", hexFrustum );
  20512. addLine( "f3", "f1", hexFrustum );
  20513. // sides
  20514. addLine( "n1", "f1", hexFrustum );
  20515. addLine( "n2", "f2", hexFrustum );
  20516. addLine( "n3", "f3", hexFrustum );
  20517. addLine( "n4", "f4", hexFrustum );
  20518. // cone
  20519. addLine( "p", "n1", hexCone );
  20520. addLine( "p", "n2", hexCone );
  20521. addLine( "p", "n3", hexCone );
  20522. addLine( "p", "n4", hexCone );
  20523. // up
  20524. addLine( "u1", "u2", hexUp );
  20525. addLine( "u2", "u3", hexUp );
  20526. addLine( "u3", "u1", hexUp );
  20527. // target
  20528. addLine( "c", "t", hexTarget );
  20529. addLine( "p", "c", hexCross );
  20530. // cross
  20531. addLine( "cn1", "cn2", hexCross );
  20532. addLine( "cn3", "cn4", hexCross );
  20533. addLine( "cf1", "cf2", hexCross );
  20534. addLine( "cf3", "cf4", hexCross );
  20535. this.camera = camera;
  20536. function addLine( a, b, hex ) {
  20537. addPoint( a, hex );
  20538. addPoint( b, hex );
  20539. }
  20540. function addPoint( id, hex ) {
  20541. scope.geometry.vertices.push( new THREE.Vector3() );
  20542. scope.geometry.colors.push( new THREE.Color( hex ) );
  20543. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  20544. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  20545. }
  20546. this.update( camera );
  20547. };
  20548. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20549. THREE.CameraHelper.prototype.update = function () {
  20550. var scope = this;
  20551. var w = 1, h = 1;
  20552. // we need just camera projection matrix
  20553. // world matrix must be identity
  20554. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  20555. // center / target
  20556. setPoint( "c", 0, 0, -1 );
  20557. setPoint( "t", 0, 0, 1 );
  20558. // near
  20559. setPoint( "n1", -w, -h, -1 );
  20560. setPoint( "n2", w, -h, -1 );
  20561. setPoint( "n3", -w, h, -1 );
  20562. setPoint( "n4", w, h, -1 );
  20563. // far
  20564. setPoint( "f1", -w, -h, 1 );
  20565. setPoint( "f2", w, -h, 1 );
  20566. setPoint( "f3", -w, h, 1 );
  20567. setPoint( "f4", w, h, 1 );
  20568. // up
  20569. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20570. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20571. setPoint( "u3", 0, h * 2, -1 );
  20572. // cross
  20573. setPoint( "cf1", -w, 0, 1 );
  20574. setPoint( "cf2", w, 0, 1 );
  20575. setPoint( "cf3", 0, -h, 1 );
  20576. setPoint( "cf4", 0, h, 1 );
  20577. setPoint( "cn1", -w, 0, -1 );
  20578. setPoint( "cn2", w, 0, -1 );
  20579. setPoint( "cn3", 0, -h, -1 );
  20580. setPoint( "cn4", 0, h, -1 );
  20581. function setPoint( point, x, y, z ) {
  20582. THREE.CameraHelper.__v.set( x, y, z );
  20583. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  20584. var points = scope.pointMap[ point ];
  20585. if ( points !== undefined ) {
  20586. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20587. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  20588. }
  20589. }
  20590. }
  20591. this.geometry.verticesNeedUpdate = true;
  20592. };
  20593. THREE.CameraHelper.__projector = new THREE.Projector();
  20594. THREE.CameraHelper.__v = new THREE.Vector3();
  20595. THREE.CameraHelper.__c = new THREE.Camera();
  20596. /**
  20597. * @author alteredq / http://alteredqualia.com/
  20598. *
  20599. * - shows directional light color, intensity, position, orientation and target
  20600. */
  20601. THREE.DirectionalLightHelper = function ( light, sphereSize, arrowLength ) {
  20602. THREE.Object3D.call( this );
  20603. this.light = light;
  20604. // position
  20605. this.position = light.position;
  20606. // direction
  20607. this.direction = new THREE.Vector3();
  20608. this.direction.sub( light.target.position, light.position );
  20609. // color
  20610. this.color = light.color.clone();
  20611. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20612. this.color.r *= intensity;
  20613. this.color.g *= intensity;
  20614. this.color.b *= intensity;
  20615. var hexColor = this.color.getHex();
  20616. // light helper
  20617. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20618. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20619. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20620. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20621. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  20622. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20623. this.lightArrow.cone.material.fog = false;
  20624. this.lightArrow.line.material.fog = false;
  20625. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20626. this.add( this.lightArrow );
  20627. this.add( this.lightSphere );
  20628. this.add( this.lightRays );
  20629. this.lightSphere.properties.isGizmo = true;
  20630. this.lightSphere.properties.gizmoSubject = light;
  20631. this.lightSphere.properties.gizmoRoot = this;
  20632. // light target helper
  20633. this.targetSphere = null;
  20634. if ( light.target.properties.targetInverse ) {
  20635. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20636. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20637. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20638. this.targetSphere.position = light.target.position;
  20639. this.targetSphere.properties.isGizmo = true;
  20640. this.targetSphere.properties.gizmoSubject = light.target;
  20641. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20642. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20643. var lineGeometry = new THREE.Geometry();
  20644. lineGeometry.vertices.push( this.position.clone() );
  20645. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20646. lineGeometry.computeLineDistances();
  20647. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20648. this.targetLine.properties.isGizmo = true;
  20649. }
  20650. //
  20651. this.properties.isGizmo = true;
  20652. }
  20653. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20654. THREE.DirectionalLightHelper.prototype.update = function () {
  20655. // update arrow orientation
  20656. // pointing from light to target
  20657. this.direction.sub( this.light.target.position, this.light.position );
  20658. this.lightArrow.setDirection( this.direction );
  20659. // update arrow, spheres, rays and line colors to light color * light intensity
  20660. this.color.copy( this.light.color );
  20661. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20662. this.color.r *= intensity;
  20663. this.color.g *= intensity;
  20664. this.color.b *= intensity;
  20665. this.lightArrow.setColor( this.color.getHex() );
  20666. this.lightSphere.material.color.copy( this.color );
  20667. this.lightRays.material.color.copy( this.color );
  20668. this.targetSphere.material.color.copy( this.color );
  20669. this.targetLine.material.color.copy( this.color );
  20670. // update target line vertices
  20671. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20672. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20673. this.targetLine.geometry.computeLineDistances();
  20674. this.targetLine.geometry.verticesNeedUpdate = true;
  20675. }
  20676. /**
  20677. * @author alteredq / http://alteredqualia.com/
  20678. *
  20679. * - shows hemisphere light intensity, sky and ground colors and directions
  20680. */
  20681. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20682. THREE.Object3D.call( this );
  20683. this.light = light;
  20684. // position
  20685. this.position = light.position;
  20686. //
  20687. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20688. // sky color
  20689. this.color = light.color.clone();
  20690. this.color.r *= intensity;
  20691. this.color.g *= intensity;
  20692. this.color.b *= intensity;
  20693. var hexColor = this.color.getHex();
  20694. // ground color
  20695. this.groundColor = light.groundColor.clone();
  20696. this.groundColor.r *= intensity;
  20697. this.groundColor.g *= intensity;
  20698. this.groundColor.b *= intensity;
  20699. var hexColorGround = this.groundColor.getHex();
  20700. // double colored light bulb
  20701. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  20702. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  20703. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20704. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  20705. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  20706. bulbGeometry.faces[ i ].materialIndex = 0;
  20707. }
  20708. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  20709. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  20710. }
  20711. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  20712. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  20713. // arrows for sky and ground light directions
  20714. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  20715. this.lightArrow.rotation.x = Math.PI;
  20716. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  20717. var joint = new THREE.Object3D();
  20718. joint.rotation.x = -Math.PI * 0.5;
  20719. joint.add( this.lightSphere );
  20720. joint.add( this.lightArrow );
  20721. joint.add( this.lightArrowGround );
  20722. this.add( joint );
  20723. //
  20724. this.lightSphere.properties.isGizmo = true;
  20725. this.lightSphere.properties.gizmoSubject = light;
  20726. this.lightSphere.properties.gizmoRoot = this;
  20727. //
  20728. this.properties.isGizmo = true;
  20729. //
  20730. this.target = new THREE.Vector3();
  20731. this.lookAt( this.target );
  20732. }
  20733. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20734. THREE.HemisphereLightHelper.prototype.update = function () {
  20735. // update sphere sky and ground colors to light color * light intensity
  20736. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20737. this.color.copy( this.light.color );
  20738. this.groundColor.copy( this.light.groundColor );
  20739. this.color.r *= intensity;
  20740. this.color.g *= intensity;
  20741. this.color.b *= intensity;
  20742. this.groundColor.r *= intensity;
  20743. this.groundColor.g *= intensity;
  20744. this.groundColor.b *= intensity;
  20745. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  20746. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  20747. this.lightArrow.setColor( this.color.getHex() );
  20748. this.lightArrowGround.setColor( this.groundColor.getHex() );
  20749. this.lookAt( this.target );
  20750. }
  20751. /**
  20752. * @author alteredq / http://alteredqualia.com/
  20753. *
  20754. * - shows point light color, intensity, position and distance
  20755. */
  20756. THREE.PointLightHelper = function ( light, sphereSize ) {
  20757. THREE.Object3D.call( this );
  20758. this.light = light;
  20759. // position
  20760. this.position = light.position;
  20761. // color
  20762. this.color = light.color.clone();
  20763. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20764. this.color.r *= intensity;
  20765. this.color.g *= intensity;
  20766. this.color.b *= intensity;
  20767. var hexColor = this.color.getHex();
  20768. // light helper
  20769. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20770. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20771. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20772. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20773. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20774. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20775. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20776. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20777. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20778. var d = light.distance;
  20779. if ( d === 0.0 ) {
  20780. this.lightDistance.visible = false;
  20781. } else {
  20782. this.lightDistance.scale.set( d, d, d );
  20783. }
  20784. this.add( this.lightSphere );
  20785. this.add( this.lightRays );
  20786. this.add( this.lightDistance );
  20787. //
  20788. this.lightSphere.properties.isGizmo = true;
  20789. this.lightSphere.properties.gizmoSubject = light;
  20790. this.lightSphere.properties.gizmoRoot = this;
  20791. //
  20792. this.properties.isGizmo = true;
  20793. }
  20794. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20795. THREE.PointLightHelper.prototype.update = function () {
  20796. // update sphere and rays colors to light color * light intensity
  20797. this.color.copy( this.light.color );
  20798. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20799. this.color.r *= intensity;
  20800. this.color.g *= intensity;
  20801. this.color.b *= intensity;
  20802. this.lightSphere.material.color.copy( this.color );
  20803. this.lightRays.material.color.copy( this.color );
  20804. this.lightDistance.material.color.copy( this.color );
  20805. //
  20806. var d = this.light.distance;
  20807. if ( d === 0.0 ) {
  20808. this.lightDistance.visible = false;
  20809. } else {
  20810. this.lightDistance.visible = true;
  20811. this.lightDistance.scale.set( d, d, d );
  20812. }
  20813. }
  20814. /**
  20815. * @author alteredq / http://alteredqualia.com/
  20816. *
  20817. * - shows spot light color, intensity, position, orientation, light cone and target
  20818. */
  20819. THREE.SpotLightHelper = function ( light, sphereSize, arrowLength ) {
  20820. THREE.Object3D.call( this );
  20821. this.light = light;
  20822. // position
  20823. this.position = light.position;
  20824. // direction
  20825. this.direction = new THREE.Vector3();
  20826. this.direction.sub( light.target.position, light.position );
  20827. // color
  20828. this.color = light.color.clone();
  20829. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20830. this.color.r *= intensity;
  20831. this.color.g *= intensity;
  20832. this.color.b *= intensity;
  20833. var hexColor = this.color.getHex();
  20834. // light helper
  20835. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20836. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20837. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20838. var coneMatrix = new THREE.Matrix4();
  20839. coneMatrix.rotateX( -Math.PI/2 );
  20840. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  20841. coneGeometry.applyMatrix( coneMatrix );
  20842. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20843. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20844. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20845. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  20846. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20847. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  20848. var coneLength = light.distance ? light.distance : 10000;
  20849. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  20850. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20851. this.lightArrow.cone.material.fog = false;
  20852. this.lightArrow.line.material.fog = false;
  20853. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20854. this.gyroscope = new THREE.Gyroscope();
  20855. this.gyroscope.add( this.lightArrow );
  20856. this.gyroscope.add( this.lightSphere );
  20857. this.gyroscope.add( this.lightRays );
  20858. this.add( this.gyroscope );
  20859. this.add( this.lightCone );
  20860. this.lookAt( light.target.position );
  20861. this.lightSphere.properties.isGizmo = true;
  20862. this.lightSphere.properties.gizmoSubject = light;
  20863. this.lightSphere.properties.gizmoRoot = this;
  20864. // light target helper
  20865. this.targetSphere = null;
  20866. if ( light.target.properties.targetInverse ) {
  20867. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20868. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20869. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20870. this.targetSphere.position = light.target.position;
  20871. this.targetSphere.properties.isGizmo = true;
  20872. this.targetSphere.properties.gizmoSubject = light.target;
  20873. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20874. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20875. var lineGeometry = new THREE.Geometry();
  20876. lineGeometry.vertices.push( this.position.clone() );
  20877. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20878. lineGeometry.computeLineDistances();
  20879. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20880. this.targetLine.properties.isGizmo = true;
  20881. }
  20882. //
  20883. this.properties.isGizmo = true;
  20884. }
  20885. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20886. THREE.SpotLightHelper.prototype.update = function () {
  20887. // update arrow orientation
  20888. // pointing from light to target
  20889. this.direction.sub( this.light.target.position, this.light.position );
  20890. this.lightArrow.setDirection( this.direction );
  20891. // update light cone orientation and size
  20892. this.lookAt( this.light.target.position );
  20893. var coneLength = this.light.distance ? this.light.distance : 10000;
  20894. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  20895. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20896. // update arrow, spheres, rays and line colors to light color * light intensity
  20897. this.color.copy( this.light.color );
  20898. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20899. this.color.r *= intensity;
  20900. this.color.g *= intensity;
  20901. this.color.b *= intensity;
  20902. this.lightArrow.setColor( this.color.getHex() );
  20903. this.lightSphere.material.color.copy( this.color );
  20904. this.lightRays.material.color.copy( this.color );
  20905. this.lightCone.material.color.copy( this.color );
  20906. this.targetSphere.material.color.copy( this.color );
  20907. this.targetLine.material.color.copy( this.color );
  20908. // update target line vertices
  20909. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20910. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20911. this.targetLine.geometry.computeLineDistances();
  20912. this.targetLine.geometry.verticesNeedUpdate = true;
  20913. }
  20914. /**
  20915. * @author alteredq / http://alteredqualia.com/
  20916. */
  20917. THREE.ImmediateRenderObject = function ( ) {
  20918. THREE.Object3D.call( this );
  20919. this.render = function ( renderCallback ) { };
  20920. };
  20921. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20922. /**
  20923. * @author mikael emtinger / http://gomo.se/
  20924. * @author alteredq / http://alteredqualia.com/
  20925. */
  20926. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20927. THREE.Object3D.call( this );
  20928. this.lensFlares = [];
  20929. this.positionScreen = new THREE.Vector3();
  20930. this.customUpdateCallback = undefined;
  20931. if( texture !== undefined ) {
  20932. this.add( texture, size, distance, blending, color );
  20933. }
  20934. };
  20935. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20936. /*
  20937. * Add: adds another flare
  20938. */
  20939. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20940. if( size === undefined ) size = -1;
  20941. if( distance === undefined ) distance = 0;
  20942. if( opacity === undefined ) opacity = 1;
  20943. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20944. if( blending === undefined ) blending = THREE.NormalBlending;
  20945. distance = Math.min( distance, Math.max( 0, distance ) );
  20946. this.lensFlares.push( { texture: texture, // THREE.Texture
  20947. size: size, // size in pixels (-1 = use texture.width)
  20948. distance: distance, // distance (0-1) from light source (0=at light source)
  20949. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20950. scale: 1, // scale
  20951. rotation: 1, // rotation
  20952. opacity: opacity, // opacity
  20953. color: color, // color
  20954. blending: blending } ); // blending
  20955. };
  20956. /*
  20957. * Update lens flares update positions on all flares based on the screen position
  20958. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20959. */
  20960. THREE.LensFlare.prototype.updateLensFlares = function () {
  20961. var f, fl = this.lensFlares.length;
  20962. var flare;
  20963. var vecX = -this.positionScreen.x * 2;
  20964. var vecY = -this.positionScreen.y * 2;
  20965. for( f = 0; f < fl; f ++ ) {
  20966. flare = this.lensFlares[ f ];
  20967. flare.x = this.positionScreen.x + vecX * flare.distance;
  20968. flare.y = this.positionScreen.y + vecY * flare.distance;
  20969. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20970. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20971. }
  20972. };
  20973. /**
  20974. * @author alteredq / http://alteredqualia.com/
  20975. */
  20976. THREE.MorphBlendMesh = function( geometry, material ) {
  20977. THREE.Mesh.call( this, geometry, material );
  20978. this.animationsMap = {};
  20979. this.animationsList = [];
  20980. // prepare default animation
  20981. // (all frames played together in 1 second)
  20982. var numFrames = this.geometry.morphTargets.length;
  20983. var name = "__default";
  20984. var startFrame = 0;
  20985. var endFrame = numFrames - 1;
  20986. var fps = numFrames / 1;
  20987. this.createAnimation( name, startFrame, endFrame, fps );
  20988. this.setAnimationWeight( name, 1 );
  20989. };
  20990. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20991. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20992. var animation = {
  20993. startFrame: start,
  20994. endFrame: end,
  20995. length: end - start + 1,
  20996. fps: fps,
  20997. duration: ( end - start ) / fps,
  20998. lastFrame: 0,
  20999. currentFrame: 0,
  21000. active: false,
  21001. time: 0,
  21002. direction: 1,
  21003. weight: 1,
  21004. directionBackwards: false,
  21005. mirroredLoop: false
  21006. };
  21007. this.animationsMap[ name ] = animation;
  21008. this.animationsList.push( animation );
  21009. };
  21010. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21011. var pattern = /([a-z]+)(\d+)/;
  21012. var firstAnimation, frameRanges = {};
  21013. var geometry = this.geometry;
  21014. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21015. var morph = geometry.morphTargets[ i ];
  21016. var chunks = morph.name.match( pattern );
  21017. if ( chunks && chunks.length > 1 ) {
  21018. var name = chunks[ 1 ];
  21019. var num = chunks[ 2 ];
  21020. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21021. var range = frameRanges[ name ];
  21022. if ( i < range.start ) range.start = i;
  21023. if ( i > range.end ) range.end = i;
  21024. if ( ! firstAnimation ) firstAnimation = name;
  21025. }
  21026. }
  21027. for ( var name in frameRanges ) {
  21028. var range = frameRanges[ name ];
  21029. this.createAnimation( name, range.start, range.end, fps );
  21030. }
  21031. this.firstAnimation = firstAnimation;
  21032. };
  21033. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21034. var animation = this.animationsMap[ name ];
  21035. if ( animation ) {
  21036. animation.direction = 1;
  21037. animation.directionBackwards = false;
  21038. }
  21039. };
  21040. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21041. var animation = this.animationsMap[ name ];
  21042. if ( animation ) {
  21043. animation.direction = -1;
  21044. animation.directionBackwards = true;
  21045. }
  21046. };
  21047. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21048. var animation = this.animationsMap[ name ];
  21049. if ( animation ) {
  21050. animation.fps = fps;
  21051. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21052. }
  21053. };
  21054. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21055. var animation = this.animationsMap[ name ];
  21056. if ( animation ) {
  21057. animation.duration = duration;
  21058. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21059. }
  21060. };
  21061. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21062. var animation = this.animationsMap[ name ];
  21063. if ( animation ) {
  21064. animation.weight = weight;
  21065. }
  21066. };
  21067. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21068. var animation = this.animationsMap[ name ];
  21069. if ( animation ) {
  21070. animation.time = time;
  21071. }
  21072. };
  21073. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21074. var time = 0;
  21075. var animation = this.animationsMap[ name ];
  21076. if ( animation ) {
  21077. time = animation.time;
  21078. }
  21079. return time;
  21080. };
  21081. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21082. var duration = -1;
  21083. var animation = this.animationsMap[ name ];
  21084. if ( animation ) {
  21085. duration = animation.duration;
  21086. }
  21087. return duration;
  21088. };
  21089. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21090. var animation = this.animationsMap[ name ];
  21091. if ( animation ) {
  21092. animation.time = 0;
  21093. animation.active = true;
  21094. } else {
  21095. console.warn( "animation[" + name + "] undefined" );
  21096. }
  21097. };
  21098. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21099. var animation = this.animationsMap[ name ];
  21100. if ( animation ) {
  21101. animation.active = false;
  21102. }
  21103. };
  21104. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21105. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21106. var animation = this.animationsList[ i ];
  21107. if ( ! animation.active ) continue;
  21108. var frameTime = animation.duration / animation.length;
  21109. animation.time += animation.direction * delta;
  21110. if ( animation.mirroredLoop ) {
  21111. if ( animation.time > animation.duration || animation.time < 0 ) {
  21112. animation.direction *= -1;
  21113. if ( animation.time > animation.duration ) {
  21114. animation.time = animation.duration;
  21115. animation.directionBackwards = true;
  21116. }
  21117. if ( animation.time < 0 ) {
  21118. animation.time = 0;
  21119. animation.directionBackwards = false;
  21120. }
  21121. }
  21122. } else {
  21123. animation.time = animation.time % animation.duration;
  21124. if ( animation.time < 0 ) animation.time += animation.duration;
  21125. }
  21126. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21127. var weight = animation.weight;
  21128. if ( keyframe !== animation.currentFrame ) {
  21129. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21130. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21131. this.morphTargetInfluences[ keyframe ] = 0;
  21132. animation.lastFrame = animation.currentFrame;
  21133. animation.currentFrame = keyframe;
  21134. }
  21135. var mix = ( animation.time % frameTime ) / frameTime;
  21136. if ( animation.directionBackwards ) mix = 1 - mix;
  21137. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21138. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21139. }
  21140. };
  21141. /**
  21142. * @author mikael emtinger / http://gomo.se/
  21143. * @author alteredq / http://alteredqualia.com/
  21144. */
  21145. THREE.LensFlarePlugin = function ( ) {
  21146. var _gl, _renderer, _precision, _lensFlare = {};
  21147. this.init = function ( renderer ) {
  21148. _gl = renderer.context;
  21149. _renderer = renderer;
  21150. _precision = renderer.getPrecision();
  21151. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21152. _lensFlare.faces = new Uint16Array( 6 );
  21153. var i = 0;
  21154. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21155. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21156. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21157. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21158. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21159. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21160. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21161. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21162. i = 0;
  21163. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21164. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21165. // buffers
  21166. _lensFlare.vertexBuffer = _gl.createBuffer();
  21167. _lensFlare.elementBuffer = _gl.createBuffer();
  21168. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21169. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21170. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21171. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21172. // textures
  21173. _lensFlare.tempTexture = _gl.createTexture();
  21174. _lensFlare.occlusionTexture = _gl.createTexture();
  21175. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21176. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21177. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21178. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21179. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21180. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21181. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21182. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21183. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21184. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21185. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21186. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21187. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21188. _lensFlare.hasVertexTexture = false;
  21189. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21190. } else {
  21191. _lensFlare.hasVertexTexture = true;
  21192. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21193. }
  21194. _lensFlare.attributes = {};
  21195. _lensFlare.uniforms = {};
  21196. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21197. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21198. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21199. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21200. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21201. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21202. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21203. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21204. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21205. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21206. };
  21207. /*
  21208. * Render lens flares
  21209. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21210. * reads these back and calculates occlusion.
  21211. * Then _lensFlare.update_lensFlares() is called to re-position and
  21212. * update transparency of flares. Then they are rendered.
  21213. *
  21214. */
  21215. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21216. var flares = scene.__webglFlares,
  21217. nFlares = flares.length;
  21218. if ( ! nFlares ) return;
  21219. var tempPosition = new THREE.Vector3();
  21220. var invAspect = viewportHeight / viewportWidth,
  21221. halfViewportWidth = viewportWidth * 0.5,
  21222. halfViewportHeight = viewportHeight * 0.5;
  21223. var size = 16 / viewportHeight,
  21224. scale = new THREE.Vector2( size * invAspect, size );
  21225. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21226. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21227. var uniforms = _lensFlare.uniforms,
  21228. attributes = _lensFlare.attributes;
  21229. // set _lensFlare program and reset blending
  21230. _gl.useProgram( _lensFlare.program );
  21231. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21232. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21233. // loop through all lens flares to update their occlusion and positions
  21234. // setup gl and common used attribs/unforms
  21235. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21236. _gl.uniform1i( uniforms.map, 1 );
  21237. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21238. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21239. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21240. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21241. _gl.disable( _gl.CULL_FACE );
  21242. _gl.depthMask( false );
  21243. var i, j, jl, flare, sprite;
  21244. for ( i = 0; i < nFlares; i ++ ) {
  21245. size = 16 / viewportHeight;
  21246. scale.set( size * invAspect, size );
  21247. // calc object screen position
  21248. flare = flares[ i ];
  21249. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21250. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21251. tempPosition.applyMatrix4( camera.projectionMatrix );
  21252. // setup arrays for gl programs
  21253. screenPosition.copy( tempPosition )
  21254. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21255. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21256. // screen cull
  21257. if ( _lensFlare.hasVertexTexture || (
  21258. screenPositionPixels.x > 0 &&
  21259. screenPositionPixels.x < viewportWidth &&
  21260. screenPositionPixels.y > 0 &&
  21261. screenPositionPixels.y < viewportHeight ) ) {
  21262. // save current RGB to temp texture
  21263. _gl.activeTexture( _gl.TEXTURE1 );
  21264. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21265. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21266. // render pink quad
  21267. _gl.uniform1i( uniforms.renderType, 0 );
  21268. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21269. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21270. _gl.disable( _gl.BLEND );
  21271. _gl.enable( _gl.DEPTH_TEST );
  21272. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21273. // copy result to occlusionMap
  21274. _gl.activeTexture( _gl.TEXTURE0 );
  21275. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21276. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21277. // restore graphics
  21278. _gl.uniform1i( uniforms.renderType, 1 );
  21279. _gl.disable( _gl.DEPTH_TEST );
  21280. _gl.activeTexture( _gl.TEXTURE1 );
  21281. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21282. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21283. // update object positions
  21284. flare.positionScreen.copy( screenPosition )
  21285. if ( flare.customUpdateCallback ) {
  21286. flare.customUpdateCallback( flare );
  21287. } else {
  21288. flare.updateLensFlares();
  21289. }
  21290. // render flares
  21291. _gl.uniform1i( uniforms.renderType, 2 );
  21292. _gl.enable( _gl.BLEND );
  21293. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21294. sprite = flare.lensFlares[ j ];
  21295. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21296. screenPosition.x = sprite.x;
  21297. screenPosition.y = sprite.y;
  21298. screenPosition.z = sprite.z;
  21299. size = sprite.size * sprite.scale / viewportHeight;
  21300. scale.x = size * invAspect;
  21301. scale.y = size;
  21302. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21303. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21304. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21305. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21306. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21307. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21308. _renderer.setTexture( sprite.texture, 1 );
  21309. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21310. }
  21311. }
  21312. }
  21313. }
  21314. // restore gl
  21315. _gl.enable( _gl.CULL_FACE );
  21316. _gl.enable( _gl.DEPTH_TEST );
  21317. _gl.depthMask( true );
  21318. };
  21319. function createProgram ( shader, precision ) {
  21320. var program = _gl.createProgram();
  21321. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21322. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21323. var prefix = "precision " + precision + " float;\n";
  21324. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21325. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21326. _gl.compileShader( fragmentShader );
  21327. _gl.compileShader( vertexShader );
  21328. _gl.attachShader( program, fragmentShader );
  21329. _gl.attachShader( program, vertexShader );
  21330. _gl.linkProgram( program );
  21331. return program;
  21332. };
  21333. };
  21334. /**
  21335. * @author alteredq / http://alteredqualia.com/
  21336. */
  21337. THREE.ShadowMapPlugin = function ( ) {
  21338. var _gl,
  21339. _renderer,
  21340. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21341. _frustum = new THREE.Frustum(),
  21342. _projScreenMatrix = new THREE.Matrix4(),
  21343. _min = new THREE.Vector3(),
  21344. _max = new THREE.Vector3();
  21345. this.init = function ( renderer ) {
  21346. _gl = renderer.context;
  21347. _renderer = renderer;
  21348. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21349. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21350. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21351. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21352. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21353. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21354. _depthMaterial._shadowPass = true;
  21355. _depthMaterialMorph._shadowPass = true;
  21356. _depthMaterialSkin._shadowPass = true;
  21357. _depthMaterialMorphSkin._shadowPass = true;
  21358. };
  21359. this.render = function ( scene, camera ) {
  21360. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21361. this.update( scene, camera );
  21362. };
  21363. this.update = function ( scene, camera ) {
  21364. var i, il, j, jl, n,
  21365. shadowMap, shadowMatrix, shadowCamera,
  21366. program, buffer, material,
  21367. webglObject, object, light,
  21368. renderList,
  21369. lights = [],
  21370. k = 0,
  21371. fog = null;
  21372. // set GL state for depth map
  21373. _gl.clearColor( 1, 1, 1, 1 );
  21374. _gl.disable( _gl.BLEND );
  21375. _gl.enable( _gl.CULL_FACE );
  21376. _gl.frontFace( _gl.CCW );
  21377. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21378. _gl.cullFace( _gl.FRONT );
  21379. } else {
  21380. _gl.cullFace( _gl.BACK );
  21381. }
  21382. _renderer.setDepthTest( true );
  21383. // preprocess lights
  21384. // - skip lights that are not casting shadows
  21385. // - create virtual lights for cascaded shadow maps
  21386. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21387. light = scene.__lights[ i ];
  21388. if ( ! light.castShadow ) continue;
  21389. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21390. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21391. var virtualLight;
  21392. if ( ! light.shadowCascadeArray[ n ] ) {
  21393. virtualLight = createVirtualLight( light, n );
  21394. virtualLight.originalCamera = camera;
  21395. var gyro = new THREE.Gyroscope();
  21396. gyro.position = light.shadowCascadeOffset;
  21397. gyro.add( virtualLight );
  21398. gyro.add( virtualLight.target );
  21399. camera.add( gyro );
  21400. light.shadowCascadeArray[ n ] = virtualLight;
  21401. console.log( "Created virtualLight", virtualLight );
  21402. } else {
  21403. virtualLight = light.shadowCascadeArray[ n ];
  21404. }
  21405. updateVirtualLight( light, n );
  21406. lights[ k ] = virtualLight;
  21407. k ++;
  21408. }
  21409. } else {
  21410. lights[ k ] = light;
  21411. k ++;
  21412. }
  21413. }
  21414. // render depth map
  21415. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21416. light = lights[ i ];
  21417. if ( ! light.shadowMap ) {
  21418. var shadowFilter = THREE.LinearFilter;
  21419. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21420. shadowFilter = THREE.NearestFilter;
  21421. }
  21422. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21423. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21424. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21425. light.shadowMatrix = new THREE.Matrix4();
  21426. }
  21427. if ( ! light.shadowCamera ) {
  21428. if ( light instanceof THREE.SpotLight ) {
  21429. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21430. } else if ( light instanceof THREE.DirectionalLight ) {
  21431. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21432. } else {
  21433. console.error( "Unsupported light type for shadow" );
  21434. continue;
  21435. }
  21436. scene.add( light.shadowCamera );
  21437. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21438. }
  21439. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21440. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21441. light.shadowCamera.add( light.cameraHelper );
  21442. }
  21443. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21444. updateShadowCamera( camera, light );
  21445. }
  21446. shadowMap = light.shadowMap;
  21447. shadowMatrix = light.shadowMatrix;
  21448. shadowCamera = light.shadowCamera;
  21449. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  21450. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  21451. shadowCamera.updateMatrixWorld();
  21452. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21453. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21454. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21455. // compute shadow matrix
  21456. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21457. 0.0, 0.5, 0.0, 0.5,
  21458. 0.0, 0.0, 0.5, 0.5,
  21459. 0.0, 0.0, 0.0, 1.0 );
  21460. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  21461. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  21462. // update camera matrices and frustum
  21463. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21464. _frustum.setFromMatrix( _projScreenMatrix );
  21465. // render shadow map
  21466. _renderer.setRenderTarget( shadowMap );
  21467. _renderer.clear();
  21468. // set object matrices & frustum culling
  21469. renderList = scene.__webglObjects;
  21470. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21471. webglObject = renderList[ j ];
  21472. object = webglObject.object;
  21473. webglObject.render = false;
  21474. if ( object.visible && object.castShadow ) {
  21475. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21476. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21477. webglObject.render = true;
  21478. }
  21479. }
  21480. }
  21481. // render regular objects
  21482. var objectMaterial, useMorphing, useSkinning;
  21483. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21484. webglObject = renderList[ j ];
  21485. if ( webglObject.render ) {
  21486. object = webglObject.object;
  21487. buffer = webglObject.buffer;
  21488. // culling is overriden globally for all objects
  21489. // while rendering depth map
  21490. // need to deal with MeshFaceMaterial somehow
  21491. // in that case just use the first of material.materials for now
  21492. // (proper solution would require to break objects by materials
  21493. // similarly to regular rendering and then set corresponding
  21494. // depth materials per each chunk instead of just once per object)
  21495. objectMaterial = getObjectMaterial( object );
  21496. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21497. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21498. if ( object.customDepthMaterial ) {
  21499. material = object.customDepthMaterial;
  21500. } else if ( useSkinning ) {
  21501. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21502. } else if ( useMorphing ) {
  21503. material = _depthMaterialMorph;
  21504. } else {
  21505. material = _depthMaterial;
  21506. }
  21507. if ( buffer instanceof THREE.BufferGeometry ) {
  21508. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21509. } else {
  21510. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21511. }
  21512. }
  21513. }
  21514. // set matrices and render immediate objects
  21515. renderList = scene.__webglObjectsImmediate;
  21516. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21517. webglObject = renderList[ j ];
  21518. object = webglObject.object;
  21519. if ( object.visible && object.castShadow ) {
  21520. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21521. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21522. }
  21523. }
  21524. }
  21525. // restore GL state
  21526. var clearColor = _renderer.getClearColor(),
  21527. clearAlpha = _renderer.getClearAlpha();
  21528. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21529. _gl.enable( _gl.BLEND );
  21530. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21531. _gl.cullFace( _gl.BACK );
  21532. }
  21533. };
  21534. function createVirtualLight( light, cascade ) {
  21535. var virtualLight = new THREE.DirectionalLight();
  21536. virtualLight.isVirtual = true;
  21537. virtualLight.onlyShadow = true;
  21538. virtualLight.castShadow = true;
  21539. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21540. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21541. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21542. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21543. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21544. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21545. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21546. virtualLight.shadowDarkness = light.shadowDarkness;
  21547. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21548. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21549. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21550. virtualLight.pointsWorld = [];
  21551. virtualLight.pointsFrustum = [];
  21552. var pointsWorld = virtualLight.pointsWorld,
  21553. pointsFrustum = virtualLight.pointsFrustum;
  21554. for ( var i = 0; i < 8; i ++ ) {
  21555. pointsWorld[ i ] = new THREE.Vector3();
  21556. pointsFrustum[ i ] = new THREE.Vector3();
  21557. }
  21558. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21559. var farZ = light.shadowCascadeFarZ[ cascade ];
  21560. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21561. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21562. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21563. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21564. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21565. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21566. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21567. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21568. return virtualLight;
  21569. }
  21570. // Synchronize virtual light with the original light
  21571. function updateVirtualLight( light, cascade ) {
  21572. var virtualLight = light.shadowCascadeArray[ cascade ];
  21573. virtualLight.position.copy( light.position );
  21574. virtualLight.target.position.copy( light.target.position );
  21575. virtualLight.lookAt( virtualLight.target );
  21576. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21577. virtualLight.shadowDarkness = light.shadowDarkness;
  21578. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21579. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21580. var farZ = light.shadowCascadeFarZ[ cascade ];
  21581. var pointsFrustum = virtualLight.pointsFrustum;
  21582. pointsFrustum[ 0 ].z = nearZ;
  21583. pointsFrustum[ 1 ].z = nearZ;
  21584. pointsFrustum[ 2 ].z = nearZ;
  21585. pointsFrustum[ 3 ].z = nearZ;
  21586. pointsFrustum[ 4 ].z = farZ;
  21587. pointsFrustum[ 5 ].z = farZ;
  21588. pointsFrustum[ 6 ].z = farZ;
  21589. pointsFrustum[ 7 ].z = farZ;
  21590. }
  21591. // Fit shadow camera's ortho frustum to camera frustum
  21592. function updateShadowCamera( camera, light ) {
  21593. var shadowCamera = light.shadowCamera,
  21594. pointsFrustum = light.pointsFrustum,
  21595. pointsWorld = light.pointsWorld;
  21596. _min.set( Infinity, Infinity, Infinity );
  21597. _max.set( -Infinity, -Infinity, -Infinity );
  21598. for ( var i = 0; i < 8; i ++ ) {
  21599. var p = pointsWorld[ i ];
  21600. p.copy( pointsFrustum[ i ] );
  21601. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21602. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21603. if ( p.x < _min.x ) _min.x = p.x;
  21604. if ( p.x > _max.x ) _max.x = p.x;
  21605. if ( p.y < _min.y ) _min.y = p.y;
  21606. if ( p.y > _max.y ) _max.y = p.y;
  21607. if ( p.z < _min.z ) _min.z = p.z;
  21608. if ( p.z > _max.z ) _max.z = p.z;
  21609. }
  21610. shadowCamera.left = _min.x;
  21611. shadowCamera.right = _max.x;
  21612. shadowCamera.top = _max.y;
  21613. shadowCamera.bottom = _min.y;
  21614. // can't really fit near/far
  21615. //shadowCamera.near = _min.z;
  21616. //shadowCamera.far = _max.z;
  21617. shadowCamera.updateProjectionMatrix();
  21618. }
  21619. // For the moment just ignore objects that have multiple materials with different animation methods
  21620. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21621. function getObjectMaterial( object ) {
  21622. return object.material instanceof THREE.MeshFaceMaterial
  21623. ? object.material.materials[ 0 ]
  21624. : object.material;
  21625. };
  21626. };
  21627. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21628. /**
  21629. * @author mikael emtinger / http://gomo.se/
  21630. * @author alteredq / http://alteredqualia.com/
  21631. */
  21632. THREE.SpritePlugin = function ( ) {
  21633. var _gl, _renderer, _precision, _sprite = {};
  21634. this.init = function ( renderer ) {
  21635. _gl = renderer.context;
  21636. _renderer = renderer;
  21637. _precision = renderer.getPrecision();
  21638. _sprite.vertices = new Float32Array( 8 + 8 );
  21639. _sprite.faces = new Uint16Array( 6 );
  21640. var i = 0;
  21641. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21642. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21643. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21644. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21645. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21646. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21647. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21648. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21649. i = 0;
  21650. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21651. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21652. _sprite.vertexBuffer = _gl.createBuffer();
  21653. _sprite.elementBuffer = _gl.createBuffer();
  21654. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21655. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21656. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21657. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21658. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21659. _sprite.attributes = {};
  21660. _sprite.uniforms = {};
  21661. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21662. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21663. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21664. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21665. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21666. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21667. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21668. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21669. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21670. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21671. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21672. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21673. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21674. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21675. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21676. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21677. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21678. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21679. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21680. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21681. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21682. };
  21683. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21684. var sprites = scene.__webglSprites,
  21685. nSprites = sprites.length;
  21686. if ( ! nSprites ) return;
  21687. var attributes = _sprite.attributes,
  21688. uniforms = _sprite.uniforms;
  21689. var invAspect = viewportHeight / viewportWidth;
  21690. var halfViewportWidth = viewportWidth * 0.5,
  21691. halfViewportHeight = viewportHeight * 0.5;
  21692. // setup gl
  21693. _gl.useProgram( _sprite.program );
  21694. _gl.enableVertexAttribArray( attributes.position );
  21695. _gl.enableVertexAttribArray( attributes.uv );
  21696. _gl.disable( _gl.CULL_FACE );
  21697. _gl.enable( _gl.BLEND );
  21698. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21699. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21700. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21701. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21702. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21703. _gl.activeTexture( _gl.TEXTURE0 );
  21704. _gl.uniform1i( uniforms.map, 0 );
  21705. var oldFogType = 0;
  21706. var sceneFogType = 0;
  21707. var fog = scene.fog;
  21708. if ( fog ) {
  21709. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21710. if ( fog instanceof THREE.Fog ) {
  21711. _gl.uniform1f( uniforms.fogNear, fog.near );
  21712. _gl.uniform1f( uniforms.fogFar, fog.far );
  21713. _gl.uniform1i( uniforms.fogType, 1 );
  21714. oldFogType = 1;
  21715. sceneFogType = 1;
  21716. } else if ( fog instanceof THREE.FogExp2 ) {
  21717. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21718. _gl.uniform1i( uniforms.fogType, 2 );
  21719. oldFogType = 2;
  21720. sceneFogType = 2;
  21721. }
  21722. } else {
  21723. _gl.uniform1i( uniforms.fogType, 0 );
  21724. oldFogType = 0;
  21725. sceneFogType = 0;
  21726. }
  21727. // update positions and sort
  21728. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21729. for( i = 0; i < nSprites; i ++ ) {
  21730. sprite = sprites[ i ];
  21731. material = sprite.material;
  21732. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21733. if ( ! material.useScreenCoordinates ) {
  21734. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  21735. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21736. } else {
  21737. sprite.z = - sprite.position.z;
  21738. }
  21739. }
  21740. sprites.sort( painterSortStable );
  21741. // render all sprites
  21742. for( i = 0; i < nSprites; i ++ ) {
  21743. sprite = sprites[ i ];
  21744. material = sprite.material;
  21745. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21746. if ( material.map && material.map.image && material.map.image.width ) {
  21747. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21748. if ( material.useScreenCoordinates === true ) {
  21749. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21750. _gl.uniform3f(
  21751. uniforms.screenPosition,
  21752. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21753. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21754. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21755. );
  21756. scale[ 0 ] = _renderer.devicePixelRatio;
  21757. scale[ 1 ] = _renderer.devicePixelRatio;
  21758. } else {
  21759. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21760. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21761. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21762. scale[ 0 ] = 1;
  21763. scale[ 1 ] = 1;
  21764. }
  21765. if ( scene.fog && material.fog ) {
  21766. fogType = sceneFogType;
  21767. } else {
  21768. fogType = 0;
  21769. }
  21770. if ( oldFogType !== fogType ) {
  21771. _gl.uniform1i( uniforms.fogType, fogType );
  21772. oldFogType = fogType;
  21773. }
  21774. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21775. scale[ 0 ] *= size * invAspect * sprite.scale.x
  21776. scale[ 1 ] *= size * sprite.scale.y;
  21777. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21778. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21779. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21780. _gl.uniform1f( uniforms.opacity, material.opacity );
  21781. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21782. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21783. _gl.uniform2fv( uniforms.scale, scale );
  21784. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21785. _renderer.setDepthTest( material.depthTest );
  21786. _renderer.setDepthWrite( material.depthWrite );
  21787. _renderer.setTexture( material.map, 0 );
  21788. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21789. }
  21790. }
  21791. // restore gl
  21792. _gl.enable( _gl.CULL_FACE );
  21793. };
  21794. function createProgram ( shader, precision ) {
  21795. var program = _gl.createProgram();
  21796. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21797. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21798. var prefix = "precision " + precision + " float;\n";
  21799. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21800. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21801. _gl.compileShader( fragmentShader );
  21802. _gl.compileShader( vertexShader );
  21803. _gl.attachShader( program, fragmentShader );
  21804. _gl.attachShader( program, vertexShader );
  21805. _gl.linkProgram( program );
  21806. return program;
  21807. };
  21808. function painterSortStable ( a, b ) {
  21809. if ( a.z !== b.z ) {
  21810. return b.z - a.z;
  21811. } else {
  21812. return b.id - a.id;
  21813. }
  21814. };
  21815. };
  21816. /**
  21817. * @author alteredq / http://alteredqualia.com/
  21818. */
  21819. THREE.DepthPassPlugin = function ( ) {
  21820. this.enabled = false;
  21821. this.renderTarget = null;
  21822. var _gl,
  21823. _renderer,
  21824. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21825. _frustum = new THREE.Frustum(),
  21826. _projScreenMatrix = new THREE.Matrix4();
  21827. this.init = function ( renderer ) {
  21828. _gl = renderer.context;
  21829. _renderer = renderer;
  21830. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21831. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21832. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21833. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21834. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21835. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21836. _depthMaterial._shadowPass = true;
  21837. _depthMaterialMorph._shadowPass = true;
  21838. _depthMaterialSkin._shadowPass = true;
  21839. _depthMaterialMorphSkin._shadowPass = true;
  21840. };
  21841. this.render = function ( scene, camera ) {
  21842. if ( ! this.enabled ) return;
  21843. this.update( scene, camera );
  21844. };
  21845. this.update = function ( scene, camera ) {
  21846. var i, il, j, jl, n,
  21847. program, buffer, material,
  21848. webglObject, object, light,
  21849. renderList,
  21850. fog = null;
  21851. // set GL state for depth map
  21852. _gl.clearColor( 1, 1, 1, 1 );
  21853. _gl.disable( _gl.BLEND );
  21854. _renderer.setDepthTest( true );
  21855. // update scene
  21856. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21857. // update camera matrices and frustum
  21858. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21859. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21860. _frustum.setFromMatrix( _projScreenMatrix );
  21861. // render depth map
  21862. _renderer.setRenderTarget( this.renderTarget );
  21863. _renderer.clear();
  21864. // set object matrices & frustum culling
  21865. renderList = scene.__webglObjects;
  21866. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21867. webglObject = renderList[ j ];
  21868. object = webglObject.object;
  21869. webglObject.render = false;
  21870. if ( object.visible ) {
  21871. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21872. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21873. webglObject.render = true;
  21874. }
  21875. }
  21876. }
  21877. // render regular objects
  21878. var objectMaterial, useMorphing, useSkinning;
  21879. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21880. webglObject = renderList[ j ];
  21881. if ( webglObject.render ) {
  21882. object = webglObject.object;
  21883. buffer = webglObject.buffer;
  21884. // todo: create proper depth material for particles
  21885. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21886. objectMaterial = getObjectMaterial( object );
  21887. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21888. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21889. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21890. if ( object.customDepthMaterial ) {
  21891. material = object.customDepthMaterial;
  21892. } else if ( useSkinning ) {
  21893. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21894. } else if ( useMorphing ) {
  21895. material = _depthMaterialMorph;
  21896. } else {
  21897. material = _depthMaterial;
  21898. }
  21899. if ( buffer instanceof THREE.BufferGeometry ) {
  21900. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21901. } else {
  21902. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21903. }
  21904. }
  21905. }
  21906. // set matrices and render immediate objects
  21907. renderList = scene.__webglObjectsImmediate;
  21908. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21909. webglObject = renderList[ j ];
  21910. object = webglObject.object;
  21911. if ( object.visible ) {
  21912. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21913. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21914. }
  21915. }
  21916. // restore GL state
  21917. var clearColor = _renderer.getClearColor(),
  21918. clearAlpha = _renderer.getClearAlpha();
  21919. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21920. _gl.enable( _gl.BLEND );
  21921. };
  21922. // For the moment just ignore objects that have multiple materials with different animation methods
  21923. // Only the first material will be taken into account for deciding which depth material to use
  21924. function getObjectMaterial( object ) {
  21925. return object.material instanceof THREE.MeshFaceMaterial
  21926. ? object.material.materials[ 0 ]
  21927. : object.material;
  21928. };
  21929. };
  21930. /**
  21931. * @author mikael emtinger / http://gomo.se/
  21932. *
  21933. */
  21934. THREE.ShaderFlares = {
  21935. 'lensFlareVertexTexture': {
  21936. vertexShader: [
  21937. "uniform lowp int renderType;",
  21938. "uniform vec3 screenPosition;",
  21939. "uniform vec2 scale;",
  21940. "uniform float rotation;",
  21941. "uniform sampler2D occlusionMap;",
  21942. "attribute vec2 position;",
  21943. "attribute vec2 uv;",
  21944. "varying vec2 vUV;",
  21945. "varying float vVisibility;",
  21946. "void main() {",
  21947. "vUV = uv;",
  21948. "vec2 pos = position;",
  21949. "if( renderType == 2 ) {",
  21950. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21951. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21952. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21953. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21954. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21955. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21956. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21957. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21958. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21959. "vVisibility = ( visibility.r / 9.0 ) *",
  21960. "( 1.0 - visibility.g / 9.0 ) *",
  21961. "( visibility.b / 9.0 ) *",
  21962. "( 1.0 - visibility.a / 9.0 );",
  21963. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21964. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21965. "}",
  21966. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21967. "}"
  21968. ].join( "\n" ),
  21969. fragmentShader: [
  21970. "uniform lowp int renderType;",
  21971. "uniform sampler2D map;",
  21972. "uniform float opacity;",
  21973. "uniform vec3 color;",
  21974. "varying vec2 vUV;",
  21975. "varying float vVisibility;",
  21976. "void main() {",
  21977. // pink square
  21978. "if( renderType == 0 ) {",
  21979. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21980. // restore
  21981. "} else if( renderType == 1 ) {",
  21982. "gl_FragColor = texture2D( map, vUV );",
  21983. // flare
  21984. "} else {",
  21985. "vec4 texture = texture2D( map, vUV );",
  21986. "texture.a *= opacity * vVisibility;",
  21987. "gl_FragColor = texture;",
  21988. "gl_FragColor.rgb *= color;",
  21989. "}",
  21990. "}"
  21991. ].join( "\n" )
  21992. },
  21993. 'lensFlare': {
  21994. vertexShader: [
  21995. "uniform lowp int renderType;",
  21996. "uniform vec3 screenPosition;",
  21997. "uniform vec2 scale;",
  21998. "uniform float rotation;",
  21999. "attribute vec2 position;",
  22000. "attribute vec2 uv;",
  22001. "varying vec2 vUV;",
  22002. "void main() {",
  22003. "vUV = uv;",
  22004. "vec2 pos = position;",
  22005. "if( renderType == 2 ) {",
  22006. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22007. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22008. "}",
  22009. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22010. "}"
  22011. ].join( "\n" ),
  22012. fragmentShader: [
  22013. "precision mediump float;",
  22014. "uniform lowp int renderType;",
  22015. "uniform sampler2D map;",
  22016. "uniform sampler2D occlusionMap;",
  22017. "uniform float opacity;",
  22018. "uniform vec3 color;",
  22019. "varying vec2 vUV;",
  22020. "void main() {",
  22021. // pink square
  22022. "if( renderType == 0 ) {",
  22023. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22024. // restore
  22025. "} else if( renderType == 1 ) {",
  22026. "gl_FragColor = texture2D( map, vUV );",
  22027. // flare
  22028. "} else {",
  22029. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  22030. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  22031. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  22032. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22033. "visibility = ( 1.0 - visibility / 4.0 );",
  22034. "vec4 texture = texture2D( map, vUV );",
  22035. "texture.a *= opacity * visibility;",
  22036. "gl_FragColor = texture;",
  22037. "gl_FragColor.rgb *= color;",
  22038. "}",
  22039. "}"
  22040. ].join( "\n" )
  22041. }
  22042. };
  22043. /**
  22044. * @author mikael emtinger / http://gomo.se/
  22045. * @author alteredq / http://alteredqualia.com/
  22046. *
  22047. */
  22048. THREE.ShaderSprite = {
  22049. 'sprite': {
  22050. vertexShader: [
  22051. "uniform int useScreenCoordinates;",
  22052. "uniform int sizeAttenuation;",
  22053. "uniform vec3 screenPosition;",
  22054. "uniform mat4 modelViewMatrix;",
  22055. "uniform mat4 projectionMatrix;",
  22056. "uniform float rotation;",
  22057. "uniform vec2 scale;",
  22058. "uniform vec2 alignment;",
  22059. "uniform vec2 uvOffset;",
  22060. "uniform vec2 uvScale;",
  22061. "attribute vec2 position;",
  22062. "attribute vec2 uv;",
  22063. "varying vec2 vUV;",
  22064. "void main() {",
  22065. "vUV = uvOffset + uv * uvScale;",
  22066. "vec2 alignedPosition = position + alignment;",
  22067. "vec2 rotatedPosition;",
  22068. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  22069. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  22070. "vec4 finalPosition;",
  22071. "if( useScreenCoordinates != 0 ) {",
  22072. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  22073. "} else {",
  22074. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  22075. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  22076. "}",
  22077. "gl_Position = finalPosition;",
  22078. "}"
  22079. ].join( "\n" ),
  22080. fragmentShader: [
  22081. "uniform vec3 color;",
  22082. "uniform sampler2D map;",
  22083. "uniform float opacity;",
  22084. "uniform int fogType;",
  22085. "uniform vec3 fogColor;",
  22086. "uniform float fogDensity;",
  22087. "uniform float fogNear;",
  22088. "uniform float fogFar;",
  22089. "uniform float alphaTest;",
  22090. "varying vec2 vUV;",
  22091. "void main() {",
  22092. "vec4 texture = texture2D( map, vUV );",
  22093. "if ( texture.a < alphaTest ) discard;",
  22094. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  22095. "if ( fogType > 0 ) {",
  22096. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  22097. "float fogFactor = 0.0;",
  22098. "if ( fogType == 1 ) {",
  22099. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  22100. "} else {",
  22101. "const float LOG2 = 1.442695;",
  22102. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  22103. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  22104. "}",
  22105. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  22106. "}",
  22107. "}"
  22108. ].join( "\n" )
  22109. }
  22110. };