three.js 846 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '54dev' };
  6. self.console = self.console || {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. self.Int32Array = self.Int32Array || Array;
  14. self.Float32Array = self.Float32Array || Array;
  15. // Shims for "startsWith", "endsWith", and "trim" for browsers where this is not yet implemented
  16. // not sure we should have this, or at least not have it here
  17. // http://stackoverflow.com/questions/646628/javascript-startswith
  18. // http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript
  19. // http://wiki.ecmascript.org/doku.php?id=harmony%3astring_extras
  20. String.prototype.startsWith = String.prototype.startsWith || function ( str ) {
  21. return this.slice( 0, str.length ) === str;
  22. };
  23. String.prototype.endsWith = String.prototype.endsWith || function ( str ) {
  24. var t = String( str );
  25. var index = this.lastIndexOf( t );
  26. return ( -1 < index && index ) === (this.length - t.length);
  27. };
  28. String.prototype.trim = String.prototype.trim || function () {
  29. return this.replace( /^\s+|\s+$/g, '' );
  30. };
  31. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  32. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  33. // requestAnimationFrame polyfill by Erik Möller
  34. // fixes from Paul Irish and Tino Zijdel
  35. ( function () {
  36. var lastTime = 0;
  37. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  38. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  39. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  40. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  41. }
  42. if ( window.requestAnimationFrame === undefined ) {
  43. window.requestAnimationFrame = function ( callback, element ) {
  44. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  45. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  46. lastTime = currTime + timeToCall;
  47. return id;
  48. };
  49. }
  50. window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
  51. }() );
  52. // 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. copy: function ( v ) {
  408. this.x = v.x;
  409. this.y = v.y;
  410. return this;
  411. },
  412. addScalar: function ( s ) {
  413. this.x += s;
  414. this.y += s;
  415. return this;
  416. },
  417. add: function ( a, b ) {
  418. this.x = a.x + b.x;
  419. this.y = a.y + b.y;
  420. return this;
  421. },
  422. addSelf: function ( v ) {
  423. this.x += v.x;
  424. this.y += v.y;
  425. return this;
  426. },
  427. sub: function ( a, b ) {
  428. this.x = a.x - b.x;
  429. this.y = a.y - b.y;
  430. return this;
  431. },
  432. subSelf: function ( v ) {
  433. this.x -= v.x;
  434. this.y -= v.y;
  435. return this;
  436. },
  437. multiplyScalar: function ( s ) {
  438. this.x *= s;
  439. this.y *= s;
  440. return this;
  441. },
  442. divideScalar: function ( s ) {
  443. if ( s ) {
  444. this.x /= s;
  445. this.y /= s;
  446. } else {
  447. this.set( 0, 0 );
  448. }
  449. return this;
  450. },
  451. minSelf: function ( v ) {
  452. if ( this.x > v.x ) {
  453. this.x = v.x;
  454. }
  455. if ( this.y > v.y ) {
  456. this.y = v.y;
  457. }
  458. return this;
  459. },
  460. maxSelf: function ( v ) {
  461. if ( this.x < v.x ) {
  462. this.x = v.x;
  463. }
  464. if ( this.y < v.y ) {
  465. this.y = v.y;
  466. }
  467. return this;
  468. },
  469. clampSelf: function ( min, max ) {
  470. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  471. if ( this.x < min.x ) {
  472. this.x = min.x;
  473. } else if ( this.x > max.x ) {
  474. this.x = max.x;
  475. }
  476. if ( this.y < min.y ) {
  477. this.y = min.y;
  478. } else if ( this.y > max.y ) {
  479. this.y = max.y;
  480. }
  481. return this;
  482. },
  483. negate: function() {
  484. return this.multiplyScalar( - 1 );
  485. },
  486. dot: function ( v ) {
  487. return this.x * v.x + this.y * v.y;
  488. },
  489. lengthSq: function () {
  490. return this.x * this.x + this.y * this.y;
  491. },
  492. length: function () {
  493. return Math.sqrt( this.lengthSq() );
  494. },
  495. normalize: function () {
  496. return this.divideScalar( this.length() );
  497. },
  498. distanceTo: function ( v ) {
  499. return Math.sqrt( this.distanceToSquared( v ) );
  500. },
  501. distanceToSquared: function ( v ) {
  502. var dx = this.x - v.x, dy = this.y - v.y;
  503. return dx * dx + dy * dy;
  504. },
  505. setLength: function ( l ) {
  506. return this.normalize().multiplyScalar( l );
  507. },
  508. lerpSelf: function ( v, alpha ) {
  509. this.x += ( v.x - this.x ) * alpha;
  510. this.y += ( v.y - this.y ) * alpha;
  511. return this;
  512. },
  513. equals: function( v ) {
  514. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  515. },
  516. clone: function () {
  517. return new THREE.Vector2( this.x, this.y );
  518. }
  519. };
  520. /**
  521. * @author mrdoob / http://mrdoob.com/
  522. * @author *kile / http://kile.stravaganza.org/
  523. * @author philogb / http://blog.thejit.org/
  524. * @author mikael emtinger / http://gomo.se/
  525. * @author egraether / http://egraether.com/
  526. * @author WestLangley / http://github.com/WestLangley
  527. */
  528. THREE.Vector3 = function ( x, y, z ) {
  529. this.x = x || 0;
  530. this.y = y || 0;
  531. this.z = z || 0;
  532. };
  533. THREE.Vector3.prototype = {
  534. constructor: THREE.Vector3,
  535. set: function ( x, y, z ) {
  536. this.x = x;
  537. this.y = y;
  538. this.z = z;
  539. return this;
  540. },
  541. setX: function ( x ) {
  542. this.x = x;
  543. return this;
  544. },
  545. setY: function ( y ) {
  546. this.y = y;
  547. return this;
  548. },
  549. setZ: function ( z ) {
  550. this.z = z;
  551. return this;
  552. },
  553. copy: function ( v ) {
  554. this.x = v.x;
  555. this.y = v.y;
  556. this.z = v.z;
  557. return this;
  558. },
  559. add: function ( a, b ) {
  560. this.x = a.x + b.x;
  561. this.y = a.y + b.y;
  562. this.z = a.z + b.z;
  563. return this;
  564. },
  565. addSelf: function ( v ) {
  566. this.x += v.x;
  567. this.y += v.y;
  568. this.z += v.z;
  569. return this;
  570. },
  571. addScalar: function ( s ) {
  572. this.x += s;
  573. this.y += s;
  574. this.z += s;
  575. return this;
  576. },
  577. sub: function ( a, b ) {
  578. this.x = a.x - b.x;
  579. this.y = a.y - b.y;
  580. this.z = a.z - b.z;
  581. return this;
  582. },
  583. subSelf: function ( v ) {
  584. this.x -= v.x;
  585. this.y -= v.y;
  586. this.z -= v.z;
  587. return this;
  588. },
  589. multiply: function ( a, b ) {
  590. this.x = a.x * b.x;
  591. this.y = a.y * b.y;
  592. this.z = a.z * b.z;
  593. return this;
  594. },
  595. multiplySelf: function ( v ) {
  596. this.x *= v.x;
  597. this.y *= v.y;
  598. this.z *= v.z;
  599. return this;
  600. },
  601. multiplyScalar: function ( s ) {
  602. this.x *= s;
  603. this.y *= s;
  604. this.z *= s;
  605. return this;
  606. },
  607. divideSelf: function ( v ) {
  608. this.x /= v.x;
  609. this.y /= v.y;
  610. this.z /= v.z;
  611. return this;
  612. },
  613. divideScalar: function ( s ) {
  614. if ( s ) {
  615. this.x /= s;
  616. this.y /= s;
  617. this.z /= s;
  618. } else {
  619. this.x = 0;
  620. this.y = 0;
  621. this.z = 0;
  622. }
  623. return this;
  624. },
  625. minSelf: function ( v ) {
  626. if ( this.x > v.x ) {
  627. this.x = v.x;
  628. }
  629. if ( this.y > v.y ) {
  630. this.y = v.y;
  631. }
  632. if ( this.z > v.z ) {
  633. this.z = v.z;
  634. }
  635. return this;
  636. },
  637. maxSelf: function ( v ) {
  638. if ( this.x < v.x ) {
  639. this.x = v.x;
  640. }
  641. if ( this.y < v.y ) {
  642. this.y = v.y;
  643. }
  644. if ( this.z < v.z ) {
  645. this.z = v.z;
  646. }
  647. return this;
  648. },
  649. clampSelf: function ( min, max ) {
  650. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  651. if ( this.x < min.x ) {
  652. this.x = min.x;
  653. } else if ( this.x > max.x ) {
  654. this.x = max.x;
  655. }
  656. if ( this.y < min.y ) {
  657. this.y = min.y;
  658. } else if ( this.y > max.y ) {
  659. this.y = max.y;
  660. }
  661. if ( this.z < min.z ) {
  662. this.z = min.z;
  663. } else if ( this.z > max.z ) {
  664. this.z = max.z;
  665. }
  666. return this;
  667. },
  668. negate: function() {
  669. return this.multiplyScalar( - 1 );
  670. },
  671. dot: function ( v ) {
  672. return this.x * v.x + this.y * v.y + this.z * v.z;
  673. },
  674. lengthSq: function () {
  675. return this.x * this.x + this.y * this.y + this.z * this.z;
  676. },
  677. length: function () {
  678. return Math.sqrt( this.lengthSq() );
  679. },
  680. lengthManhattan: function () {
  681. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  682. },
  683. normalize: function () {
  684. return this.divideScalar( this.length() );
  685. },
  686. setLength: function ( l ) {
  687. return this.normalize().multiplyScalar( l );
  688. },
  689. lerpSelf: function ( v, alpha ) {
  690. this.x += ( v.x - this.x ) * alpha;
  691. this.y += ( v.y - this.y ) * alpha;
  692. this.z += ( v.z - this.z ) * alpha;
  693. return this;
  694. },
  695. cross: function ( a, b ) {
  696. this.x = a.y * b.z - a.z * b.y;
  697. this.y = a.z * b.x - a.x * b.z;
  698. this.z = a.x * b.y - a.y * b.x;
  699. return this;
  700. },
  701. crossSelf: function ( v ) {
  702. var x = this.x, y = this.y, z = this.z;
  703. this.x = y * v.z - z * v.y;
  704. this.y = z * v.x - x * v.z;
  705. this.z = x * v.y - y * v.x;
  706. return this;
  707. },
  708. angleTo: function ( v ) {
  709. return Math.acos( this.dot( v ) / this.length() / v.length() );
  710. },
  711. distanceTo: function ( v ) {
  712. return Math.sqrt( this.distanceToSquared( v ) );
  713. },
  714. distanceToSquared: function ( v ) {
  715. var dx = this.x - v.x;
  716. var dy = this.y - v.y;
  717. var dz = this.z - v.z;
  718. return dx * dx + dy * dy + dz * dz;
  719. },
  720. getPositionFromMatrix: function ( m ) {
  721. this.x = m.elements[12];
  722. this.y = m.elements[13];
  723. this.z = m.elements[14];
  724. return this;
  725. },
  726. setEulerFromRotationMatrix: function ( m, order ) {
  727. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  728. // clamp, to handle numerical problems
  729. function clamp( x ) {
  730. return Math.min( Math.max( x, -1 ), 1 );
  731. }
  732. var te = m.elements;
  733. var m11 = te[0], m12 = te[4], m13 = te[8];
  734. var m21 = te[1], m22 = te[5], m23 = te[9];
  735. var m31 = te[2], m32 = te[6], m33 = te[10];
  736. if ( order === undefined || order === 'XYZ' ) {
  737. this.y = Math.asin( clamp( m13 ) );
  738. if ( Math.abs( m13 ) < 0.99999 ) {
  739. this.x = Math.atan2( - m23, m33 );
  740. this.z = Math.atan2( - m12, m11 );
  741. } else {
  742. this.x = Math.atan2( m32, m22 );
  743. this.z = 0;
  744. }
  745. } else if ( order === 'YXZ' ) {
  746. this.x = Math.asin( - clamp( m23 ) );
  747. if ( Math.abs( m23 ) < 0.99999 ) {
  748. this.y = Math.atan2( m13, m33 );
  749. this.z = Math.atan2( m21, m22 );
  750. } else {
  751. this.y = Math.atan2( - m31, m11 );
  752. this.z = 0;
  753. }
  754. } else if ( order === 'ZXY' ) {
  755. this.x = Math.asin( clamp( m32 ) );
  756. if ( Math.abs( m32 ) < 0.99999 ) {
  757. this.y = Math.atan2( - m31, m33 );
  758. this.z = Math.atan2( - m12, m22 );
  759. } else {
  760. this.y = 0;
  761. this.z = Math.atan2( m21, m11 );
  762. }
  763. } else if ( order === 'ZYX' ) {
  764. this.y = Math.asin( - clamp( m31 ) );
  765. if ( Math.abs( m31 ) < 0.99999 ) {
  766. this.x = Math.atan2( m32, m33 );
  767. this.z = Math.atan2( m21, m11 );
  768. } else {
  769. this.x = 0;
  770. this.z = Math.atan2( - m12, m22 );
  771. }
  772. } else if ( order === 'YZX' ) {
  773. this.z = Math.asin( clamp( m21 ) );
  774. if ( Math.abs( m21 ) < 0.99999 ) {
  775. this.x = Math.atan2( - m23, m22 );
  776. this.y = Math.atan2( - m31, m11 );
  777. } else {
  778. this.x = 0;
  779. this.y = Math.atan2( m13, m33 );
  780. }
  781. } else if ( order === 'XZY' ) {
  782. this.z = Math.asin( - clamp( m12 ) );
  783. if ( Math.abs( m12 ) < 0.99999 ) {
  784. this.x = Math.atan2( m32, m22 );
  785. this.y = Math.atan2( m13, m11 );
  786. } else {
  787. this.x = Math.atan2( - m23, m33 );
  788. this.y = 0;
  789. }
  790. }
  791. return this;
  792. },
  793. setEulerFromQuaternion: function ( q, order ) {
  794. // q is assumed to be normalized
  795. // clamp, to handle numerical problems
  796. function clamp( x ) {
  797. return Math.min( Math.max( x, -1 ), 1 );
  798. }
  799. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  800. var sqx = q.x * q.x;
  801. var sqy = q.y * q.y;
  802. var sqz = q.z * q.z;
  803. var sqw = q.w * q.w;
  804. if ( order === undefined || order === 'XYZ' ) {
  805. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  806. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  807. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  808. } else if ( order === 'YXZ' ) {
  809. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  810. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  811. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  812. } else if ( order === 'ZXY' ) {
  813. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  814. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  815. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  816. } else if ( order === 'ZYX' ) {
  817. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  818. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  819. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  820. } else if ( order === 'YZX' ) {
  821. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  822. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  823. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  824. } else if ( order === 'XZY' ) {
  825. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  826. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  827. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  828. }
  829. return this;
  830. },
  831. getScaleFromMatrix: function ( m ) {
  832. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  833. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  834. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  835. this.x = sx;
  836. this.y = sy;
  837. this.z = sz;
  838. return this;
  839. },
  840. equals: function ( v ) {
  841. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  842. },
  843. clone: function () {
  844. return new THREE.Vector3( this.x, this.y, this.z );
  845. }
  846. };
  847. /**
  848. * @author supereggbert / http://www.paulbrunt.co.uk/
  849. * @author philogb / http://blog.thejit.org/
  850. * @author mikael emtinger / http://gomo.se/
  851. * @author egraether / http://egraether.com/
  852. * @author WestLangley / http://github.com/WestLangley
  853. */
  854. THREE.Vector4 = function ( x, y, z, w ) {
  855. this.x = x || 0;
  856. this.y = y || 0;
  857. this.z = z || 0;
  858. this.w = ( w !== undefined ) ? w : 1;
  859. };
  860. THREE.Vector4.prototype = {
  861. constructor: THREE.Vector4,
  862. set: function ( x, y, z, w ) {
  863. this.x = x;
  864. this.y = y;
  865. this.z = z;
  866. this.w = w;
  867. return this;
  868. },
  869. setX: function ( x ) {
  870. this.x = x;
  871. return this;
  872. },
  873. setY: function ( y ) {
  874. this.y = y;
  875. return this;
  876. },
  877. setZ: function ( z ) {
  878. this.z = z;
  879. return this;
  880. },
  881. setW: function ( w ) {
  882. this.w = w;
  883. return this;
  884. },
  885. copy: function ( v ) {
  886. this.x = v.x;
  887. this.y = v.y;
  888. this.z = v.z;
  889. this.w = ( v.w !== undefined ) ? v.w : 1;
  890. return this;
  891. },
  892. addScalar: function ( s ) {
  893. this.x += s;
  894. this.y += s;
  895. this.z += s;
  896. this.w += s;
  897. return this;
  898. },
  899. add: function ( a, b ) {
  900. this.x = a.x + b.x;
  901. this.y = a.y + b.y;
  902. this.z = a.z + b.z;
  903. this.w = a.w + b.w;
  904. return this;
  905. },
  906. addSelf: function ( v ) {
  907. this.x += v.x;
  908. this.y += v.y;
  909. this.z += v.z;
  910. this.w += v.w;
  911. return this;
  912. },
  913. sub: function ( a, b ) {
  914. this.x = a.x - b.x;
  915. this.y = a.y - b.y;
  916. this.z = a.z - b.z;
  917. this.w = a.w - b.w;
  918. return this;
  919. },
  920. subSelf: function ( v ) {
  921. this.x -= v.x;
  922. this.y -= v.y;
  923. this.z -= v.z;
  924. this.w -= v.w;
  925. return this;
  926. },
  927. multiplyScalar: function ( s ) {
  928. this.x *= s;
  929. this.y *= s;
  930. this.z *= s;
  931. this.w *= s;
  932. return this;
  933. },
  934. divideScalar: function ( s ) {
  935. if ( s ) {
  936. this.x /= s;
  937. this.y /= s;
  938. this.z /= s;
  939. this.w /= s;
  940. } else {
  941. this.x = 0;
  942. this.y = 0;
  943. this.z = 0;
  944. this.w = 1;
  945. }
  946. return this;
  947. },
  948. minSelf: function ( v ) {
  949. if ( this.x > v.x ) {
  950. this.x = v.x;
  951. }
  952. if ( this.y > v.y ) {
  953. this.y = v.y;
  954. }
  955. if ( this.z > v.z ) {
  956. this.z = v.z;
  957. }
  958. if ( this.w > v.w ) {
  959. this.w = v.w;
  960. }
  961. return this;
  962. },
  963. maxSelf: function ( v ) {
  964. if ( this.x < v.x ) {
  965. this.x = v.x;
  966. }
  967. if ( this.y < v.y ) {
  968. this.y = v.y;
  969. }
  970. if ( this.z < v.z ) {
  971. this.z = v.z;
  972. }
  973. if ( this.w < v.w ) {
  974. this.w = v.w;
  975. }
  976. return this;
  977. },
  978. clampSelf: function ( min, max ) {
  979. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  980. if ( this.x < min.x ) {
  981. this.x = min.x;
  982. } else if ( this.x > max.x ) {
  983. this.x = max.x;
  984. }
  985. if ( this.y < min.y ) {
  986. this.y = min.y;
  987. } else if ( this.y > max.y ) {
  988. this.y = max.y;
  989. }
  990. if ( this.z < min.z ) {
  991. this.z = min.z;
  992. } else if ( this.z > max.z ) {
  993. this.z = max.z;
  994. }
  995. if ( this.w < min.w ) {
  996. this.w = min.w;
  997. } else if ( this.w > max.w ) {
  998. this.w = max.w;
  999. }
  1000. return this;
  1001. },
  1002. negate: function() {
  1003. return this.multiplyScalar( -1 );
  1004. },
  1005. dot: function ( v ) {
  1006. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1007. },
  1008. lengthSq: function () {
  1009. return this.dot( this );
  1010. },
  1011. length: function () {
  1012. return Math.sqrt( this.lengthSq() );
  1013. },
  1014. lengthManhattan: function () {
  1015. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1016. },
  1017. normalize: function () {
  1018. return this.divideScalar( this.length() );
  1019. },
  1020. setLength: function ( l ) {
  1021. return this.normalize().multiplyScalar( l );
  1022. },
  1023. lerpSelf: function ( v, alpha ) {
  1024. this.x += ( v.x - this.x ) * alpha;
  1025. this.y += ( v.y - this.y ) * alpha;
  1026. this.z += ( v.z - this.z ) * alpha;
  1027. this.w += ( v.w - this.w ) * alpha;
  1028. return this;
  1029. },
  1030. equals: function ( v ) {
  1031. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1032. },
  1033. clone: function () {
  1034. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1035. },
  1036. setAxisAngleFromQuaternion: function ( q ) {
  1037. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1038. // q is assumed to be normalized
  1039. this.w = 2 * Math.acos( q.w );
  1040. var s = Math.sqrt( 1 - q.w * q.w );
  1041. if ( s < 0.0001 ) {
  1042. this.x = 1;
  1043. this.y = 0;
  1044. this.z = 0;
  1045. } else {
  1046. this.x = q.x / s;
  1047. this.y = q.y / s;
  1048. this.z = q.z / s;
  1049. }
  1050. return this;
  1051. },
  1052. setAxisAngleFromRotationMatrix: function ( m ) {
  1053. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1054. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1055. var angle, x, y, z, // variables for result
  1056. epsilon = 0.01, // margin to allow for rounding errors
  1057. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1058. te = m.elements,
  1059. m11 = te[0], m12 = te[4], m13 = te[8],
  1060. m21 = te[1], m22 = te[5], m23 = te[9],
  1061. m31 = te[2], m32 = te[6], m33 = te[10];
  1062. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1063. && ( Math.abs( m13 - m31 ) < epsilon )
  1064. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1065. // singularity found
  1066. // first check for identity matrix which must have +1 for all terms
  1067. // in leading diagonal and zero in other terms
  1068. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1069. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1070. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1071. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1072. // this singularity is identity matrix so angle = 0
  1073. this.set( 1, 0, 0, 0 );
  1074. return this; // zero angle, arbitrary axis
  1075. }
  1076. // otherwise this singularity is angle = 180
  1077. angle = Math.PI;
  1078. var xx = ( m11 + 1 ) / 2;
  1079. var yy = ( m22 + 1 ) / 2;
  1080. var zz = ( m33 + 1 ) / 2;
  1081. var xy = ( m12 + m21 ) / 4;
  1082. var xz = ( m13 + m31 ) / 4;
  1083. var yz = ( m23 + m32 ) / 4;
  1084. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1085. if ( xx < epsilon ) {
  1086. x = 0;
  1087. y = 0.707106781;
  1088. z = 0.707106781;
  1089. } else {
  1090. x = Math.sqrt( xx );
  1091. y = xy / x;
  1092. z = xz / x;
  1093. }
  1094. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1095. if ( yy < epsilon ) {
  1096. x = 0.707106781;
  1097. y = 0;
  1098. z = 0.707106781;
  1099. } else {
  1100. y = Math.sqrt( yy );
  1101. x = xy / y;
  1102. z = yz / y;
  1103. }
  1104. } else { // m33 is the largest diagonal term so base result on this
  1105. if ( zz < epsilon ) {
  1106. x = 0.707106781;
  1107. y = 0.707106781;
  1108. z = 0;
  1109. } else {
  1110. z = Math.sqrt( zz );
  1111. x = xz / z;
  1112. y = yz / z;
  1113. }
  1114. }
  1115. this.set( x, y, z, angle );
  1116. return this; // return 180 deg rotation
  1117. }
  1118. // as we have reached here there are no singularities so we can handle normally
  1119. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1120. + ( m13 - m31 ) * ( m13 - m31 )
  1121. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1122. if ( Math.abs( s ) < 0.001 ) s = 1;
  1123. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1124. // caught by singularity test above, but I've left it in just in case
  1125. this.x = ( m32 - m23 ) / s;
  1126. this.y = ( m13 - m31 ) / s;
  1127. this.z = ( m21 - m12 ) / s;
  1128. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1129. return this;
  1130. }
  1131. };
  1132. /**
  1133. * @author bhouston / http://exocortex.com
  1134. */
  1135. THREE.Box2 = function ( min, max ) {
  1136. this.min = min !== undefined ? min.clone() : new THREE.Vector2( Infinity, Infinity );
  1137. this.max = max !== undefined ? max.clone() : new THREE.Vector2( -Infinity, -Infinity );
  1138. };
  1139. THREE.Box2.prototype = {
  1140. constructor: THREE.Box2,
  1141. set: function ( min, max ) {
  1142. this.min.copy( min );
  1143. this.max.copy( max );
  1144. return this;
  1145. },
  1146. setFromPoints: function ( points ) {
  1147. if ( points.length > 0 ) {
  1148. var point = points[ 0 ];
  1149. this.min.copy( point );
  1150. this.max.copy( point );
  1151. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1152. point = points[ i ];
  1153. if ( point.x < this.min.x ) {
  1154. this.min.x = point.x;
  1155. } else if ( point.x > this.max.x ) {
  1156. this.max.x = point.x;
  1157. }
  1158. if ( point.y < this.min.y ) {
  1159. this.min.y = point.y;
  1160. } else if ( point.y > this.max.y ) {
  1161. this.max.y = point.y;
  1162. }
  1163. }
  1164. } else {
  1165. this.makeEmpty();
  1166. }
  1167. return this;
  1168. },
  1169. setFromCenterAndSize: function ( center, size ) {
  1170. var halfSize = THREE.Box2.__v1.copy( size ).multiplyScalar( 0.5 );
  1171. this.min.copy( center ).subSelf( halfSize );
  1172. this.max.copy( center ).addSelf( halfSize );
  1173. return this;
  1174. },
  1175. copy: function ( box ) {
  1176. this.min.copy( box.min );
  1177. this.max.copy( box.max );
  1178. return this;
  1179. },
  1180. makeEmpty: function () {
  1181. this.min.x = this.min.y = Infinity;
  1182. this.max.x = this.max.y = -Infinity;
  1183. return this;
  1184. },
  1185. empty: function () {
  1186. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1187. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1188. },
  1189. center: function ( optionalTarget ) {
  1190. var result = optionalTarget || new THREE.Vector2();
  1191. return result.add( this.min, this.max ).multiplyScalar( 0.5 );
  1192. },
  1193. size: function ( optionalTarget ) {
  1194. var result = optionalTarget || new THREE.Vector2();
  1195. return result.sub( this.max, this.min );
  1196. },
  1197. expandByPoint: function ( point ) {
  1198. this.min.minSelf( point );
  1199. this.max.maxSelf( point );
  1200. return this;
  1201. },
  1202. expandByVector: function ( vector ) {
  1203. this.min.subSelf( vector );
  1204. this.max.addSelf( vector );
  1205. return this;
  1206. },
  1207. expandByScalar: function ( scalar ) {
  1208. this.min.addScalar( -scalar );
  1209. this.max.addScalar( scalar );
  1210. return this;
  1211. },
  1212. containsPoint: function ( point ) {
  1213. if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
  1214. ( this.min.y <= point.y ) && ( point.y <= this.max.y ) ) {
  1215. return true;
  1216. }
  1217. return false;
  1218. },
  1219. containsBox: function ( box ) {
  1220. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1221. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1222. return true;
  1223. }
  1224. return false;
  1225. },
  1226. getParameter: function ( point ) {
  1227. // This can potentially have a divide by zero if the box
  1228. // has a size dimension of 0.
  1229. return new THREE.Vector2(
  1230. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1231. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1232. );
  1233. },
  1234. isIntersectionBox: function ( box ) {
  1235. // using 6 splitting planes to rule out intersections.
  1236. if ( ( box.max.x < this.min.x ) ||
  1237. ( box.min.x > this.max.x ) ||
  1238. ( box.max.y < this.min.y ) ||
  1239. ( box.min.y > this.max.y ) ) {
  1240. return false;
  1241. }
  1242. return true;
  1243. },
  1244. clampPoint: function ( point, optionalTarget ) {
  1245. var result = optionalTarget || new THREE.Vector2();
  1246. return result.copy( point ).clampSelf( this.min, this.max );
  1247. },
  1248. distanceToPoint: function ( point ) {
  1249. var clampedPoint = THREE.Box2.__v1.copy( point ).clampSelf( this.min, this.max );
  1250. return clampedPoint.subSelf( point ).length();
  1251. },
  1252. intersect: function ( box ) {
  1253. this.min.maxSelf( box.min );
  1254. this.max.minSelf( box.max );
  1255. return this;
  1256. },
  1257. union: function ( box ) {
  1258. this.min.minSelf( box.min );
  1259. this.max.maxSelf( box.max );
  1260. return this;
  1261. },
  1262. translate: function ( offset ) {
  1263. this.min.addSelf( offset );
  1264. this.max.addSelf( offset );
  1265. return this;
  1266. },
  1267. equals: function ( box ) {
  1268. return box.min.equals( this.min ) && box.max.equals( this.max );
  1269. },
  1270. clone: function () {
  1271. return new THREE.Box2().copy( this );
  1272. }
  1273. };
  1274. THREE.Box2.__v1 = new THREE.Vector2();
  1275. /**
  1276. * @author bhouston / http://exocortex.com
  1277. */
  1278. THREE.Box3 = function ( min, max ) {
  1279. this.min = min !== undefined ? min.clone() : new THREE.Vector3( Infinity, Infinity, Infinity );
  1280. this.max = max !== undefined ? max.clone() : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1281. };
  1282. THREE.Box3.prototype = {
  1283. constructor: THREE.Box3,
  1284. set: function ( min, max ) {
  1285. this.min.copy( min );
  1286. this.max.copy( max );
  1287. return this;
  1288. },
  1289. setFromPoints: function ( points ) {
  1290. if ( points.length > 0 ) {
  1291. var p = points[ 0 ];
  1292. this.min.copy( p );
  1293. this.max.copy( p );
  1294. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1295. p = points[ i ];
  1296. if ( p.x < this.min.x ) {
  1297. this.min.x = p.x;
  1298. } else if ( p.x > this.max.x ) {
  1299. this.max.x = p.x;
  1300. }
  1301. if ( p.y < this.min.y ) {
  1302. this.min.y = p.y;
  1303. } else if ( p.y > this.max.y ) {
  1304. this.max.y = p.y;
  1305. }
  1306. if ( p.z < this.min.z ) {
  1307. this.min.z = p.z;
  1308. } else if ( p.z > this.max.z ) {
  1309. this.max.z = p.z;
  1310. }
  1311. }
  1312. } else {
  1313. this.makeEmpty();
  1314. }
  1315. return this;
  1316. },
  1317. setFromCenterAndSize: function ( center, size ) {
  1318. var halfSize = THREE.Box3.__v1.copy( size ).multiplyScalar( 0.5 );
  1319. this.min.copy( center ).subSelf( halfSize );
  1320. this.max.copy( center ).addSelf( halfSize );
  1321. return this;
  1322. },
  1323. copy: function ( box ) {
  1324. this.min.copy( box.min );
  1325. this.max.copy( box.max );
  1326. return this;
  1327. },
  1328. makeEmpty: function () {
  1329. this.min.x = this.min.y = this.min.z = Infinity;
  1330. this.max.x = this.max.y = this.max.z = -Infinity;
  1331. return this;
  1332. },
  1333. empty: function () {
  1334. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1335. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1336. },
  1337. center: function ( optionalTarget ) {
  1338. var result = optionalTarget || new THREE.Vector3();
  1339. return result.add( this.min, this.max ).multiplyScalar( 0.5 );
  1340. },
  1341. size: function ( optionalTarget ) {
  1342. var result = optionalTarget || new THREE.Vector3();
  1343. return result.sub( this.max, this.min );
  1344. },
  1345. expandByPoint: function ( point ) {
  1346. this.min.minSelf( point );
  1347. this.max.maxSelf( point );
  1348. return this;
  1349. },
  1350. expandByVector: function ( vector ) {
  1351. this.min.subSelf( vector );
  1352. this.max.addSelf( vector );
  1353. return this;
  1354. },
  1355. expandByScalar: function ( scalar ) {
  1356. this.min.addScalar( -scalar );
  1357. this.max.addScalar( scalar );
  1358. return this;
  1359. },
  1360. containsPoint: function ( point ) {
  1361. if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
  1362. ( this.min.y <= point.y ) && ( point.y <= this.max.y ) &&
  1363. ( this.min.z <= point.z ) && ( point.z <= this.max.z ) ) {
  1364. return true;
  1365. }
  1366. return false;
  1367. },
  1368. containsBox: function ( box ) {
  1369. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1370. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1371. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1372. return true;
  1373. }
  1374. return false;
  1375. },
  1376. getParameter: function ( point ) {
  1377. // This can potentially have a divide by zero if the box
  1378. // has a size dimension of 0.
  1379. return new THREE.Vector3(
  1380. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1381. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1382. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1383. );
  1384. },
  1385. isIntersectionBox: function ( box ) {
  1386. // using 6 splitting planes to rule out intersections.
  1387. if ( ( box.max.x < this.min.x ) || ( box.min.x > this.max.x ) ||
  1388. ( box.max.y < this.min.y ) || ( box.min.y > this.max.y ) ||
  1389. ( box.max.z < this.min.z ) || ( box.min.z > this.max.z ) ) {
  1390. return false;
  1391. }
  1392. return true;
  1393. },
  1394. clampPoint: function ( point, optionalTarget ) {
  1395. var result = optionalTarget || new THREE.Vector3();
  1396. return new THREE.Vector3().copy( point ).clampSelf( this.min, this.max );
  1397. },
  1398. distanceToPoint: function ( point ) {
  1399. var clampedPoint = THREE.Box3.__v1.copy( point ).clampSelf( this.min, this.max );
  1400. return clampedPoint.subSelf( point ).length();
  1401. },
  1402. intersect: function ( box ) {
  1403. this.min.maxSelf( box.min );
  1404. this.max.minSelf( box.max );
  1405. return this;
  1406. },
  1407. union: function ( box ) {
  1408. this.min.minSelf( box.min );
  1409. this.max.maxSelf( box.max );
  1410. return this;
  1411. },
  1412. transform: function ( matrix ) {
  1413. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  1414. var newPoints = [
  1415. matrix.multiplyVector3( THREE.Box3.__v0.set( this.min.x, this.min.y, this.min.z ) ), // 000
  1416. matrix.multiplyVector3( THREE.Box3.__v1.set( this.min.x, this.min.y, this.max.z ) ), // 001
  1417. matrix.multiplyVector3( THREE.Box3.__v2.set( this.min.x, this.max.y, this.min.z ) ), // 010
  1418. matrix.multiplyVector3( THREE.Box3.__v3.set( this.min.x, this.max.y, this.max.z ) ), // 011
  1419. matrix.multiplyVector3( THREE.Box3.__v4.set( this.max.x, this.min.y, this.min.z ) ), // 100
  1420. matrix.multiplyVector3( THREE.Box3.__v5.set( this.max.x, this.min.y, this.max.z ) ), // 101
  1421. matrix.multiplyVector3( THREE.Box3.__v6.set( this.max.x, this.max.y, this.min.z ) ), // 110
  1422. matrix.multiplyVector3( THREE.Box3.__v7.set( this.max.x, this.max.y, this.max.z ) ) // 111
  1423. ];
  1424. this.makeEmpty();
  1425. this.setFromPoints( newPoints );
  1426. return this;
  1427. },
  1428. translate: function ( offset ) {
  1429. this.min.addSelf( offset );
  1430. this.max.addSelf( offset );
  1431. return this;
  1432. },
  1433. equals: function ( box ) {
  1434. return box.min.equals( this.min ) && box.max.equals( this.max );
  1435. },
  1436. clone: function () {
  1437. return new THREE.Box3().copy( this );
  1438. }
  1439. };
  1440. THREE.Box3.__v0 = new THREE.Vector3();
  1441. THREE.Box3.__v1 = new THREE.Vector3();
  1442. THREE.Box3.__v2 = new THREE.Vector3();
  1443. THREE.Box3.__v3 = new THREE.Vector3();
  1444. THREE.Box3.__v4 = new THREE.Vector3();
  1445. THREE.Box3.__v5 = new THREE.Vector3();
  1446. THREE.Box3.__v6 = new THREE.Vector3();
  1447. THREE.Box3.__v7 = new THREE.Vector3();
  1448. /**
  1449. * @author alteredq / http://alteredqualia.com/
  1450. * @author WestLangley / http://github.com/WestLangley
  1451. */
  1452. THREE.Matrix3 = function () {
  1453. this.elements = new Float32Array(9);
  1454. };
  1455. THREE.Matrix3.prototype = {
  1456. constructor: THREE.Matrix3,
  1457. multiplyVector3: function ( v ) {
  1458. var te = this.elements;
  1459. var vx = v.x, vy = v.y, vz = v.z;
  1460. v.x = te[0] * vx + te[3] * vy + te[6] * vz;
  1461. v.y = te[1] * vx + te[4] * vy + te[7] * vz;
  1462. v.z = te[2] * vx + te[5] * vy + te[8] * vz;
  1463. return v;
  1464. },
  1465. multiplyVector3Array: function ( a ) {
  1466. var tmp = THREE.Matrix3.__v1;
  1467. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1468. tmp.x = a[ i ];
  1469. tmp.y = a[ i + 1 ];
  1470. tmp.z = a[ i + 2 ];
  1471. this.multiplyVector3( tmp );
  1472. a[ i ] = tmp.x;
  1473. a[ i + 1 ] = tmp.y;
  1474. a[ i + 2 ] = tmp.z;
  1475. }
  1476. return a;
  1477. },
  1478. getInverse: function ( matrix ) {
  1479. // input: THREE.Matrix4
  1480. // ( based on http://code.google.com/p/webgl-mjs/ )
  1481. var me = matrix.elements;
  1482. var a11 = me[10] * me[5] - me[6] * me[9];
  1483. var a21 = - me[10] * me[1] + me[2] * me[9];
  1484. var a31 = me[6] * me[1] - me[2] * me[5];
  1485. var a12 = - me[10] * me[4] + me[6] * me[8];
  1486. var a22 = me[10] * me[0] - me[2] * me[8];
  1487. var a32 = - me[6] * me[0] + me[2] * me[4];
  1488. var a13 = me[9] * me[4] - me[5] * me[8];
  1489. var a23 = - me[9] * me[0] + me[1] * me[8];
  1490. var a33 = me[5] * me[0] - me[1] * me[4];
  1491. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  1492. // no inverse
  1493. if ( det === 0 ) {
  1494. console.warn( "Matrix3.getInverse(): determinant == 0" );
  1495. }
  1496. var idet = 1.0 / det;
  1497. var m = this.elements;
  1498. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  1499. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  1500. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  1501. return this;
  1502. },
  1503. transpose: function () {
  1504. var tmp, m = this.elements;
  1505. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  1506. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  1507. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  1508. return this;
  1509. },
  1510. transposeIntoArray: function ( r ) {
  1511. var m = this.elements;
  1512. r[ 0 ] = m[ 0 ];
  1513. r[ 1 ] = m[ 3 ];
  1514. r[ 2 ] = m[ 6 ];
  1515. r[ 3 ] = m[ 1 ];
  1516. r[ 4 ] = m[ 4 ];
  1517. r[ 5 ] = m[ 7 ];
  1518. r[ 6 ] = m[ 2 ];
  1519. r[ 7 ] = m[ 5 ];
  1520. r[ 8 ] = m[ 8 ];
  1521. return this;
  1522. }
  1523. };
  1524. THREE.Matrix3.__v1 = new THREE.Vector3();/**
  1525. * @author mrdoob / http://mrdoob.com/
  1526. * @author supereggbert / http://www.paulbrunt.co.uk/
  1527. * @author philogb / http://blog.thejit.org/
  1528. * @author jordi_ros / http://plattsoft.com
  1529. * @author D1plo1d / http://github.com/D1plo1d
  1530. * @author alteredq / http://alteredqualia.com/
  1531. * @author mikael emtinger / http://gomo.se/
  1532. * @author timknip / http://www.floorplanner.com/
  1533. */
  1534. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1535. this.elements = new Float32Array( 16 );
  1536. this.set(
  1537. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  1538. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  1539. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  1540. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  1541. );
  1542. };
  1543. THREE.Matrix4.prototype = {
  1544. constructor: THREE.Matrix4,
  1545. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1546. var te = this.elements;
  1547. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  1548. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1549. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1550. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1551. return this;
  1552. },
  1553. identity: function () {
  1554. this.set(
  1555. 1, 0, 0, 0,
  1556. 0, 1, 0, 0,
  1557. 0, 0, 1, 0,
  1558. 0, 0, 0, 1
  1559. );
  1560. return this;
  1561. },
  1562. copy: function ( m ) {
  1563. var me = m.elements;
  1564. this.set(
  1565. me[0], me[4], me[8], me[12],
  1566. me[1], me[5], me[9], me[13],
  1567. me[2], me[6], me[10], me[14],
  1568. me[3], me[7], me[11], me[15]
  1569. );
  1570. return this;
  1571. },
  1572. lookAt: function ( eye, target, up ) {
  1573. var te = this.elements;
  1574. var x = THREE.Matrix4.__v1;
  1575. var y = THREE.Matrix4.__v2;
  1576. var z = THREE.Matrix4.__v3;
  1577. z.sub( eye, target ).normalize();
  1578. if ( z.length() === 0 ) {
  1579. z.z = 1;
  1580. }
  1581. x.cross( up, z ).normalize();
  1582. if ( x.length() === 0 ) {
  1583. z.x += 0.0001;
  1584. x.cross( up, z ).normalize();
  1585. }
  1586. y.cross( z, x );
  1587. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1588. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1589. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1590. return this;
  1591. },
  1592. multiply: function ( a, b ) {
  1593. var ae = a.elements;
  1594. var be = b.elements;
  1595. var te = this.elements;
  1596. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1597. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1598. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1599. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1600. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1601. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1602. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1603. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1604. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1605. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1606. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1607. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1608. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1609. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1610. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1611. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1612. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1613. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1614. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1615. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1616. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1617. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1618. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1619. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1620. return this;
  1621. },
  1622. multiplySelf: function ( m ) {
  1623. return this.multiply( this, m );
  1624. },
  1625. multiplyToArray: function ( a, b, r ) {
  1626. var te = this.elements;
  1627. this.multiply( a, b );
  1628. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1629. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1630. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1631. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1632. return this;
  1633. },
  1634. multiplyScalar: function ( s ) {
  1635. var te = this.elements;
  1636. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1637. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1638. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1639. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1640. return this;
  1641. },
  1642. multiplyVector3: function ( v ) {
  1643. var te = this.elements;
  1644. var vx = v.x, vy = v.y, vz = v.z;
  1645. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1646. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1647. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1648. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1649. return v;
  1650. },
  1651. multiplyVector4: function ( v ) {
  1652. var te = this.elements;
  1653. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1654. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1655. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1656. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1657. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1658. return v;
  1659. },
  1660. multiplyVector3Array: function ( a ) {
  1661. var tmp = THREE.Matrix4.__v1;
  1662. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1663. tmp.x = a[ i ];
  1664. tmp.y = a[ i + 1 ];
  1665. tmp.z = a[ i + 2 ];
  1666. this.multiplyVector3( tmp );
  1667. a[ i ] = tmp.x;
  1668. a[ i + 1 ] = tmp.y;
  1669. a[ i + 2 ] = tmp.z;
  1670. }
  1671. return a;
  1672. },
  1673. rotateAxis: function ( v ) {
  1674. var te = this.elements;
  1675. var vx = v.x, vy = v.y, vz = v.z;
  1676. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1677. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1678. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1679. v.normalize();
  1680. return v;
  1681. },
  1682. crossVector: function ( a ) {
  1683. var te = this.elements;
  1684. var v = new THREE.Vector4();
  1685. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1686. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1687. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1688. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1689. return v;
  1690. },
  1691. determinant: function () {
  1692. var te = this.elements;
  1693. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1694. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1695. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1696. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1697. //TODO: make this more efficient
  1698. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1699. return (
  1700. n14 * n23 * n32 * n41-
  1701. n13 * n24 * n32 * n41-
  1702. n14 * n22 * n33 * n41+
  1703. n12 * n24 * n33 * n41+
  1704. n13 * n22 * n34 * n41-
  1705. n12 * n23 * n34 * n41-
  1706. n14 * n23 * n31 * n42+
  1707. n13 * n24 * n31 * n42+
  1708. n14 * n21 * n33 * n42-
  1709. n11 * n24 * n33 * n42-
  1710. n13 * n21 * n34 * n42+
  1711. n11 * n23 * n34 * n42+
  1712. n14 * n22 * n31 * n43-
  1713. n12 * n24 * n31 * n43-
  1714. n14 * n21 * n32 * n43+
  1715. n11 * n24 * n32 * n43+
  1716. n12 * n21 * n34 * n43-
  1717. n11 * n22 * n34 * n43-
  1718. n13 * n22 * n31 * n44+
  1719. n12 * n23 * n31 * n44+
  1720. n13 * n21 * n32 * n44-
  1721. n11 * n23 * n32 * n44-
  1722. n12 * n21 * n33 * n44+
  1723. n11 * n22 * n33 * n44
  1724. );
  1725. },
  1726. transpose: function () {
  1727. var te = this.elements;
  1728. var tmp;
  1729. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1730. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1731. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1732. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1733. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1734. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1735. return this;
  1736. },
  1737. flattenToArray: function ( flat ) {
  1738. var te = this.elements;
  1739. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1740. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1741. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1742. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1743. return flat;
  1744. },
  1745. flattenToArrayOffset: function( flat, offset ) {
  1746. var te = this.elements;
  1747. flat[ offset ] = te[0];
  1748. flat[ offset + 1 ] = te[1];
  1749. flat[ offset + 2 ] = te[2];
  1750. flat[ offset + 3 ] = te[3];
  1751. flat[ offset + 4 ] = te[4];
  1752. flat[ offset + 5 ] = te[5];
  1753. flat[ offset + 6 ] = te[6];
  1754. flat[ offset + 7 ] = te[7];
  1755. flat[ offset + 8 ] = te[8];
  1756. flat[ offset + 9 ] = te[9];
  1757. flat[ offset + 10 ] = te[10];
  1758. flat[ offset + 11 ] = te[11];
  1759. flat[ offset + 12 ] = te[12];
  1760. flat[ offset + 13 ] = te[13];
  1761. flat[ offset + 14 ] = te[14];
  1762. flat[ offset + 15 ] = te[15];
  1763. return flat;
  1764. },
  1765. getPosition: function () {
  1766. var te = this.elements;
  1767. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1768. },
  1769. setPosition: function ( v ) {
  1770. var te = this.elements;
  1771. te[12] = v.x;
  1772. te[13] = v.y;
  1773. te[14] = v.z;
  1774. return this;
  1775. },
  1776. getColumnX: function () {
  1777. var te = this.elements;
  1778. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1779. },
  1780. getColumnY: function () {
  1781. var te = this.elements;
  1782. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1783. },
  1784. getColumnZ: function() {
  1785. var te = this.elements;
  1786. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1787. },
  1788. getInverse: function ( m ) {
  1789. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1790. var te = this.elements;
  1791. var me = m.elements;
  1792. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1793. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1794. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1795. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1796. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1797. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1798. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1799. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1800. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1801. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1802. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1803. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1804. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1805. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1806. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1807. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1808. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1809. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1810. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1811. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1812. this.multiplyScalar( 1 / m.determinant() );
  1813. return this;
  1814. },
  1815. setRotationFromEuler: function ( v, order ) {
  1816. var te = this.elements;
  1817. var x = v.x, y = v.y, z = v.z;
  1818. var a = Math.cos( x ), b = Math.sin( x );
  1819. var c = Math.cos( y ), d = Math.sin( y );
  1820. var e = Math.cos( z ), f = Math.sin( z );
  1821. if ( order === undefined || order === 'XYZ' ) {
  1822. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1823. te[0] = c * e;
  1824. te[4] = - c * f;
  1825. te[8] = d;
  1826. te[1] = af + be * d;
  1827. te[5] = ae - bf * d;
  1828. te[9] = - b * c;
  1829. te[2] = bf - ae * d;
  1830. te[6] = be + af * d;
  1831. te[10] = a * c;
  1832. } else if ( order === 'YXZ' ) {
  1833. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1834. te[0] = ce + df * b;
  1835. te[4] = de * b - cf;
  1836. te[8] = a * d;
  1837. te[1] = a * f;
  1838. te[5] = a * e;
  1839. te[9] = - b;
  1840. te[2] = cf * b - de;
  1841. te[6] = df + ce * b;
  1842. te[10] = a * c;
  1843. } else if ( order === 'ZXY' ) {
  1844. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1845. te[0] = ce - df * b;
  1846. te[4] = - a * f;
  1847. te[8] = de + cf * b;
  1848. te[1] = cf + de * b;
  1849. te[5] = a * e;
  1850. te[9] = df - ce * b;
  1851. te[2] = - a * d;
  1852. te[6] = b;
  1853. te[10] = a * c;
  1854. } else if ( order === 'ZYX' ) {
  1855. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1856. te[0] = c * e;
  1857. te[4] = be * d - af;
  1858. te[8] = ae * d + bf;
  1859. te[1] = c * f;
  1860. te[5] = bf * d + ae;
  1861. te[9] = af * d - be;
  1862. te[2] = - d;
  1863. te[6] = b * c;
  1864. te[10] = a * c;
  1865. } else if ( order === 'YZX' ) {
  1866. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1867. te[0] = c * e;
  1868. te[4] = bd - ac * f;
  1869. te[8] = bc * f + ad;
  1870. te[1] = f;
  1871. te[5] = a * e;
  1872. te[9] = - b * e;
  1873. te[2] = - d * e;
  1874. te[6] = ad * f + bc;
  1875. te[10] = ac - bd * f;
  1876. } else if ( order === 'XZY' ) {
  1877. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1878. te[0] = c * e;
  1879. te[4] = - f;
  1880. te[8] = d * e;
  1881. te[1] = ac * f + bd;
  1882. te[5] = a * e;
  1883. te[9] = ad * f - bc;
  1884. te[2] = bc * f - ad;
  1885. te[6] = b * e;
  1886. te[10] = bd * f + ac;
  1887. }
  1888. return this;
  1889. },
  1890. setRotationFromQuaternion: function ( q ) {
  1891. var te = this.elements;
  1892. var x = q.x, y = q.y, z = q.z, w = q.w;
  1893. var x2 = x + x, y2 = y + y, z2 = z + z;
  1894. var xx = x * x2, xy = x * y2, xz = x * z2;
  1895. var yy = y * y2, yz = y * z2, zz = z * z2;
  1896. var wx = w * x2, wy = w * y2, wz = w * z2;
  1897. te[0] = 1 - ( yy + zz );
  1898. te[4] = xy - wz;
  1899. te[8] = xz + wy;
  1900. te[1] = xy + wz;
  1901. te[5] = 1 - ( xx + zz );
  1902. te[9] = yz - wx;
  1903. te[2] = xz - wy;
  1904. te[6] = yz + wx;
  1905. te[10] = 1 - ( xx + yy );
  1906. return this;
  1907. },
  1908. compose: function ( translation, rotation, scale ) {
  1909. var te = this.elements;
  1910. var mRotation = THREE.Matrix4.__m1;
  1911. var mScale = THREE.Matrix4.__m2;
  1912. mRotation.identity();
  1913. mRotation.setRotationFromQuaternion( rotation );
  1914. mScale.makeScale( scale );
  1915. this.multiply( mRotation, mScale );
  1916. te[12] = translation.x;
  1917. te[13] = translation.y;
  1918. te[14] = translation.z;
  1919. return this;
  1920. },
  1921. decompose: function ( translation, rotation, scale ) {
  1922. var te = this.elements;
  1923. // grab the axis vectors
  1924. var x = THREE.Matrix4.__v1;
  1925. var y = THREE.Matrix4.__v2;
  1926. var z = THREE.Matrix4.__v3;
  1927. x.set( te[0], te[1], te[2] );
  1928. y.set( te[4], te[5], te[6] );
  1929. z.set( te[8], te[9], te[10] );
  1930. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1931. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1932. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1933. scale.x = x.length();
  1934. scale.y = y.length();
  1935. scale.z = z.length();
  1936. translation.x = te[12];
  1937. translation.y = te[13];
  1938. translation.z = te[14];
  1939. // scale the rotation part
  1940. var matrix = THREE.Matrix4.__m1;
  1941. matrix.copy( this );
  1942. matrix.elements[0] /= scale.x;
  1943. matrix.elements[1] /= scale.x;
  1944. matrix.elements[2] /= scale.x;
  1945. matrix.elements[4] /= scale.y;
  1946. matrix.elements[5] /= scale.y;
  1947. matrix.elements[6] /= scale.y;
  1948. matrix.elements[8] /= scale.z;
  1949. matrix.elements[9] /= scale.z;
  1950. matrix.elements[10] /= scale.z;
  1951. rotation.setFromRotationMatrix( matrix );
  1952. return [ translation, rotation, scale ];
  1953. },
  1954. extractPosition: function ( m ) {
  1955. var te = this.elements;
  1956. var me = m.elements;
  1957. te[12] = me[12];
  1958. te[13] = me[13];
  1959. te[14] = me[14];
  1960. return this;
  1961. },
  1962. extractRotation: function ( m ) {
  1963. var te = this.elements;
  1964. var me = m.elements;
  1965. var vector = THREE.Matrix4.__v1;
  1966. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1967. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1968. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1969. te[0] = me[0] * scaleX;
  1970. te[1] = me[1] * scaleX;
  1971. te[2] = me[2] * scaleX;
  1972. te[4] = me[4] * scaleY;
  1973. te[5] = me[5] * scaleY;
  1974. te[6] = me[6] * scaleY;
  1975. te[8] = me[8] * scaleZ;
  1976. te[9] = me[9] * scaleZ;
  1977. te[10] = me[10] * scaleZ;
  1978. return this;
  1979. },
  1980. //
  1981. translate: function ( v ) {
  1982. var te = this.elements;
  1983. var x = v.x, y = v.y, z = v.z;
  1984. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1985. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1986. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1987. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1988. return this;
  1989. },
  1990. rotateX: function ( angle ) {
  1991. var te = this.elements;
  1992. var m12 = te[4];
  1993. var m22 = te[5];
  1994. var m32 = te[6];
  1995. var m42 = te[7];
  1996. var m13 = te[8];
  1997. var m23 = te[9];
  1998. var m33 = te[10];
  1999. var m43 = te[11];
  2000. var c = Math.cos( angle );
  2001. var s = Math.sin( angle );
  2002. te[4] = c * m12 + s * m13;
  2003. te[5] = c * m22 + s * m23;
  2004. te[6] = c * m32 + s * m33;
  2005. te[7] = c * m42 + s * m43;
  2006. te[8] = c * m13 - s * m12;
  2007. te[9] = c * m23 - s * m22;
  2008. te[10] = c * m33 - s * m32;
  2009. te[11] = c * m43 - s * m42;
  2010. return this;
  2011. },
  2012. rotateY: function ( angle ) {
  2013. var te = this.elements;
  2014. var m11 = te[0];
  2015. var m21 = te[1];
  2016. var m31 = te[2];
  2017. var m41 = te[3];
  2018. var m13 = te[8];
  2019. var m23 = te[9];
  2020. var m33 = te[10];
  2021. var m43 = te[11];
  2022. var c = Math.cos( angle );
  2023. var s = Math.sin( angle );
  2024. te[0] = c * m11 - s * m13;
  2025. te[1] = c * m21 - s * m23;
  2026. te[2] = c * m31 - s * m33;
  2027. te[3] = c * m41 - s * m43;
  2028. te[8] = c * m13 + s * m11;
  2029. te[9] = c * m23 + s * m21;
  2030. te[10] = c * m33 + s * m31;
  2031. te[11] = c * m43 + s * m41;
  2032. return this;
  2033. },
  2034. rotateZ: function ( angle ) {
  2035. var te = this.elements;
  2036. var m11 = te[0];
  2037. var m21 = te[1];
  2038. var m31 = te[2];
  2039. var m41 = te[3];
  2040. var m12 = te[4];
  2041. var m22 = te[5];
  2042. var m32 = te[6];
  2043. var m42 = te[7];
  2044. var c = Math.cos( angle );
  2045. var s = Math.sin( angle );
  2046. te[0] = c * m11 + s * m12;
  2047. te[1] = c * m21 + s * m22;
  2048. te[2] = c * m31 + s * m32;
  2049. te[3] = c * m41 + s * m42;
  2050. te[4] = c * m12 - s * m11;
  2051. te[5] = c * m22 - s * m21;
  2052. te[6] = c * m32 - s * m31;
  2053. te[7] = c * m42 - s * m41;
  2054. return this;
  2055. },
  2056. rotateByAxis: function ( axis, angle ) {
  2057. var te = this.elements;
  2058. // optimize by checking axis
  2059. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  2060. return this.rotateX( angle );
  2061. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  2062. return this.rotateY( angle );
  2063. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  2064. return this.rotateZ( angle );
  2065. }
  2066. var x = axis.x, y = axis.y, z = axis.z;
  2067. var n = Math.sqrt(x * x + y * y + z * z);
  2068. x /= n;
  2069. y /= n;
  2070. z /= n;
  2071. var xx = x * x, yy = y * y, zz = z * z;
  2072. var c = Math.cos( angle );
  2073. var s = Math.sin( angle );
  2074. var oneMinusCosine = 1 - c;
  2075. var xy = x * y * oneMinusCosine;
  2076. var xz = x * z * oneMinusCosine;
  2077. var yz = y * z * oneMinusCosine;
  2078. var xs = x * s;
  2079. var ys = y * s;
  2080. var zs = z * s;
  2081. var r11 = xx + (1 - xx) * c;
  2082. var r21 = xy + zs;
  2083. var r31 = xz - ys;
  2084. var r12 = xy - zs;
  2085. var r22 = yy + (1 - yy) * c;
  2086. var r32 = yz + xs;
  2087. var r13 = xz + ys;
  2088. var r23 = yz - xs;
  2089. var r33 = zz + (1 - zz) * c;
  2090. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  2091. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  2092. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  2093. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  2094. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  2095. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  2096. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  2097. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  2098. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  2099. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  2100. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  2101. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  2102. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  2103. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  2104. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  2105. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  2106. return this;
  2107. },
  2108. scale: function ( v ) {
  2109. var te = this.elements;
  2110. var x = v.x, y = v.y, z = v.z;
  2111. te[0] *= x; te[4] *= y; te[8] *= z;
  2112. te[1] *= x; te[5] *= y; te[9] *= z;
  2113. te[2] *= x; te[6] *= y; te[10] *= z;
  2114. te[3] *= x; te[7] *= y; te[11] *= z;
  2115. return this;
  2116. },
  2117. getMaxScaleOnAxis: function () {
  2118. var te = this.elements;
  2119. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2120. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2121. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2122. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2123. },
  2124. //
  2125. makeTranslation: function ( offset ) {
  2126. this.set(
  2127. 1, 0, 0, offset.x,
  2128. 0, 1, 0, offset.y,
  2129. 0, 0, 1, offset.z,
  2130. 0, 0, 0, 1
  2131. );
  2132. return this;
  2133. },
  2134. makeRotationX: function ( theta ) {
  2135. var c = Math.cos( theta ), s = Math.sin( theta );
  2136. this.set(
  2137. 1, 0, 0, 0,
  2138. 0, c, -s, 0,
  2139. 0, s, c, 0,
  2140. 0, 0, 0, 1
  2141. );
  2142. return this;
  2143. },
  2144. makeRotationY: function ( theta ) {
  2145. var c = Math.cos( theta ), s = Math.sin( theta );
  2146. this.set(
  2147. c, 0, s, 0,
  2148. 0, 1, 0, 0,
  2149. -s, 0, c, 0,
  2150. 0, 0, 0, 1
  2151. );
  2152. return this;
  2153. },
  2154. makeRotationZ: function ( theta ) {
  2155. var c = Math.cos( theta ), s = Math.sin( theta );
  2156. this.set(
  2157. c, -s, 0, 0,
  2158. s, c, 0, 0,
  2159. 0, 0, 1, 0,
  2160. 0, 0, 0, 1
  2161. );
  2162. return this;
  2163. },
  2164. makeRotationAxis: function ( axis, angle ) {
  2165. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2166. var c = Math.cos( angle );
  2167. var s = Math.sin( angle );
  2168. var t = 1 - c;
  2169. var x = axis.x, y = axis.y, z = axis.z;
  2170. var tx = t * x, ty = t * y;
  2171. this.set(
  2172. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2173. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2174. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2175. 0, 0, 0, 1
  2176. );
  2177. return this;
  2178. },
  2179. makeScale: function ( factor ) {
  2180. this.set(
  2181. factor.x, 0, 0, 0,
  2182. 0, factor.y, 0, 0,
  2183. 0, 0, factor.z, 0,
  2184. 0, 0, 0, 1
  2185. );
  2186. return this;
  2187. },
  2188. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2189. var te = this.elements;
  2190. var x = 2 * near / ( right - left );
  2191. var y = 2 * near / ( top - bottom );
  2192. var a = ( right + left ) / ( right - left );
  2193. var b = ( top + bottom ) / ( top - bottom );
  2194. var c = - ( far + near ) / ( far - near );
  2195. var d = - 2 * far * near / ( far - near );
  2196. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2197. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2198. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2199. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2200. return this;
  2201. },
  2202. makePerspective: function ( fov, aspect, near, far ) {
  2203. var ymax = near * Math.tan( fov * Math.PI / 360 );
  2204. var ymin = - ymax;
  2205. var xmin = ymin * aspect;
  2206. var xmax = ymax * aspect;
  2207. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2208. },
  2209. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2210. var te = this.elements;
  2211. var w = right - left;
  2212. var h = top - bottom;
  2213. var p = far - near;
  2214. var x = ( right + left ) / w;
  2215. var y = ( top + bottom ) / h;
  2216. var z = ( far + near ) / p;
  2217. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2218. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2219. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  2220. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2221. return this;
  2222. },
  2223. clone: function () {
  2224. var te = this.elements;
  2225. return new THREE.Matrix4(
  2226. te[0], te[4], te[8], te[12],
  2227. te[1], te[5], te[9], te[13],
  2228. te[2], te[6], te[10], te[14],
  2229. te[3], te[7], te[11], te[15]
  2230. );
  2231. }
  2232. };
  2233. THREE.Matrix4.__v1 = new THREE.Vector3();
  2234. THREE.Matrix4.__v2 = new THREE.Vector3();
  2235. THREE.Matrix4.__v3 = new THREE.Vector3();
  2236. THREE.Matrix4.__m1 = new THREE.Matrix4();
  2237. THREE.Matrix4.__m2 = new THREE.Matrix4();
  2238. /**
  2239. * @author bhouston / http://exocortex.com
  2240. */
  2241. THREE.Ray = function ( origin, direction ) {
  2242. this.origin = origin !== undefined ? origin.clone() : new THREE.Vector3();
  2243. this.direction = direction !== undefined ? direction.clone() : new THREE.Vector3();
  2244. };
  2245. THREE.Ray.prototype = {
  2246. constructor: THREE.Ray,
  2247. set: function ( origin, direction ) {
  2248. this.origin.copy( origin );
  2249. this.direction.copy( direction );
  2250. return this;
  2251. },
  2252. copy: function ( ray ) {
  2253. this.origin.copy( ray.origin );
  2254. this.direction.copy( ray.direction );
  2255. return this;
  2256. },
  2257. at: function( t, optionalTarget ) {
  2258. var result = optionalTarget || new THREE.Vector3();
  2259. return result.copy( this.direction ).multiplyScalar( t ).addSelf( this.origin );
  2260. },
  2261. recastSelf: function ( t ) {
  2262. this.origin.copy( this.at( t, THREE.Ray.__v1 ) );
  2263. return this;
  2264. },
  2265. closestPointToPoint: function ( point, optionalTarget ) {
  2266. var result = optionalTarget || new THREE.Vector3();
  2267. result.sub( point, this.origin );
  2268. var directionDistance = result.dot( this.direction );
  2269. return result.copy( this.direction ).multiplyScalar( directionDistance ).addSelf( this.origin );
  2270. },
  2271. distanceToPoint: function ( point ) {
  2272. var directionDistance = THREE.Ray.__v1.sub( point, this.origin ).dot( this.direction );
  2273. THREE.Ray.__v1.copy( this.direction ).multiplyScalar( directionDistance ).addSelf( this.origin );
  2274. return THREE.Ray.__v1.distanceTo( point );
  2275. },
  2276. isIntersectionSphere: function( sphere ) {
  2277. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  2278. },
  2279. isIntersectionPlane: function ( plane ) {
  2280. // check if the line and plane are non-perpendicular, if they
  2281. // eventually they will intersect.
  2282. var denominator = plane.normal.dot( this.direction );
  2283. if ( denominator != 0 ) {
  2284. return true;
  2285. }
  2286. // line is coplanar, return origin
  2287. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2288. return true;
  2289. }
  2290. return false;
  2291. },
  2292. distanceToPlane: function ( plane ) {
  2293. var denominator = plane.normal.dot( this.direction );
  2294. if ( denominator == 0 ) {
  2295. // line is coplanar, return origin
  2296. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2297. return 0;
  2298. }
  2299. // Unsure if this is the correct method to handle this case.
  2300. return undefined;
  2301. }
  2302. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2303. return t;
  2304. },
  2305. intersectPlane: function ( plane, optionalTarget ) {
  2306. var t = this.distanceToPlane( plane );
  2307. if( t === undefined ) {
  2308. return undefined;
  2309. }
  2310. return this.at( t, optionalTarget );
  2311. },
  2312. transform: function ( matrix4 ) {
  2313. this.direction = matrix4.multiplyVector3( this.direction.addSelf( this.origin ) );
  2314. this.origin = matrix4.multiplyVector3( this.origin );
  2315. this.direction.subSelf( this.origin );
  2316. return this;
  2317. },
  2318. equals: function ( ray ) {
  2319. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  2320. },
  2321. clone: function () {
  2322. return new THREE.Ray().copy( this );
  2323. }
  2324. };
  2325. THREE.Ray.__v1 = new THREE.Vector3();
  2326. THREE.Ray.__v2 = new THREE.Vector3();/**
  2327. * @author mrdoob / http://mrdoob.com/
  2328. * @author alteredq / http://alteredqualia.com/
  2329. * @author bhouston / http://exocortex.com
  2330. */
  2331. THREE.Frustum = function ( ) {
  2332. this.planes = [
  2333. new THREE.Plane(),
  2334. new THREE.Plane(),
  2335. new THREE.Plane(),
  2336. new THREE.Plane(),
  2337. new THREE.Plane(),
  2338. new THREE.Plane()
  2339. ];
  2340. };
  2341. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  2342. var planes = this.planes;
  2343. var me = m.elements;
  2344. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  2345. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  2346. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  2347. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  2348. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  2349. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  2350. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  2351. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  2352. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  2353. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  2354. for ( var i = 0; i < 6; i ++ ) {
  2355. planes[ i ].normalize();
  2356. }
  2357. };
  2358. THREE.Frustum.prototype.contains = function ( object ) {
  2359. var planes = this.planes;
  2360. var matrix = object.matrixWorld;
  2361. var matrixPosition = matrix.getPosition();
  2362. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  2363. var distance = 0.0;
  2364. for ( var i = 0; i < 6; i ++ ) {
  2365. distance = planes[ i ].distanceToPoint( matrixPosition );
  2366. if ( distance <= radius ) return false;
  2367. }
  2368. return true;
  2369. };
  2370. THREE.Frustum.__v1 = new THREE.Vector3();
  2371. /**
  2372. * @author bhouston / http://exocortex.com
  2373. */
  2374. THREE.Plane = function ( normal, constant ) {
  2375. this.normal = normal !== undefined ? normal.clone() : new THREE.Vector3( 1, 0, 0 );
  2376. this.constant = constant !== undefined ? constant : 0;
  2377. };
  2378. THREE.Plane.prototype = {
  2379. constructor: THREE.Plane,
  2380. set: function ( normal, constant ) {
  2381. this.normal.copy( normal );
  2382. this.constant = constant;
  2383. return this;
  2384. },
  2385. setComponents: function ( x, y, z, w ) {
  2386. this.normal.set( x, y, z );
  2387. this.constant = w;
  2388. return this;
  2389. },
  2390. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  2391. this.normal.copy( normal ).normalize();
  2392. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  2393. return this;
  2394. },
  2395. setFromCoplanarPoints: function ( a, b, c ) {
  2396. var normal = THREE.Plane.__v1.sub( c, b ).crossSelf(
  2397. THREE.Plane.__v2.sub( a, b ) ).normalize();
  2398. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  2399. this.setFromNormalAndCoplanarPoint( normal, a );
  2400. return this;
  2401. },
  2402. copy: function ( plane ) {
  2403. this.normal.copy( plane.normal );
  2404. this.constant = plane.constant;
  2405. return this;
  2406. },
  2407. normalize: function () {
  2408. // Note: will lead to a divide by zero if the plane is invalid.
  2409. var inverseNormalLength = 1.0 / this.normal.length();
  2410. this.normal.multiplyScalar( inverseNormalLength );
  2411. this.constant *= inverseNormalLength;
  2412. return this;
  2413. },
  2414. distanceToPoint: function ( point ) {
  2415. return this.normal.dot( point ) + this.constant;
  2416. },
  2417. distanceToSphere: function ( sphere ) {
  2418. return this.distanceToPoint( sphere.center ) - sphere.radius;
  2419. },
  2420. projectPoint: function ( point, optionalTarget ) {
  2421. return this.orthoPoint( point, optionalTarget ).subSelf( point ).negate();
  2422. },
  2423. orthoPoint: function ( point, optionalTarget ) {
  2424. var perpendicularMagnitude = this.distanceToPoint( point );
  2425. var result = optionalTarget || new THREE.Vector3();
  2426. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  2427. },
  2428. isIntersectionLine: function ( startPoint, endPoint ) {
  2429. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  2430. var startSign = this.distanceToPoint( startPoint );
  2431. var endSign = this.distanceToPoint( endPoint );
  2432. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  2433. },
  2434. coplanarPoint: function ( optionalTarget ) {
  2435. var result = optionalTarget || new THREE.Vector3();
  2436. return result.copy( this.normal ).multiplyScalar( - this.constant );
  2437. },
  2438. transform: function( matrix, optionalNormalMatrix ) {
  2439. var newNormal = THREE.Plane.__v1, newCoplanarPoint = THREE.Plane.__v2;
  2440. // compute new normal based on theory here:
  2441. // http://www.songho.ca/opengl/gl_normaltransform.html
  2442. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getInverse( matrix ).transpose();
  2443. newNormal = optionalNormalMatrix.multiplyVector3( newNormal.copy( this.normal ) );
  2444. newCoplanarPoint = this.coplanarPoint( newCoplanarPoint );
  2445. newCoplanarPoint = matrix.multiplyVector3( newCoplanarPoint );
  2446. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  2447. return this;
  2448. },
  2449. translate: function ( offset ) {
  2450. this.constant = this.constant - offset.dot( this.normal );
  2451. return this;
  2452. },
  2453. equals: function ( plane ) {
  2454. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  2455. },
  2456. clone: function () {
  2457. return new THREE.Plane().copy( this );
  2458. }
  2459. };
  2460. THREE.Plane.__vZero = new THREE.Vector3( 0, 0, 0 );
  2461. THREE.Plane.__v1 = new THREE.Vector3();
  2462. THREE.Plane.__v2 = new THREE.Vector3();
  2463. /**
  2464. * @author bhouston / http://exocortex.com
  2465. * @author mrdoob / http://mrdoob.com/
  2466. */
  2467. THREE.Sphere = function ( center, radius ) {
  2468. this.center = center === undefined ? new THREE.Vector3() : center.clone();
  2469. this.radius = radius === undefined ? 0 : radius;
  2470. };
  2471. THREE.Sphere.prototype = {
  2472. constructor: THREE.Sphere,
  2473. set: function ( center, radius ) {
  2474. this.center.copy( center );
  2475. this.radius = radius;
  2476. return this;
  2477. },
  2478. setFromCenterAndPoints: function ( center, points ) {
  2479. var maxRadiusSq = 0;
  2480. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2481. var radiusSq = center.distanceToSquared( points[ i ] );
  2482. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2483. }
  2484. this.center = center;
  2485. this.radius = Math.sqrt( maxRadiusSq );
  2486. return this;
  2487. },
  2488. copy: function ( sphere ) {
  2489. this.center.copy( sphere.center );
  2490. this.radius = sphere.radius;
  2491. return this;
  2492. },
  2493. empty: function () {
  2494. return ( this.radius <= 0 );
  2495. },
  2496. containsPoint: function ( point ) {
  2497. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2498. },
  2499. distanceToPoint: function ( point ) {
  2500. return ( point.distanceTo( this.center ) - this.radius );
  2501. },
  2502. clampPoint: function ( point, optionalTarget ) {
  2503. var deltaLengthSq = this.center.distanceToSquared( point );
  2504. var result = optionalTarget || new THREE.Vector3();
  2505. result.copy( point );
  2506. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2507. result.subSelf( this.center ).normalize();
  2508. result.multiplyScalar( this.radius ).addSelf( this.center );
  2509. }
  2510. return result;
  2511. },
  2512. bounds: function ( optionalTarget ) {
  2513. var box = optionalTarget || new THREE.Box3();
  2514. box.set( this.center, this.center );
  2515. box.expandByScalar( this.radius );
  2516. return box;
  2517. },
  2518. transform: function ( matrix ) {
  2519. this.center = matrix.multiplyVector3( this.center );
  2520. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2521. return this;
  2522. },
  2523. translate: function ( offset ) {
  2524. this.center.addSelf( offset );
  2525. return this;
  2526. },
  2527. equals: function ( sphere ) {
  2528. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2529. },
  2530. clone: function () {
  2531. return new THREE.Sphere().copy( this );
  2532. }
  2533. };
  2534. /**
  2535. * @author alteredq / http://alteredqualia.com/
  2536. */
  2537. THREE.Math = {
  2538. // Clamp value to range <a, b>
  2539. clamp: function ( x, a, b ) {
  2540. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2541. },
  2542. // Clamp value to range <a, inf)
  2543. clampBottom: function ( x, a ) {
  2544. return x < a ? a : x;
  2545. },
  2546. // Linear mapping from range <a1, a2> to range <b1, b2>
  2547. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2548. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2549. },
  2550. // Random float from <0, 1> with 16 bits of randomness
  2551. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2552. random16: function () {
  2553. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2554. },
  2555. // Random integer from <low, high> interval
  2556. randInt: function ( low, high ) {
  2557. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2558. },
  2559. // Random float from <low, high> interval
  2560. randFloat: function ( low, high ) {
  2561. return low + Math.random() * ( high - low );
  2562. },
  2563. // Random float from <-range/2, range/2> interval
  2564. randFloatSpread: function ( range ) {
  2565. return range * ( 0.5 - Math.random() );
  2566. },
  2567. sign: function ( x ) {
  2568. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2569. },
  2570. degreesToRadians: function ( degrees ) {
  2571. return degrees * THREE.Math.__d2r;
  2572. },
  2573. radiansToDegrees: function ( radians ) {
  2574. return radians * THREE.Math.__r2d;
  2575. }
  2576. };
  2577. THREE.Math.__d2r = Math.PI / 180;
  2578. THREE.Math.__r2d = 180 / Math.PI;
  2579. /**
  2580. * @author mikael emtinger / http://gomo.se/
  2581. * @author alteredq / http://alteredqualia.com/
  2582. * @author WestLangley / http://github.com/WestLangley
  2583. */
  2584. THREE.Quaternion = function( x, y, z, w ) {
  2585. this.x = x || 0;
  2586. this.y = y || 0;
  2587. this.z = z || 0;
  2588. this.w = ( w !== undefined ) ? w : 1;
  2589. };
  2590. THREE.Quaternion.prototype = {
  2591. constructor: THREE.Quaternion,
  2592. set: function ( x, y, z, w ) {
  2593. this.x = x;
  2594. this.y = y;
  2595. this.z = z;
  2596. this.w = w;
  2597. return this;
  2598. },
  2599. copy: function ( q ) {
  2600. this.x = q.x;
  2601. this.y = q.y;
  2602. this.z = q.z;
  2603. this.w = q.w;
  2604. return this;
  2605. },
  2606. setFromEuler: function ( v, order ) {
  2607. // http://www.mathworks.com/matlabcentral/fileexchange/
  2608. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2609. // content/SpinCalc.m
  2610. var c1 = Math.cos( v.x / 2 );
  2611. var c2 = Math.cos( v.y / 2 );
  2612. var c3 = Math.cos( v.z / 2 );
  2613. var s1 = Math.sin( v.x / 2 );
  2614. var s2 = Math.sin( v.y / 2 );
  2615. var s3 = Math.sin( v.z / 2 );
  2616. if ( order === undefined || order === 'XYZ' ) {
  2617. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2618. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2619. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2620. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2621. } else if ( order === 'YXZ' ) {
  2622. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2623. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2624. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2625. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2626. } else if ( order === 'ZXY' ) {
  2627. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2628. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2629. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2630. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2631. } else if ( order === 'ZYX' ) {
  2632. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2633. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2634. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2635. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2636. } else if ( order === 'YZX' ) {
  2637. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2638. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2639. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2640. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2641. } else if ( order === 'XZY' ) {
  2642. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2643. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2644. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2645. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2646. }
  2647. return this;
  2648. },
  2649. setFromAxisAngle: function ( axis, angle ) {
  2650. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2651. // axis have to be normalized
  2652. var halfAngle = angle / 2,
  2653. s = Math.sin( halfAngle );
  2654. this.x = axis.x * s;
  2655. this.y = axis.y * s;
  2656. this.z = axis.z * s;
  2657. this.w = Math.cos( halfAngle );
  2658. return this;
  2659. },
  2660. setFromRotationMatrix: function ( m ) {
  2661. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2662. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2663. var te = m.elements,
  2664. m11 = te[0], m12 = te[4], m13 = te[8],
  2665. m21 = te[1], m22 = te[5], m23 = te[9],
  2666. m31 = te[2], m32 = te[6], m33 = te[10],
  2667. trace = m11 + m22 + m33,
  2668. s;
  2669. if( trace > 0 ) {
  2670. s = 0.5 / Math.sqrt( trace + 1.0 );
  2671. this.w = 0.25 / s;
  2672. this.x = ( m32 - m23 ) * s;
  2673. this.y = ( m13 - m31 ) * s;
  2674. this.z = ( m21 - m12 ) * s;
  2675. } else if ( m11 > m22 && m11 > m33 ) {
  2676. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2677. this.w = (m32 - m23 ) / s;
  2678. this.x = 0.25 * s;
  2679. this.y = (m12 + m21 ) / s;
  2680. this.z = (m13 + m31 ) / s;
  2681. } else if (m22 > m33) {
  2682. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2683. this.w = (m13 - m31 ) / s;
  2684. this.x = (m12 + m21 ) / s;
  2685. this.y = 0.25 * s;
  2686. this.z = (m23 + m32 ) / s;
  2687. } else {
  2688. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2689. this.w = ( m21 - m12 ) / s;
  2690. this.x = ( m13 + m31 ) / s;
  2691. this.y = ( m23 + m32 ) / s;
  2692. this.z = 0.25 * s;
  2693. }
  2694. return this;
  2695. },
  2696. inverse: function () {
  2697. this.conjugate().normalize();
  2698. return this;
  2699. },
  2700. conjugate: function () {
  2701. this.x *= -1;
  2702. this.y *= -1;
  2703. this.z *= -1;
  2704. return this;
  2705. },
  2706. length: function () {
  2707. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2708. },
  2709. normalize: function () {
  2710. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2711. if ( l === 0 ) {
  2712. this.x = 0;
  2713. this.y = 0;
  2714. this.z = 0;
  2715. this.w = 1;
  2716. } else {
  2717. l = 1 / l;
  2718. this.x = this.x * l;
  2719. this.y = this.y * l;
  2720. this.z = this.z * l;
  2721. this.w = this.w * l;
  2722. }
  2723. return this;
  2724. },
  2725. multiply: function ( a, b ) {
  2726. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2727. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
  2728. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2729. this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
  2730. this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
  2731. this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
  2732. this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
  2733. return this;
  2734. },
  2735. multiplySelf: function ( b ) {
  2736. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2737. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2738. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2739. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2740. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2741. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2742. return this;
  2743. },
  2744. multiplyVector3: function ( vector, dest ) {
  2745. if ( !dest ) { dest = vector; }
  2746. var x = vector.x, y = vector.y, z = vector.z,
  2747. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2748. // calculate quat * vector
  2749. var ix = qw * x + qy * z - qz * y,
  2750. iy = qw * y + qz * x - qx * z,
  2751. iz = qw * z + qx * y - qy * x,
  2752. iw = -qx * x - qy * y - qz * z;
  2753. // calculate result * inverse quat
  2754. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2755. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2756. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2757. return dest;
  2758. },
  2759. slerpSelf: function ( qb, t ) {
  2760. var x = this.x, y = this.y, z = this.z, w = this.w;
  2761. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2762. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  2763. if ( cosHalfTheta < 0 ) {
  2764. this.w = -qb.w;
  2765. this.x = -qb.x;
  2766. this.y = -qb.y;
  2767. this.z = -qb.z;
  2768. cosHalfTheta = -cosHalfTheta;
  2769. } else {
  2770. this.copy( qb );
  2771. }
  2772. if ( cosHalfTheta >= 1.0 ) {
  2773. this.w = w;
  2774. this.x = x;
  2775. this.y = y;
  2776. this.z = z;
  2777. return this;
  2778. }
  2779. var halfTheta = Math.acos( cosHalfTheta );
  2780. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2781. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2782. this.w = 0.5 * ( w + this.w );
  2783. this.x = 0.5 * ( x + this.x );
  2784. this.y = 0.5 * ( y + this.y );
  2785. this.z = 0.5 * ( z + this.z );
  2786. return this;
  2787. }
  2788. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2789. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2790. this.w = ( w * ratioA + this.w * ratioB );
  2791. this.x = ( x * ratioA + this.x * ratioB );
  2792. this.y = ( y * ratioA + this.y * ratioB );
  2793. this.z = ( z * ratioA + this.z * ratioB );
  2794. return this;
  2795. },
  2796. clone: function () {
  2797. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2798. }
  2799. }
  2800. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2801. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2802. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2803. if ( cosHalfTheta < 0 ) {
  2804. qm.w = -qb.w;
  2805. qm.x = -qb.x;
  2806. qm.y = -qb.y;
  2807. qm.z = -qb.z;
  2808. cosHalfTheta = -cosHalfTheta;
  2809. } else {
  2810. qm.copy( qb );
  2811. }
  2812. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2813. qm.w = qa.w;
  2814. qm.x = qa.x;
  2815. qm.y = qa.y;
  2816. qm.z = qa.z;
  2817. return qm;
  2818. }
  2819. var halfTheta = Math.acos( cosHalfTheta );
  2820. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2821. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2822. qm.w = 0.5 * ( qa.w + qm.w );
  2823. qm.x = 0.5 * ( qa.x + qm.x );
  2824. qm.y = 0.5 * ( qa.y + qm.y );
  2825. qm.z = 0.5 * ( qa.z + qm.z );
  2826. return qm;
  2827. }
  2828. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
  2829. var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2830. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2831. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2832. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2833. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2834. return qm;
  2835. }
  2836. /**
  2837. * Spline from Tween.js, slightly optimized (and trashed)
  2838. * http://sole.github.com/tween.js/examples/05_spline.html
  2839. *
  2840. * @author mrdoob / http://mrdoob.com/
  2841. * @author alteredq / http://alteredqualia.com/
  2842. */
  2843. THREE.Spline = function ( points ) {
  2844. this.points = points;
  2845. var c = [], v3 = { x: 0, y: 0, z: 0 },
  2846. point, intPoint, weight, w2, w3,
  2847. pa, pb, pc, pd;
  2848. this.initFromArray = function( a ) {
  2849. this.points = [];
  2850. for ( var i = 0; i < a.length; i++ ) {
  2851. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  2852. }
  2853. };
  2854. this.getPoint = function ( k ) {
  2855. point = ( this.points.length - 1 ) * k;
  2856. intPoint = Math.floor( point );
  2857. weight = point - intPoint;
  2858. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  2859. c[ 1 ] = intPoint;
  2860. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  2861. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  2862. pa = this.points[ c[ 0 ] ];
  2863. pb = this.points[ c[ 1 ] ];
  2864. pc = this.points[ c[ 2 ] ];
  2865. pd = this.points[ c[ 3 ] ];
  2866. w2 = weight * weight;
  2867. w3 = weight * w2;
  2868. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  2869. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  2870. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  2871. return v3;
  2872. };
  2873. this.getControlPointsArray = function () {
  2874. var i, p, l = this.points.length,
  2875. coords = [];
  2876. for ( i = 0; i < l; i ++ ) {
  2877. p = this.points[ i ];
  2878. coords[ i ] = [ p.x, p.y, p.z ];
  2879. }
  2880. return coords;
  2881. };
  2882. // approximate length by summing linear segments
  2883. this.getLength = function ( nSubDivisions ) {
  2884. var i, index, nSamples, position,
  2885. point = 0, intPoint = 0, oldIntPoint = 0,
  2886. oldPosition = new THREE.Vector3(),
  2887. tmpVec = new THREE.Vector3(),
  2888. chunkLengths = [],
  2889. totalLength = 0;
  2890. // first point has 0 length
  2891. chunkLengths[ 0 ] = 0;
  2892. if ( !nSubDivisions ) nSubDivisions = 100;
  2893. nSamples = this.points.length * nSubDivisions;
  2894. oldPosition.copy( this.points[ 0 ] );
  2895. for ( i = 1; i < nSamples; i ++ ) {
  2896. index = i / nSamples;
  2897. position = this.getPoint( index );
  2898. tmpVec.copy( position );
  2899. totalLength += tmpVec.distanceTo( oldPosition );
  2900. oldPosition.copy( position );
  2901. point = ( this.points.length - 1 ) * index;
  2902. intPoint = Math.floor( point );
  2903. if ( intPoint != oldIntPoint ) {
  2904. chunkLengths[ intPoint ] = totalLength;
  2905. oldIntPoint = intPoint;
  2906. }
  2907. }
  2908. // last point ends with total length
  2909. chunkLengths[ chunkLengths.length ] = totalLength;
  2910. return { chunks: chunkLengths, total: totalLength };
  2911. };
  2912. this.reparametrizeByArcLength = function ( samplingCoef ) {
  2913. var i, j,
  2914. index, indexCurrent, indexNext,
  2915. linearDistance, realDistance,
  2916. sampling, position,
  2917. newpoints = [],
  2918. tmpVec = new THREE.Vector3(),
  2919. sl = this.getLength();
  2920. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  2921. for ( i = 1; i < this.points.length; i++ ) {
  2922. //tmpVec.copy( this.points[ i - 1 ] );
  2923. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  2924. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  2925. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  2926. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  2927. indexNext = i / ( this.points.length - 1 );
  2928. for ( j = 1; j < sampling - 1; j++ ) {
  2929. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  2930. position = this.getPoint( index );
  2931. newpoints.push( tmpVec.copy( position ).clone() );
  2932. }
  2933. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  2934. }
  2935. this.points = newpoints;
  2936. };
  2937. // Catmull-Rom
  2938. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  2939. var v0 = ( p2 - p0 ) * 0.5,
  2940. v1 = ( p3 - p1 ) * 0.5;
  2941. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  2942. };
  2943. };
  2944. /**
  2945. * @author bhouston / http://exocortex.com
  2946. * @author mrdoob / http://mrdoob.com/
  2947. */
  2948. THREE.Triangle = function ( a, b, c ) {
  2949. this.a = new THREE.Vector3();
  2950. this.b = new THREE.Vector3();
  2951. this.c = new THREE.Vector3();
  2952. if( a !== undefined && b !== undefined && c !== undefined ) {
  2953. this.a.copy( a );
  2954. this.b.copy( b );
  2955. this.c.copy( c );
  2956. }
  2957. };
  2958. THREE.Triangle.normal = function( a, b, c, optionalTarget ) {
  2959. var result = optionalTarget || new THREE.Vector3();
  2960. result.sub( c, b );
  2961. THREE.Triangle.__v0.sub( a, b );
  2962. result.crossSelf( THREE.Triangle.__v0 );
  2963. var resultLengthSq = result.lengthSq();
  2964. if( resultLengthSq > 0 ) {
  2965. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  2966. }
  2967. return result.set( 0, 0, 0 );
  2968. };
  2969. // static/instance method to calculate barycoordinates
  2970. THREE.Triangle.barycoordFromPoint = function ( point, a, b, c, optionalTarget ) {
  2971. THREE.Triangle.__v0.sub( c, a );
  2972. THREE.Triangle.__v1.sub( b, a );
  2973. THREE.Triangle.__v2.sub( point, a );
  2974. var dot00 = THREE.Triangle.__v0.dot( THREE.Triangle.__v0 );
  2975. var dot01 = THREE.Triangle.__v0.dot( THREE.Triangle.__v1 );
  2976. var dot02 = THREE.Triangle.__v0.dot( THREE.Triangle.__v2 );
  2977. var dot11 = THREE.Triangle.__v1.dot( THREE.Triangle.__v1 );
  2978. var dot12 = THREE.Triangle.__v1.dot( THREE.Triangle.__v2 );
  2979. var denom = ( dot00 * dot11 - dot01 * dot01 );
  2980. var result = optionalTarget || new THREE.Vector3();
  2981. // colinear or singular triangle
  2982. if( denom == 0 ) {
  2983. // arbitrary location outside of triangle?
  2984. // not sure if this is the best idea, maybe should be returning undefined
  2985. return result.set( -2, -1, -1 );
  2986. }
  2987. var invDenom = 1 / denom;
  2988. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  2989. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  2990. // barycoordinates must always sum to 1
  2991. return result.set( 1 - u - v, v, u );
  2992. };
  2993. THREE.Triangle.containsPoint = function ( point, a, b, c ) {
  2994. // NOTE: need to use __v3 here because __v0, __v1 and __v2 are used in barycoordFromPoint.
  2995. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, THREE.Triangle.__v3 );
  2996. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  2997. };
  2998. THREE.Triangle.prototype = {
  2999. constructor: THREE.Triangle,
  3000. set: function ( a, b, c ) {
  3001. this.a.copy( a );
  3002. this.b.copy( b );
  3003. this.c.copy( c );
  3004. return this;
  3005. },
  3006. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3007. this.a.copy( points[i0] );
  3008. this.b.copy( points[i1] );
  3009. this.c.copy( points[i2] );
  3010. return this;
  3011. },
  3012. copy: function ( triangle ) {
  3013. this.a.copy( triangle.a );
  3014. this.b.copy( triangle.b );
  3015. this.c.copy( triangle.c );
  3016. return this;
  3017. },
  3018. area: function () {
  3019. THREE.Triangle.__v0.sub( this.c, this.b );
  3020. THREE.Triangle.__v1.sub( this.a, this.b );
  3021. return THREE.Triangle.__v0.crossSelf( THREE.Triangle.__v1 ).length() * 0.5;
  3022. },
  3023. midpoint: function ( optionalTarget ) {
  3024. var result = optionalTarget || new THREE.Vector3();
  3025. return result.add( this.a, this.b ).addSelf( this.c ).multiplyScalar( 1 / 3 );
  3026. },
  3027. normal: function ( optionalTarget ) {
  3028. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3029. },
  3030. plane: function ( optionalTarget ) {
  3031. var result = optionalTarget || new THREE.Plane();
  3032. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3033. },
  3034. barycoordFromPoint: function ( point, optionalTarget ) {
  3035. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3036. },
  3037. containsPoint: function ( point ) {
  3038. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3039. },
  3040. equals: function ( triangle ) {
  3041. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3042. },
  3043. clone: function () {
  3044. return new THREE.Triangle().copy( this );
  3045. }
  3046. };
  3047. THREE.Triangle.__v0 = new THREE.Vector3();
  3048. THREE.Triangle.__v1 = new THREE.Vector3();
  3049. THREE.Triangle.__v2 = new THREE.Vector3();
  3050. THREE.Triangle.__v3 = new THREE.Vector3();
  3051. /**
  3052. * @author mrdoob / http://mrdoob.com/
  3053. */
  3054. THREE.Vertex = function ( v ) {
  3055. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3056. return v;
  3057. };
  3058. /**
  3059. * @author mrdoob / http://mrdoob.com/
  3060. */
  3061. THREE.UV = function ( u, v ) {
  3062. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3063. return new THREE.Vector2( u, v );
  3064. };
  3065. /**
  3066. * @author alteredq / http://alteredqualia.com/
  3067. */
  3068. THREE.Clock = function ( autoStart ) {
  3069. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3070. this.startTime = 0;
  3071. this.oldTime = 0;
  3072. this.elapsedTime = 0;
  3073. this.running = false;
  3074. };
  3075. THREE.Clock.prototype.start = function () {
  3076. this.startTime = Date.now();
  3077. this.oldTime = this.startTime;
  3078. this.running = true;
  3079. };
  3080. THREE.Clock.prototype.stop = function () {
  3081. this.getElapsedTime();
  3082. this.running = false;
  3083. };
  3084. THREE.Clock.prototype.getElapsedTime = function () {
  3085. this.getDelta();
  3086. return this.elapsedTime;
  3087. };
  3088. THREE.Clock.prototype.getDelta = function () {
  3089. var diff = 0;
  3090. if ( this.autoStart && ! this.running ) {
  3091. this.start();
  3092. }
  3093. if ( this.running ) {
  3094. var newTime = Date.now();
  3095. diff = 0.001 * ( newTime - this.oldTime );
  3096. this.oldTime = newTime;
  3097. this.elapsedTime += diff;
  3098. }
  3099. return diff;
  3100. };/**
  3101. * https://github.com/mrdoob/eventdispatcher.js/
  3102. */
  3103. THREE.EventDispatcher = function () {
  3104. var listeners = {};
  3105. this.addEventListener = function ( type, listener ) {
  3106. if ( listeners[ type ] === undefined ) {
  3107. listeners[ type ] = [];
  3108. }
  3109. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3110. listeners[ type ].push( listener );
  3111. }
  3112. };
  3113. this.removeEventListener = function ( type, listener ) {
  3114. var index = listeners[ type ].indexOf( listener );
  3115. if ( index !== - 1 ) {
  3116. listeners[ type ].splice( index, 1 );
  3117. }
  3118. };
  3119. this.dispatchEvent = function ( event ) {
  3120. var listenerArray = listeners[ event.type ];
  3121. if ( listenerArray !== undefined ) {
  3122. event.target = this;
  3123. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3124. listenerArray[ i ].call( this, event );
  3125. }
  3126. }
  3127. };
  3128. };/**
  3129. * @author mrdoob / http://mrdoob.com/
  3130. * @author bhouston / http://exocortex.com/
  3131. */
  3132. ( function ( THREE ) {
  3133. THREE.Raycaster = function ( origin, direction, near, far ) {
  3134. this.ray = new THREE.Ray( origin, direction );
  3135. // normalized ray.direction required for accurate distance calculations
  3136. if( this.ray.direction.length() > 0 ) {
  3137. this.ray.direction.normalize();
  3138. }
  3139. this.near = near || 0;
  3140. this.far = far || Infinity;
  3141. };
  3142. var sphere = new THREE.Sphere();
  3143. var localRay = new THREE.Ray();
  3144. var facePlane = new THREE.Plane();
  3145. var intersectPoint = new THREE.Vector3();
  3146. var inverseMatrix = new THREE.Matrix4();
  3147. var descSort = function ( a, b ) {
  3148. return a.distance - b.distance;
  3149. };
  3150. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  3151. // http://www.blackpawn.com/texts/pointinpoly/default.html
  3152. var intersectObject = function ( object, raycaster, intersects ) {
  3153. if ( object instanceof THREE.Particle ) {
  3154. var distance = raycaster.ray.distanceToPoint( object.matrixWorld.getPosition() );
  3155. if ( distance > object.scale.x ) {
  3156. return intersects;
  3157. }
  3158. intersects.push( {
  3159. distance: distance,
  3160. point: object.position,
  3161. face: null,
  3162. object: object
  3163. } );
  3164. } else if ( object instanceof THREE.Mesh ) {
  3165. // Checking boundingSphere distance to ray
  3166. sphere.set(
  3167. object.matrixWorld.getPosition(),
  3168. object.geometry.boundingSphere.radius* object.matrixWorld.getMaxScaleOnAxis() );
  3169. if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
  3170. return intersects;
  3171. }
  3172. // Checking faces
  3173. var geometry = object.geometry;
  3174. var vertices = geometry.vertices;
  3175. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3176. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3177. var side = object.material.side;
  3178. var a, b, c, d;
  3179. var precision = raycaster.precision;
  3180. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  3181. inverseMatrix.getInverse( object.matrixWorld );
  3182. localRay.copy( raycaster.ray ).transform( inverseMatrix );
  3183. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3184. var face = geometry.faces[ f ];
  3185. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3186. if ( material === undefined ) continue;
  3187. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3188. var planeDistance = localRay.distanceToPlane( facePlane );
  3189. // bail if raycaster and plane are parallel
  3190. if ( Math.abs( planeDistance ) < precision ) continue;
  3191. // if negative distance, then plane is behind raycaster
  3192. if ( planeDistance < 0 ) continue;
  3193. // check if we hit the wrong side of a single sided face
  3194. side = material.side;
  3195. if( side !== THREE.DoubleSide ) {
  3196. var planeSign = localRay.direction.dot( facePlane.normal );
  3197. if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3198. }
  3199. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3200. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3201. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3202. if ( face instanceof THREE.Face3 ) {
  3203. a = vertices[ face.a ];
  3204. b = vertices[ face.b ];
  3205. c = vertices[ face.c ];
  3206. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3207. } else if ( face instanceof THREE.Face4 ) {
  3208. a = vertices[ face.a ];
  3209. b = vertices[ face.b ];
  3210. c = vertices[ face.c ];
  3211. d = vertices[ face.d ];
  3212. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3213. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3214. } else {
  3215. // This is added because if we call out of this if/else group when none of the cases
  3216. // match it will add a point to the intersection list erroneously.
  3217. throw Error( "face type not supported" );
  3218. }
  3219. intersects.push( {
  3220. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3221. point: raycaster.ray.at( planeDistance ),
  3222. face: face,
  3223. faceIndex: f,
  3224. object: object
  3225. } );
  3226. }
  3227. }
  3228. };
  3229. var intersectDescendants = function ( object, raycaster, intersects ) {
  3230. var descendants = object.getDescendants();
  3231. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3232. intersectObject( descendants[ i ], raycaster, intersects );
  3233. }
  3234. };
  3235. //
  3236. THREE.Raycaster.prototype.precision = 0.0001;
  3237. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3238. this.ray.set( origin, direction );
  3239. // normalized ray.direction required for accurate distance calculations
  3240. if( this.ray.direction.length() > 0 ) {
  3241. this.ray.direction.normalize();
  3242. }
  3243. };
  3244. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3245. var intersects = [];
  3246. if ( recursive === true ) {
  3247. intersectDescendants( object, this, intersects );
  3248. }
  3249. intersectObject( object, this, intersects );
  3250. intersects.sort( descSort );
  3251. return intersects;
  3252. };
  3253. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3254. var intersects = [];
  3255. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3256. intersectObject( objects[ i ], this, intersects );
  3257. if ( recursive === true ) {
  3258. intersectDescendants( objects[ i ], this, intersects );
  3259. }
  3260. }
  3261. intersects.sort( descSort );
  3262. return intersects;
  3263. };
  3264. }( THREE ) );
  3265. /**
  3266. * @author mrdoob / http://mrdoob.com/
  3267. * @author mikael emtinger / http://gomo.se/
  3268. * @author alteredq / http://alteredqualia.com/
  3269. */
  3270. THREE.Object3D = function () {
  3271. this.id = THREE.Object3DIdCount ++;
  3272. this.name = '';
  3273. this.properties = {};
  3274. this.parent = undefined;
  3275. this.children = [];
  3276. this.up = new THREE.Vector3( 0, 1, 0 );
  3277. this.position = new THREE.Vector3();
  3278. this.rotation = new THREE.Vector3();
  3279. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3280. this.scale = new THREE.Vector3( 1, 1, 1 );
  3281. this.renderDepth = null;
  3282. this.rotationAutoUpdate = true;
  3283. this.matrix = new THREE.Matrix4();
  3284. this.matrixWorld = new THREE.Matrix4();
  3285. this.matrixRotationWorld = new THREE.Matrix4();
  3286. this.matrixAutoUpdate = true;
  3287. this.matrixWorldNeedsUpdate = true;
  3288. this.quaternion = new THREE.Quaternion();
  3289. this.useQuaternion = false;
  3290. this.visible = true;
  3291. this.castShadow = false;
  3292. this.receiveShadow = false;
  3293. this.frustumCulled = true;
  3294. this._vector = new THREE.Vector3();
  3295. };
  3296. THREE.Object3D.prototype = {
  3297. constructor: THREE.Object3D,
  3298. applyMatrix: function ( matrix ) {
  3299. this.matrix.multiply( matrix, this.matrix );
  3300. this.scale.getScaleFromMatrix( this.matrix );
  3301. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  3302. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  3303. this.position.getPositionFromMatrix( this.matrix );
  3304. },
  3305. translate: function ( distance, axis ) {
  3306. this.matrix.rotateAxis( axis );
  3307. this.position.addSelf( axis.multiplyScalar( distance ) );
  3308. },
  3309. translateX: function ( distance ) {
  3310. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  3311. },
  3312. translateY: function ( distance ) {
  3313. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  3314. },
  3315. translateZ: function ( distance ) {
  3316. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  3317. },
  3318. localToWorld: function ( vector ) {
  3319. return this.matrixWorld.multiplyVector3( vector );
  3320. },
  3321. worldToLocal: function ( vector ) {
  3322. return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
  3323. },
  3324. lookAt: function ( vector ) {
  3325. // TODO: Add hierarchy support.
  3326. this.matrix.lookAt( vector, this.position, this.up );
  3327. if ( this.rotationAutoUpdate ) {
  3328. if ( this.useQuaternion === false ) {
  3329. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3330. } else {
  3331. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  3332. }
  3333. }
  3334. },
  3335. add: function ( object ) {
  3336. if ( object === this ) {
  3337. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3338. return;
  3339. }
  3340. if ( object instanceof THREE.Object3D ) {
  3341. if ( object.parent !== undefined ) {
  3342. object.parent.remove( object );
  3343. }
  3344. object.parent = this;
  3345. this.children.push( object );
  3346. // add to scene
  3347. var scene = this;
  3348. while ( scene.parent !== undefined ) {
  3349. scene = scene.parent;
  3350. }
  3351. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3352. scene.__addObject( object );
  3353. }
  3354. }
  3355. },
  3356. remove: function ( object ) {
  3357. var index = this.children.indexOf( object );
  3358. if ( index !== - 1 ) {
  3359. object.parent = undefined;
  3360. this.children.splice( index, 1 );
  3361. // remove from scene
  3362. var scene = this;
  3363. while ( scene.parent !== undefined ) {
  3364. scene = scene.parent;
  3365. }
  3366. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3367. scene.__removeObject( object );
  3368. }
  3369. }
  3370. },
  3371. traverse: function ( callback ) {
  3372. callback( this );
  3373. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3374. this.children[ i ].traverse( callback );
  3375. }
  3376. },
  3377. getChildByName: function ( name, recursive ) {
  3378. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3379. var child = this.children[ i ];
  3380. if ( child.name === name ) {
  3381. return child;
  3382. }
  3383. if ( recursive === true ) {
  3384. child = child.getChildByName( name, recursive );
  3385. if ( child !== undefined ) {
  3386. return child;
  3387. }
  3388. }
  3389. }
  3390. return undefined;
  3391. },
  3392. getDescendants: function ( array ) {
  3393. if ( array === undefined ) array = [];
  3394. Array.prototype.push.apply( array, this.children );
  3395. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3396. this.children[ i ].getDescendants( array );
  3397. }
  3398. return array;
  3399. },
  3400. updateMatrix: function () {
  3401. this.matrix.setPosition( this.position );
  3402. if ( this.useQuaternion === false ) {
  3403. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  3404. } else {
  3405. this.matrix.setRotationFromQuaternion( this.quaternion );
  3406. }
  3407. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  3408. this.matrix.scale( this.scale );
  3409. }
  3410. this.matrixWorldNeedsUpdate = true;
  3411. },
  3412. updateMatrixWorld: function ( force ) {
  3413. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  3414. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  3415. if ( this.parent === undefined ) {
  3416. this.matrixWorld.copy( this.matrix );
  3417. } else {
  3418. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  3419. }
  3420. this.matrixWorldNeedsUpdate = false;
  3421. force = true;
  3422. }
  3423. // update children
  3424. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3425. this.children[ i ].updateMatrixWorld( force );
  3426. }
  3427. },
  3428. clone: function ( object ) {
  3429. if ( object === undefined ) object = new THREE.Object3D();
  3430. object.name = this.name;
  3431. object.up.copy( this.up );
  3432. object.position.copy( this.position );
  3433. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  3434. object.eulerOrder = this.eulerOrder;
  3435. object.scale.copy( this.scale );
  3436. object.renderDepth = this.renderDepth;
  3437. object.rotationAutoUpdate = this.rotationAutoUpdate;
  3438. object.matrix.copy( this.matrix );
  3439. object.matrixWorld.copy( this.matrixWorld );
  3440. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  3441. object.matrixAutoUpdate = this.matrixAutoUpdate;
  3442. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  3443. object.quaternion.copy( this.quaternion );
  3444. object.useQuaternion = this.useQuaternion;
  3445. object.visible = this.visible;
  3446. object.castShadow = this.castShadow;
  3447. object.receiveShadow = this.receiveShadow;
  3448. object.frustumCulled = this.frustumCulled;
  3449. for ( var i = 0; i < this.children.length; i ++ ) {
  3450. var child = this.children[ i ];
  3451. object.add( child.clone() );
  3452. }
  3453. return object;
  3454. }
  3455. };
  3456. THREE.Object3D.__m1 = new THREE.Matrix4();
  3457. THREE.Object3D.defaultEulerOrder = 'XYZ',
  3458. THREE.Object3DIdCount = 0;
  3459. /**
  3460. * @author mrdoob / http://mrdoob.com/
  3461. * @author supereggbert / http://www.paulbrunt.co.uk/
  3462. * @author julianwa / https://github.com/julianwa
  3463. */
  3464. THREE.Projector = function() {
  3465. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  3466. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  3467. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  3468. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  3469. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  3470. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  3471. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  3472. _vector3 = new THREE.Vector3(),
  3473. _vector4 = new THREE.Vector4(),
  3474. _viewProjectionMatrix = new THREE.Matrix4(),
  3475. _modelViewProjectionMatrix = new THREE.Matrix4(),
  3476. _normalMatrix = new THREE.Matrix3(),
  3477. _frustum = new THREE.Frustum(),
  3478. _clippedVertex1PositionScreen = new THREE.Vector4(),
  3479. _clippedVertex2PositionScreen = new THREE.Vector4(),
  3480. _face3VertexNormals;
  3481. this.projectVector = function ( vector, camera ) {
  3482. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3483. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  3484. _viewProjectionMatrix.multiplyVector3( vector );
  3485. return vector;
  3486. };
  3487. this.unprojectVector = function ( vector, camera ) {
  3488. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  3489. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  3490. _viewProjectionMatrix.multiplyVector3( vector );
  3491. return vector;
  3492. };
  3493. this.pickingRay = function ( vector, camera ) {
  3494. // set two vectors with opposing z values
  3495. vector.z = -1.0;
  3496. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  3497. this.unprojectVector( vector, camera );
  3498. this.unprojectVector( end, camera );
  3499. // find direction from vector to end
  3500. end.subSelf( vector ).normalize();
  3501. return new THREE.Raycaster( vector, end );
  3502. };
  3503. var projectGraph = function ( root, sortObjects ) {
  3504. _objectCount = 0;
  3505. _renderData.objects.length = 0;
  3506. _renderData.sprites.length = 0;
  3507. _renderData.lights.length = 0;
  3508. var projectObject = function ( parent ) {
  3509. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  3510. var object = parent.children[ c ];
  3511. if ( object.visible === false ) continue;
  3512. if ( object instanceof THREE.Light ) {
  3513. _renderData.lights.push( object );
  3514. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  3515. if ( object.frustumCulled === false || _frustum.contains( object ) === true ) {
  3516. _object = getNextObjectInPool();
  3517. _object.object = object;
  3518. if ( object.renderDepth !== null ) {
  3519. _object.z = object.renderDepth;
  3520. } else {
  3521. _vector3.copy( object.matrixWorld.getPosition() );
  3522. _viewProjectionMatrix.multiplyVector3( _vector3 );
  3523. _object.z = _vector3.z;
  3524. }
  3525. _renderData.objects.push( _object );
  3526. }
  3527. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  3528. _object = getNextObjectInPool();
  3529. _object.object = object;
  3530. // TODO: Find an elegant and performant solution and remove this dupe code.
  3531. if ( object.renderDepth !== null ) {
  3532. _object.z = object.renderDepth;
  3533. } else {
  3534. _vector3.copy( object.matrixWorld.getPosition() );
  3535. _viewProjectionMatrix.multiplyVector3( _vector3 );
  3536. _object.z = _vector3.z;
  3537. }
  3538. _renderData.sprites.push( _object );
  3539. } else {
  3540. _object = getNextObjectInPool();
  3541. _object.object = object;
  3542. if ( object.renderDepth !== null ) {
  3543. _object.z = object.renderDepth;
  3544. } else {
  3545. _vector3.copy( object.matrixWorld.getPosition() );
  3546. _viewProjectionMatrix.multiplyVector3( _vector3 );
  3547. _object.z = _vector3.z;
  3548. }
  3549. _renderData.objects.push( _object );
  3550. }
  3551. projectObject( object );
  3552. }
  3553. };
  3554. projectObject( root );
  3555. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  3556. return _renderData;
  3557. };
  3558. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  3559. var near = camera.near, far = camera.far, visible = false,
  3560. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object, modelMatrix,
  3561. geometry, vertices, vertex, vertexPositionScreen,
  3562. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  3563. v1, v2, v3, v4, isFaceMaterial, objectMaterials, material, side;
  3564. _face3Count = 0;
  3565. _face4Count = 0;
  3566. _lineCount = 0;
  3567. _particleCount = 0;
  3568. _renderData.elements.length = 0;
  3569. scene.updateMatrixWorld();
  3570. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  3571. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3572. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  3573. _frustum.setFromMatrix( _viewProjectionMatrix );
  3574. _renderData = projectGraph( scene, sortObjects );
  3575. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  3576. object = _renderData.objects[ o ].object;
  3577. modelMatrix = object.matrixWorld;
  3578. _vertexCount = 0;
  3579. if ( object instanceof THREE.Mesh ) {
  3580. geometry = object.geometry;
  3581. vertices = geometry.vertices;
  3582. faces = geometry.faces;
  3583. faceVertexUvs = geometry.faceVertexUvs;
  3584. _normalMatrix.getInverse( modelMatrix );
  3585. _normalMatrix.transpose();
  3586. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3587. objectMaterials = isFaceMaterial === true ? object.material : null;
  3588. side = object.material.side;
  3589. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  3590. _vertex = getNextVertexInPool();
  3591. _vertex.positionWorld.copy( vertices[ v ] );
  3592. modelMatrix.multiplyVector3( _vertex.positionWorld );
  3593. _vertex.positionScreen.copy( _vertex.positionWorld );
  3594. _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
  3595. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  3596. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  3597. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  3598. }
  3599. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  3600. face = faces[ f ];
  3601. material = isFaceMaterial === true ? objectMaterials.materials[ face.materialIndex ] : object.material;
  3602. if ( material === undefined ) continue;
  3603. side = material.side;
  3604. if ( face instanceof THREE.Face3 ) {
  3605. v1 = _vertexPool[ face.a ];
  3606. v2 = _vertexPool[ face.b ];
  3607. v3 = _vertexPool[ face.c ];
  3608. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  3609. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3610. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  3611. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3612. _face = getNextFace3InPool();
  3613. _face.v1.copy( v1 );
  3614. _face.v2.copy( v2 );
  3615. _face.v3.copy( v3 );
  3616. } else {
  3617. continue;
  3618. }
  3619. } else {
  3620. continue;
  3621. }
  3622. } else if ( face instanceof THREE.Face4 ) {
  3623. v1 = _vertexPool[ face.a ];
  3624. v2 = _vertexPool[ face.b ];
  3625. v3 = _vertexPool[ face.c ];
  3626. v4 = _vertexPool[ face.d ];
  3627. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  3628. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3629. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  3630. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  3631. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  3632. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3633. _face = getNextFace4InPool();
  3634. _face.v1.copy( v1 );
  3635. _face.v2.copy( v2 );
  3636. _face.v3.copy( v3 );
  3637. _face.v4.copy( v4 );
  3638. } else {
  3639. continue;
  3640. }
  3641. } else {
  3642. continue;
  3643. }
  3644. }
  3645. _face.normalWorld.copy( face.normal );
  3646. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
  3647. _normalMatrix.multiplyVector3( _face.normalWorld ).normalize();
  3648. _face.centroidWorld.copy( face.centroid );
  3649. modelMatrix.multiplyVector3( _face.centroidWorld );
  3650. _face.centroidScreen.copy( _face.centroidWorld );
  3651. _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
  3652. faceVertexNormals = face.vertexNormals;
  3653. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  3654. normal = _face.vertexNormalsWorld[ n ];
  3655. normal.copy( faceVertexNormals[ n ] );
  3656. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
  3657. _normalMatrix.multiplyVector3( normal ).normalize();
  3658. }
  3659. _face.vertexNormalsLength = faceVertexNormals.length;
  3660. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  3661. uvs = faceVertexUvs[ c ][ f ];
  3662. if ( uvs === undefined ) continue;
  3663. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  3664. _face.uvs[ c ][ u ] = uvs[ u ];
  3665. }
  3666. }
  3667. _face.color = face.color;
  3668. _face.material = material;
  3669. _face.z = _face.centroidScreen.z;
  3670. _renderData.elements.push( _face );
  3671. }
  3672. } else if ( object instanceof THREE.Line ) {
  3673. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
  3674. vertices = object.geometry.vertices;
  3675. v1 = getNextVertexInPool();
  3676. v1.positionScreen.copy( vertices[ 0 ] );
  3677. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  3678. // Handle LineStrip and LinePieces
  3679. var step = object.type === THREE.LinePieces ? 2 : 1;
  3680. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  3681. v1 = getNextVertexInPool();
  3682. v1.positionScreen.copy( vertices[ v ] );
  3683. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  3684. if ( ( v + 1 ) % step > 0 ) continue;
  3685. v2 = _vertexPool[ _vertexCount - 2 ];
  3686. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  3687. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  3688. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  3689. // Perform the perspective divide
  3690. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  3691. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  3692. _line = getNextLineInPool();
  3693. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  3694. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  3695. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  3696. _line.material = object.material;
  3697. _renderData.elements.push( _line );
  3698. }
  3699. }
  3700. }
  3701. }
  3702. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  3703. object = _renderData.sprites[ o ].object;
  3704. modelMatrix = object.matrixWorld;
  3705. if ( object instanceof THREE.Particle ) {
  3706. _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
  3707. _viewProjectionMatrix.multiplyVector4( _vector4 );
  3708. _vector4.z /= _vector4.w;
  3709. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  3710. _particle = getNextParticleInPool();
  3711. _particle.object = object;
  3712. _particle.x = _vector4.x / _vector4.w;
  3713. _particle.y = _vector4.y / _vector4.w;
  3714. _particle.z = _vector4.z;
  3715. _particle.rotation = object.rotation.z;
  3716. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  3717. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  3718. _particle.material = object.material;
  3719. _renderData.elements.push( _particle );
  3720. }
  3721. }
  3722. }
  3723. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  3724. return _renderData;
  3725. };
  3726. // Pools
  3727. function getNextObjectInPool() {
  3728. if ( _objectCount === _objectPoolLength ) {
  3729. var object = new THREE.RenderableObject();
  3730. _objectPool.push( object );
  3731. _objectPoolLength ++;
  3732. _objectCount ++;
  3733. return object;
  3734. }
  3735. return _objectPool[ _objectCount ++ ];
  3736. }
  3737. function getNextVertexInPool() {
  3738. if ( _vertexCount === _vertexPoolLength ) {
  3739. var vertex = new THREE.RenderableVertex();
  3740. _vertexPool.push( vertex );
  3741. _vertexPoolLength ++;
  3742. _vertexCount ++;
  3743. return vertex;
  3744. }
  3745. return _vertexPool[ _vertexCount ++ ];
  3746. }
  3747. function getNextFace3InPool() {
  3748. if ( _face3Count === _face3PoolLength ) {
  3749. var face = new THREE.RenderableFace3();
  3750. _face3Pool.push( face );
  3751. _face3PoolLength ++;
  3752. _face3Count ++;
  3753. return face;
  3754. }
  3755. return _face3Pool[ _face3Count ++ ];
  3756. }
  3757. function getNextFace4InPool() {
  3758. if ( _face4Count === _face4PoolLength ) {
  3759. var face = new THREE.RenderableFace4();
  3760. _face4Pool.push( face );
  3761. _face4PoolLength ++;
  3762. _face4Count ++;
  3763. return face;
  3764. }
  3765. return _face4Pool[ _face4Count ++ ];
  3766. }
  3767. function getNextLineInPool() {
  3768. if ( _lineCount === _linePoolLength ) {
  3769. var line = new THREE.RenderableLine();
  3770. _linePool.push( line );
  3771. _linePoolLength ++;
  3772. _lineCount ++
  3773. return line;
  3774. }
  3775. return _linePool[ _lineCount ++ ];
  3776. }
  3777. function getNextParticleInPool() {
  3778. if ( _particleCount === _particlePoolLength ) {
  3779. var particle = new THREE.RenderableParticle();
  3780. _particlePool.push( particle );
  3781. _particlePoolLength ++;
  3782. _particleCount ++
  3783. return particle;
  3784. }
  3785. return _particlePool[ _particleCount ++ ];
  3786. }
  3787. //
  3788. function painterSort( a, b ) {
  3789. return b.z - a.z;
  3790. }
  3791. function clipLine( s1, s2 ) {
  3792. var alpha1 = 0, alpha2 = 1,
  3793. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  3794. // Z = -1 and Z = +1, respectively.
  3795. bc1near = s1.z + s1.w,
  3796. bc2near = s2.z + s2.w,
  3797. bc1far = - s1.z + s1.w,
  3798. bc2far = - s2.z + s2.w;
  3799. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  3800. // Both vertices lie entirely within all clip planes.
  3801. return true;
  3802. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  3803. // Both vertices lie entirely outside one of the clip planes.
  3804. return false;
  3805. } else {
  3806. // The line segment spans at least one clip plane.
  3807. if ( bc1near < 0 ) {
  3808. // v1 lies outside the near plane, v2 inside
  3809. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  3810. } else if ( bc2near < 0 ) {
  3811. // v2 lies outside the near plane, v1 inside
  3812. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  3813. }
  3814. if ( bc1far < 0 ) {
  3815. // v1 lies outside the far plane, v2 inside
  3816. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  3817. } else if ( bc2far < 0 ) {
  3818. // v2 lies outside the far plane, v2 inside
  3819. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  3820. }
  3821. if ( alpha2 < alpha1 ) {
  3822. // The line segment spans two boundaries, but is outside both of them.
  3823. // (This can't happen when we're only clipping against just near/far but good
  3824. // to leave the check here for future usage if other clip planes are added.)
  3825. return false;
  3826. } else {
  3827. // Update the s1 and s2 vertices to match the clipped line segment.
  3828. s1.lerpSelf( s2, alpha1 );
  3829. s2.lerpSelf( s1, 1 - alpha2 );
  3830. return true;
  3831. }
  3832. }
  3833. }
  3834. };
  3835. /**
  3836. * @author mrdoob / http://mrdoob.com/
  3837. * @author alteredq / http://alteredqualia.com/
  3838. */
  3839. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  3840. this.a = a;
  3841. this.b = b;
  3842. this.c = c;
  3843. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  3844. this.vertexNormals = normal instanceof Array ? normal : [ ];
  3845. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  3846. this.vertexColors = color instanceof Array ? color : [];
  3847. this.vertexTangents = [];
  3848. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  3849. this.centroid = new THREE.Vector3();
  3850. };
  3851. THREE.Face3.prototype = {
  3852. constructor: THREE.Face3,
  3853. clone: function () {
  3854. var face = new THREE.Face3( this.a, this.b, this.c );
  3855. face.normal.copy( this.normal );
  3856. face.color.copy( this.color );
  3857. face.centroid.copy( this.centroid );
  3858. face.materialIndex = this.materialIndex;
  3859. var i, il;
  3860. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  3861. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  3862. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  3863. return face;
  3864. }
  3865. };
  3866. /**
  3867. * @author mrdoob / http://mrdoob.com/
  3868. * @author alteredq / http://alteredqualia.com/
  3869. */
  3870. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  3871. this.a = a;
  3872. this.b = b;
  3873. this.c = c;
  3874. this.d = d;
  3875. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  3876. this.vertexNormals = normal instanceof Array ? normal : [ ];
  3877. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  3878. this.vertexColors = color instanceof Array ? color : [];
  3879. this.vertexTangents = [];
  3880. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  3881. this.centroid = new THREE.Vector3();
  3882. };
  3883. THREE.Face4.prototype = {
  3884. constructor: THREE.Face4,
  3885. clone: function () {
  3886. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  3887. face.normal.copy( this.normal );
  3888. face.color.copy( this.color );
  3889. face.centroid.copy( this.centroid );
  3890. face.materialIndex = this.materialIndex;
  3891. var i, il;
  3892. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  3893. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  3894. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  3895. return face;
  3896. }
  3897. };
  3898. /**
  3899. * @author mrdoob / http://mrdoob.com/
  3900. * @author kile / http://kile.stravaganza.org/
  3901. * @author alteredq / http://alteredqualia.com/
  3902. * @author mikael emtinger / http://gomo.se/
  3903. * @author zz85 / http://www.lab4games.net/zz85/blog
  3904. * @author bhouston / http://exocortex.com
  3905. */
  3906. THREE.Geometry = function () {
  3907. THREE.EventDispatcher.call( this );
  3908. this.id = THREE.GeometryIdCount ++;
  3909. this.name = '';
  3910. this.vertices = [];
  3911. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  3912. this.normals = []; // one-to-one vertex normals, used in Ribbon
  3913. this.faces = [];
  3914. this.faceUvs = [[]];
  3915. this.faceVertexUvs = [[]];
  3916. this.morphTargets = [];
  3917. this.morphColors = [];
  3918. this.morphNormals = [];
  3919. this.skinWeights = [];
  3920. this.skinIndices = [];
  3921. this.lineDistances = [];
  3922. this.boundingBox = null;
  3923. this.boundingSphere = null;
  3924. this.hasTangents = false;
  3925. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  3926. // update flags
  3927. this.verticesNeedUpdate = false;
  3928. this.elementsNeedUpdate = false;
  3929. this.uvsNeedUpdate = false;
  3930. this.normalsNeedUpdate = false;
  3931. this.tangentsNeedUpdate = false;
  3932. this.colorsNeedUpdate = false;
  3933. this.lineDistancesNeedUpdate = false;
  3934. this.buffersNeedUpdate = false;
  3935. };
  3936. THREE.Geometry.prototype = {
  3937. constructor: THREE.Geometry,
  3938. applyMatrix: function ( matrix ) {
  3939. var normalMatrix = new THREE.Matrix3();
  3940. normalMatrix.getInverse( matrix ).transpose();
  3941. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  3942. var vertex = this.vertices[ i ];
  3943. matrix.multiplyVector3( vertex );
  3944. }
  3945. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  3946. var face = this.faces[ i ];
  3947. normalMatrix.multiplyVector3( face.normal ).normalize();
  3948. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  3949. normalMatrix.multiplyVector3( face.vertexNormals[ j ] ).normalize();
  3950. }
  3951. matrix.multiplyVector3( face.centroid );
  3952. }
  3953. },
  3954. computeCentroids: function () {
  3955. var f, fl, face;
  3956. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3957. face = this.faces[ f ];
  3958. face.centroid.set( 0, 0, 0 );
  3959. if ( face instanceof THREE.Face3 ) {
  3960. face.centroid.addSelf( this.vertices[ face.a ] );
  3961. face.centroid.addSelf( this.vertices[ face.b ] );
  3962. face.centroid.addSelf( this.vertices[ face.c ] );
  3963. face.centroid.divideScalar( 3 );
  3964. } else if ( face instanceof THREE.Face4 ) {
  3965. face.centroid.addSelf( this.vertices[ face.a ] );
  3966. face.centroid.addSelf( this.vertices[ face.b ] );
  3967. face.centroid.addSelf( this.vertices[ face.c ] );
  3968. face.centroid.addSelf( this.vertices[ face.d ] );
  3969. face.centroid.divideScalar( 4 );
  3970. }
  3971. }
  3972. },
  3973. computeFaceNormals: function () {
  3974. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  3975. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  3976. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3977. face = this.faces[ f ];
  3978. vA = this.vertices[ face.a ];
  3979. vB = this.vertices[ face.b ];
  3980. vC = this.vertices[ face.c ];
  3981. cb.sub( vC, vB );
  3982. ab.sub( vA, vB );
  3983. cb.crossSelf( ab );
  3984. cb.normalize();
  3985. face.normal.copy( cb );
  3986. }
  3987. },
  3988. computeVertexNormals: function ( areaWeighted ) {
  3989. var v, vl, f, fl, face, vertices;
  3990. // create internal buffers for reuse when calling this method repeatedly
  3991. // (otherwise memory allocation / deallocation every frame is big resource hog)
  3992. if ( this.__tmpVertices === undefined ) {
  3993. this.__tmpVertices = new Array( this.vertices.length );
  3994. vertices = this.__tmpVertices;
  3995. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3996. vertices[ v ] = new THREE.Vector3();
  3997. }
  3998. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3999. face = this.faces[ f ];
  4000. if ( face instanceof THREE.Face3 ) {
  4001. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4002. } else if ( face instanceof THREE.Face4 ) {
  4003. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4004. }
  4005. }
  4006. } else {
  4007. vertices = this.__tmpVertices;
  4008. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4009. vertices[ v ].set( 0, 0, 0 );
  4010. }
  4011. }
  4012. if ( areaWeighted ) {
  4013. // vertex normals weighted by triangle areas
  4014. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4015. var vA, vB, vC, vD;
  4016. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4017. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4018. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4019. face = this.faces[ f ];
  4020. if ( face instanceof THREE.Face3 ) {
  4021. vA = this.vertices[ face.a ];
  4022. vB = this.vertices[ face.b ];
  4023. vC = this.vertices[ face.c ];
  4024. cb.sub( vC, vB );
  4025. ab.sub( vA, vB );
  4026. cb.crossSelf( ab );
  4027. vertices[ face.a ].addSelf( cb );
  4028. vertices[ face.b ].addSelf( cb );
  4029. vertices[ face.c ].addSelf( cb );
  4030. } else if ( face instanceof THREE.Face4 ) {
  4031. vA = this.vertices[ face.a ];
  4032. vB = this.vertices[ face.b ];
  4033. vC = this.vertices[ face.c ];
  4034. vD = this.vertices[ face.d ];
  4035. // abd
  4036. db.sub( vD, vB );
  4037. ab.sub( vA, vB );
  4038. db.crossSelf( ab );
  4039. vertices[ face.a ].addSelf( db );
  4040. vertices[ face.b ].addSelf( db );
  4041. vertices[ face.d ].addSelf( db );
  4042. // bcd
  4043. dc.sub( vD, vC );
  4044. bc.sub( vB, vC );
  4045. dc.crossSelf( bc );
  4046. vertices[ face.b ].addSelf( dc );
  4047. vertices[ face.c ].addSelf( dc );
  4048. vertices[ face.d ].addSelf( dc );
  4049. }
  4050. }
  4051. } else {
  4052. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4053. face = this.faces[ f ];
  4054. if ( face instanceof THREE.Face3 ) {
  4055. vertices[ face.a ].addSelf( face.normal );
  4056. vertices[ face.b ].addSelf( face.normal );
  4057. vertices[ face.c ].addSelf( face.normal );
  4058. } else if ( face instanceof THREE.Face4 ) {
  4059. vertices[ face.a ].addSelf( face.normal );
  4060. vertices[ face.b ].addSelf( face.normal );
  4061. vertices[ face.c ].addSelf( face.normal );
  4062. vertices[ face.d ].addSelf( face.normal );
  4063. }
  4064. }
  4065. }
  4066. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4067. vertices[ v ].normalize();
  4068. }
  4069. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4070. face = this.faces[ f ];
  4071. if ( face instanceof THREE.Face3 ) {
  4072. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4073. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4074. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4075. } else if ( face instanceof THREE.Face4 ) {
  4076. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4077. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4078. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4079. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4080. }
  4081. }
  4082. },
  4083. computeMorphNormals: function () {
  4084. var i, il, f, fl, face;
  4085. // save original normals
  4086. // - create temp variables on first access
  4087. // otherwise just copy (for faster repeated calls)
  4088. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4089. face = this.faces[ f ];
  4090. if ( ! face.__originalFaceNormal ) {
  4091. face.__originalFaceNormal = face.normal.clone();
  4092. } else {
  4093. face.__originalFaceNormal.copy( face.normal );
  4094. }
  4095. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4096. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4097. if ( ! face.__originalVertexNormals[ i ] ) {
  4098. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4099. } else {
  4100. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4101. }
  4102. }
  4103. }
  4104. // use temp geometry to compute face and vertex normals for each morph
  4105. var tmpGeo = new THREE.Geometry();
  4106. tmpGeo.faces = this.faces;
  4107. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4108. // create on first access
  4109. if ( ! this.morphNormals[ i ] ) {
  4110. this.morphNormals[ i ] = {};
  4111. this.morphNormals[ i ].faceNormals = [];
  4112. this.morphNormals[ i ].vertexNormals = [];
  4113. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4114. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4115. var faceNormal, vertexNormals;
  4116. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4117. face = this.faces[ f ];
  4118. faceNormal = new THREE.Vector3();
  4119. if ( face instanceof THREE.Face3 ) {
  4120. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4121. } else {
  4122. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4123. }
  4124. dstNormalsFace.push( faceNormal );
  4125. dstNormalsVertex.push( vertexNormals );
  4126. }
  4127. }
  4128. var morphNormals = this.morphNormals[ i ];
  4129. // set vertices to morph target
  4130. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4131. // compute morph normals
  4132. tmpGeo.computeFaceNormals();
  4133. tmpGeo.computeVertexNormals();
  4134. // store morph normals
  4135. var faceNormal, vertexNormals;
  4136. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4137. face = this.faces[ f ];
  4138. faceNormal = morphNormals.faceNormals[ f ];
  4139. vertexNormals = morphNormals.vertexNormals[ f ];
  4140. faceNormal.copy( face.normal );
  4141. if ( face instanceof THREE.Face3 ) {
  4142. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4143. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4144. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4145. } else {
  4146. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4147. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4148. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4149. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4150. }
  4151. }
  4152. }
  4153. // restore original normals
  4154. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4155. face = this.faces[ f ];
  4156. face.normal = face.__originalFaceNormal;
  4157. face.vertexNormals = face.__originalVertexNormals;
  4158. }
  4159. },
  4160. computeTangents: function () {
  4161. // based on http://www.terathon.com/code/tangent.html
  4162. // tangents go to vertices
  4163. var f, fl, v, vl, i, il, vertexIndex,
  4164. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4165. x1, x2, y1, y2, z1, z2,
  4166. s1, s2, t1, t2, r, t, test,
  4167. tan1 = [], tan2 = [],
  4168. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4169. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4170. n = new THREE.Vector3(), w;
  4171. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4172. tan1[ v ] = new THREE.Vector3();
  4173. tan2[ v ] = new THREE.Vector3();
  4174. }
  4175. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4176. vA = context.vertices[ a ];
  4177. vB = context.vertices[ b ];
  4178. vC = context.vertices[ c ];
  4179. uvA = uv[ ua ];
  4180. uvB = uv[ ub ];
  4181. uvC = uv[ uc ];
  4182. x1 = vB.x - vA.x;
  4183. x2 = vC.x - vA.x;
  4184. y1 = vB.y - vA.y;
  4185. y2 = vC.y - vA.y;
  4186. z1 = vB.z - vA.z;
  4187. z2 = vC.z - vA.z;
  4188. s1 = uvB.x - uvA.x;
  4189. s2 = uvC.x - uvA.x;
  4190. t1 = uvB.y - uvA.y;
  4191. t2 = uvC.y - uvA.y;
  4192. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4193. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4194. ( t2 * y1 - t1 * y2 ) * r,
  4195. ( t2 * z1 - t1 * z2 ) * r );
  4196. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4197. ( s1 * y2 - s2 * y1 ) * r,
  4198. ( s1 * z2 - s2 * z1 ) * r );
  4199. tan1[ a ].addSelf( sdir );
  4200. tan1[ b ].addSelf( sdir );
  4201. tan1[ c ].addSelf( sdir );
  4202. tan2[ a ].addSelf( tdir );
  4203. tan2[ b ].addSelf( tdir );
  4204. tan2[ c ].addSelf( tdir );
  4205. }
  4206. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4207. face = this.faces[ f ];
  4208. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4209. if ( face instanceof THREE.Face3 ) {
  4210. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4211. } else if ( face instanceof THREE.Face4 ) {
  4212. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4213. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4214. }
  4215. }
  4216. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4217. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4218. face = this.faces[ f ];
  4219. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4220. n.copy( face.vertexNormals[ i ] );
  4221. vertexIndex = face[ faceIndex[ i ] ];
  4222. t = tan1[ vertexIndex ];
  4223. // Gram-Schmidt orthogonalize
  4224. tmp.copy( t );
  4225. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4226. // Calculate handedness
  4227. tmp2.cross( face.vertexNormals[ i ], t );
  4228. test = tmp2.dot( tan2[ vertexIndex ] );
  4229. w = (test < 0.0) ? -1.0 : 1.0;
  4230. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4231. }
  4232. }
  4233. this.hasTangents = true;
  4234. },
  4235. computeLineDistances: function ( ) {
  4236. var d = 0;
  4237. var vertices = this.vertices;
  4238. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4239. if ( i > 0 ) {
  4240. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4241. }
  4242. this.lineDistances[ i ] = d;
  4243. }
  4244. },
  4245. computeBoundingBox: function () {
  4246. if ( this.boundingBox === null ) {
  4247. this.boundingBox = new THREE.Box3();
  4248. }
  4249. this.boundingBox.setFromPoints( this.vertices );
  4250. },
  4251. computeBoundingSphere: function () {
  4252. if ( this.boundingSphere === null ) {
  4253. this.boundingSphere = new THREE.Sphere();
  4254. }
  4255. this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
  4256. },
  4257. /*
  4258. * Checks for duplicate vertices with hashmap.
  4259. * Duplicated vertices are removed
  4260. * and faces' vertices are updated.
  4261. */
  4262. mergeVertices: function () {
  4263. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4264. var unique = [], changes = [];
  4265. var v, key;
  4266. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4267. var precision = Math.pow( 10, precisionPoints );
  4268. var i,il, face;
  4269. var abcd = 'abcd', o, k, j, jl, u;
  4270. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4271. v = this.vertices[ i ];
  4272. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  4273. if ( verticesMap[ key ] === undefined ) {
  4274. verticesMap[ key ] = i;
  4275. unique.push( this.vertices[ i ] );
  4276. changes[ i ] = unique.length - 1;
  4277. } else {
  4278. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4279. changes[ i ] = changes[ verticesMap[ key ] ];
  4280. }
  4281. };
  4282. // Start to patch face indices
  4283. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4284. face = this.faces[ i ];
  4285. if ( face instanceof THREE.Face3 ) {
  4286. face.a = changes[ face.a ];
  4287. face.b = changes[ face.b ];
  4288. face.c = changes[ face.c ];
  4289. } else if ( face instanceof THREE.Face4 ) {
  4290. face.a = changes[ face.a ];
  4291. face.b = changes[ face.b ];
  4292. face.c = changes[ face.c ];
  4293. face.d = changes[ face.d ];
  4294. // check dups in (a, b, c, d) and convert to -> face3
  4295. o = [ face.a, face.b, face.c, face.d ];
  4296. for ( k = 3; k > 0; k -- ) {
  4297. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  4298. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  4299. o.splice( k, 1 );
  4300. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  4301. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4302. u = this.faceVertexUvs[ j ][ i ];
  4303. if ( u ) u.splice( k, 1 );
  4304. }
  4305. this.faces[ i ].vertexColors = face.vertexColors;
  4306. break;
  4307. }
  4308. }
  4309. }
  4310. }
  4311. // Use unique set of vertices
  4312. var diff = this.vertices.length - unique.length;
  4313. this.vertices = unique;
  4314. return diff;
  4315. },
  4316. clone: function () {
  4317. var geometry = new THREE.Geometry();
  4318. var vertices = this.vertices;
  4319. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4320. geometry.vertices.push( vertices[ i ].clone() );
  4321. }
  4322. var faces = this.faces;
  4323. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4324. geometry.faces.push( faces[ i ].clone() );
  4325. }
  4326. var uvs = this.faceVertexUvs[ 0 ];
  4327. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4328. var uv = uvs[ i ], uvCopy = [];
  4329. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4330. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  4331. }
  4332. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4333. }
  4334. return geometry;
  4335. },
  4336. dispose: function () {
  4337. this.dispatchEvent( { type: 'dispose' } );
  4338. }
  4339. };
  4340. THREE.GeometryIdCount = 0;
  4341. /**
  4342. * @author alteredq / http://alteredqualia.com/
  4343. */
  4344. THREE.BufferGeometry = function () {
  4345. THREE.EventDispatcher.call( this );
  4346. this.id = THREE.GeometryIdCount ++;
  4347. // attributes
  4348. this.attributes = {};
  4349. // attributes typed arrays are kept only if dynamic flag is set
  4350. this.dynamic = false;
  4351. // offsets for chunks when using indexed elements
  4352. this.offsets = [];
  4353. // boundings
  4354. this.boundingBox = null;
  4355. this.boundingSphere = null;
  4356. this.hasTangents = false;
  4357. // for compatibility
  4358. this.morphTargets = [];
  4359. };
  4360. THREE.BufferGeometry.prototype = {
  4361. constructor : THREE.BufferGeometry,
  4362. applyMatrix: function ( matrix ) {
  4363. var positionArray;
  4364. var normalArray;
  4365. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  4366. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  4367. if ( positionArray !== undefined ) {
  4368. matrix.multiplyVector3Array( positionArray );
  4369. this.verticesNeedUpdate = true;
  4370. }
  4371. if ( normalArray !== undefined ) {
  4372. var normalMatrix = new THREE.Matrix3();
  4373. normalMatrix.getInverse( matrix ).transpose();
  4374. normalMatrix.multiplyVector3Array( normalArray );
  4375. this.normalizeNormals();
  4376. this.normalsNeedUpdate = true;
  4377. }
  4378. },
  4379. computeBoundingBox: function () {
  4380. if ( this.boundingBox === null ) {
  4381. this.boundingBox = new THREE.Box3();
  4382. }
  4383. var positions = this.attributes[ "position" ].array;
  4384. if ( positions ) {
  4385. var bb = this.boundingBox;
  4386. var x, y, z;
  4387. if( positions.length >= 3 ) {
  4388. bb.min.x = bb.max.x = positions[ 0 ];
  4389. bb.min.y = bb.max.y = positions[ 1 ];
  4390. bb.min.z = bb.max.z = positions[ 2 ];
  4391. }
  4392. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  4393. x = positions[ i ];
  4394. y = positions[ i + 1 ];
  4395. z = positions[ i + 2 ];
  4396. // bounding box
  4397. if ( x < bb.min.x ) {
  4398. bb.min.x = x;
  4399. } else if ( x > bb.max.x ) {
  4400. bb.max.x = x;
  4401. }
  4402. if ( y < bb.min.y ) {
  4403. bb.min.y = y;
  4404. } else if ( y > bb.max.y ) {
  4405. bb.max.y = y;
  4406. }
  4407. if ( z < bb.min.z ) {
  4408. bb.min.z = z;
  4409. } else if ( z > bb.max.z ) {
  4410. bb.max.z = z;
  4411. }
  4412. }
  4413. }
  4414. if ( positions === undefined || positions.length === 0 ) {
  4415. this.boundingBox.min.set( 0, 0, 0 );
  4416. this.boundingBox.max.set( 0, 0, 0 );
  4417. }
  4418. },
  4419. computeBoundingSphere: function () {
  4420. if ( this.boundingSphere === null ) {
  4421. this.boundingSphere = new THREE.Sphere();
  4422. }
  4423. var positions = this.attributes[ "position" ].array;
  4424. if ( positions ) {
  4425. var radiusSq, maxRadiusSq = 0;
  4426. var x, y, z;
  4427. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4428. x = positions[ i ];
  4429. y = positions[ i + 1 ];
  4430. z = positions[ i + 2 ];
  4431. radiusSq = x * x + y * y + z * z;
  4432. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  4433. }
  4434. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  4435. }
  4436. },
  4437. computeVertexNormals: function () {
  4438. if ( this.attributes[ "position" ] ) {
  4439. var i, il;
  4440. var j, jl;
  4441. var nVertexElements = this.attributes[ "position" ].array.length;
  4442. if ( this.attributes[ "normal" ] === undefined ) {
  4443. this.attributes[ "normal" ] = {
  4444. itemSize: 3,
  4445. array: new Float32Array( nVertexElements ),
  4446. numItems: nVertexElements
  4447. };
  4448. } else {
  4449. // reset existing normals to zero
  4450. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  4451. this.attributes[ "normal" ].array[ i ] = 0;
  4452. }
  4453. }
  4454. var positions = this.attributes[ "position" ].array;
  4455. var normals = this.attributes[ "normal" ].array;
  4456. var vA, vB, vC, x, y, z,
  4457. pA = new THREE.Vector3(),
  4458. pB = new THREE.Vector3(),
  4459. pC = new THREE.Vector3(),
  4460. cb = new THREE.Vector3(),
  4461. ab = new THREE.Vector3();
  4462. // indexed elements
  4463. if ( this.attributes[ "index" ] ) {
  4464. var indices = this.attributes[ "index" ].array;
  4465. var offsets = this.offsets;
  4466. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4467. var start = offsets[ j ].start;
  4468. var count = offsets[ j ].count;
  4469. var index = offsets[ j ].index;
  4470. for ( i = start, il = start + count; i < il; i += 3 ) {
  4471. vA = index + indices[ i ];
  4472. vB = index + indices[ i + 1 ];
  4473. vC = index + indices[ i + 2 ];
  4474. x = positions[ vA * 3 ];
  4475. y = positions[ vA * 3 + 1 ];
  4476. z = positions[ vA * 3 + 2 ];
  4477. pA.set( x, y, z );
  4478. x = positions[ vB * 3 ];
  4479. y = positions[ vB * 3 + 1 ];
  4480. z = positions[ vB * 3 + 2 ];
  4481. pB.set( x, y, z );
  4482. x = positions[ vC * 3 ];
  4483. y = positions[ vC * 3 + 1 ];
  4484. z = positions[ vC * 3 + 2 ];
  4485. pC.set( x, y, z );
  4486. cb.sub( pC, pB );
  4487. ab.sub( pA, pB );
  4488. cb.crossSelf( ab );
  4489. normals[ vA * 3 ] += cb.x;
  4490. normals[ vA * 3 + 1 ] += cb.y;
  4491. normals[ vA * 3 + 2 ] += cb.z;
  4492. normals[ vB * 3 ] += cb.x;
  4493. normals[ vB * 3 + 1 ] += cb.y;
  4494. normals[ vB * 3 + 2 ] += cb.z;
  4495. normals[ vC * 3 ] += cb.x;
  4496. normals[ vC * 3 + 1 ] += cb.y;
  4497. normals[ vC * 3 + 2 ] += cb.z;
  4498. }
  4499. }
  4500. // non-indexed elements (unconnected triangle soup)
  4501. } else {
  4502. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  4503. x = positions[ i ];
  4504. y = positions[ i + 1 ];
  4505. z = positions[ i + 2 ];
  4506. pA.set( x, y, z );
  4507. x = positions[ i + 3 ];
  4508. y = positions[ i + 4 ];
  4509. z = positions[ i + 5 ];
  4510. pB.set( x, y, z );
  4511. x = positions[ i + 6 ];
  4512. y = positions[ i + 7 ];
  4513. z = positions[ i + 8 ];
  4514. pC.set( x, y, z );
  4515. cb.sub( pC, pB );
  4516. ab.sub( pA, pB );
  4517. cb.crossSelf( ab );
  4518. normals[ i ] = cb.x;
  4519. normals[ i + 1 ] = cb.y;
  4520. normals[ i + 2 ] = cb.z;
  4521. normals[ i + 3 ] = cb.x;
  4522. normals[ i + 4 ] = cb.y;
  4523. normals[ i + 5 ] = cb.z;
  4524. normals[ i + 6 ] = cb.x;
  4525. normals[ i + 7 ] = cb.y;
  4526. normals[ i + 8 ] = cb.z;
  4527. }
  4528. }
  4529. this.normalizeNormals();
  4530. this.normalsNeedUpdate = true;
  4531. }
  4532. },
  4533. normalizeNormals: function () {
  4534. var normals = this.attributes[ "normal" ].array;
  4535. var x, y, z, n;
  4536. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  4537. x = normals[ i ];
  4538. y = normals[ i + 1 ];
  4539. z = normals[ i + 2 ];
  4540. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  4541. normals[ i ] *= n;
  4542. normals[ i + 1 ] *= n;
  4543. normals[ i + 2 ] *= n;
  4544. }
  4545. },
  4546. computeTangents: function () {
  4547. // based on http://www.terathon.com/code/tangent.html
  4548. // (per vertex tangents)
  4549. if ( this.attributes[ "index" ] === undefined ||
  4550. this.attributes[ "position" ] === undefined ||
  4551. this.attributes[ "normal" ] === undefined ||
  4552. this.attributes[ "uv" ] === undefined ) {
  4553. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  4554. return;
  4555. }
  4556. var indices = this.attributes[ "index" ].array;
  4557. var positions = this.attributes[ "position" ].array;
  4558. var normals = this.attributes[ "normal" ].array;
  4559. var uvs = this.attributes[ "uv" ].array;
  4560. var nVertices = positions.length / 3;
  4561. if ( this.attributes[ "tangent" ] === undefined ) {
  4562. var nTangentElements = 4 * nVertices;
  4563. this.attributes[ "tangent" ] = {
  4564. itemSize: 4,
  4565. array: new Float32Array( nTangentElements ),
  4566. numItems: nTangentElements
  4567. };
  4568. }
  4569. var tangents = this.attributes[ "tangent" ].array;
  4570. var tan1 = [], tan2 = [];
  4571. for ( var k = 0; k < nVertices; k ++ ) {
  4572. tan1[ k ] = new THREE.Vector3();
  4573. tan2[ k ] = new THREE.Vector3();
  4574. }
  4575. var xA, yA, zA,
  4576. xB, yB, zB,
  4577. xC, yC, zC,
  4578. uA, vA,
  4579. uB, vB,
  4580. uC, vC,
  4581. x1, x2, y1, y2, z1, z2,
  4582. s1, s2, t1, t2, r;
  4583. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  4584. function handleTriangle( a, b, c ) {
  4585. xA = positions[ a * 3 ];
  4586. yA = positions[ a * 3 + 1 ];
  4587. zA = positions[ a * 3 + 2 ];
  4588. xB = positions[ b * 3 ];
  4589. yB = positions[ b * 3 + 1 ];
  4590. zB = positions[ b * 3 + 2 ];
  4591. xC = positions[ c * 3 ];
  4592. yC = positions[ c * 3 + 1 ];
  4593. zC = positions[ c * 3 + 2 ];
  4594. uA = uvs[ a * 2 ];
  4595. vA = uvs[ a * 2 + 1 ];
  4596. uB = uvs[ b * 2 ];
  4597. vB = uvs[ b * 2 + 1 ];
  4598. uC = uvs[ c * 2 ];
  4599. vC = uvs[ c * 2 + 1 ];
  4600. x1 = xB - xA;
  4601. x2 = xC - xA;
  4602. y1 = yB - yA;
  4603. y2 = yC - yA;
  4604. z1 = zB - zA;
  4605. z2 = zC - zA;
  4606. s1 = uB - uA;
  4607. s2 = uC - uA;
  4608. t1 = vB - vA;
  4609. t2 = vC - vA;
  4610. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4611. sdir.set(
  4612. ( t2 * x1 - t1 * x2 ) * r,
  4613. ( t2 * y1 - t1 * y2 ) * r,
  4614. ( t2 * z1 - t1 * z2 ) * r
  4615. );
  4616. tdir.set(
  4617. ( s1 * x2 - s2 * x1 ) * r,
  4618. ( s1 * y2 - s2 * y1 ) * r,
  4619. ( s1 * z2 - s2 * z1 ) * r
  4620. );
  4621. tan1[ a ].addSelf( sdir );
  4622. tan1[ b ].addSelf( sdir );
  4623. tan1[ c ].addSelf( sdir );
  4624. tan2[ a ].addSelf( tdir );
  4625. tan2[ b ].addSelf( tdir );
  4626. tan2[ c ].addSelf( tdir );
  4627. }
  4628. var i, il;
  4629. var j, jl;
  4630. var iA, iB, iC;
  4631. var offsets = this.offsets;
  4632. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4633. var start = offsets[ j ].start;
  4634. var count = offsets[ j ].count;
  4635. var index = offsets[ j ].index;
  4636. for ( i = start, il = start + count; i < il; i += 3 ) {
  4637. iA = index + indices[ i ];
  4638. iB = index + indices[ i + 1 ];
  4639. iC = index + indices[ i + 2 ];
  4640. handleTriangle( iA, iB, iC );
  4641. }
  4642. }
  4643. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  4644. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  4645. var w, t, test;
  4646. var nx, ny, nz;
  4647. function handleVertex( v ) {
  4648. n.x = normals[ v * 3 ];
  4649. n.y = normals[ v * 3 + 1 ];
  4650. n.z = normals[ v * 3 + 2 ];
  4651. n2.copy( n );
  4652. t = tan1[ v ];
  4653. // Gram-Schmidt orthogonalize
  4654. tmp.copy( t );
  4655. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4656. // Calculate handedness
  4657. tmp2.cross( n2, t );
  4658. test = tmp2.dot( tan2[ v ] );
  4659. w = ( test < 0.0 ) ? -1.0 : 1.0;
  4660. tangents[ v * 4 ] = tmp.x;
  4661. tangents[ v * 4 + 1 ] = tmp.y;
  4662. tangents[ v * 4 + 2 ] = tmp.z;
  4663. tangents[ v * 4 + 3 ] = w;
  4664. }
  4665. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4666. var start = offsets[ j ].start;
  4667. var count = offsets[ j ].count;
  4668. var index = offsets[ j ].index;
  4669. for ( i = start, il = start + count; i < il; i += 3 ) {
  4670. iA = index + indices[ i ];
  4671. iB = index + indices[ i + 1 ];
  4672. iC = index + indices[ i + 2 ];
  4673. handleVertex( iA );
  4674. handleVertex( iB );
  4675. handleVertex( iC );
  4676. }
  4677. }
  4678. this.hasTangents = true;
  4679. this.tangentsNeedUpdate = true;
  4680. },
  4681. dispose: function () {
  4682. this.dispatchEvent( { type: 'dispose' } );
  4683. }
  4684. };
  4685. /**
  4686. * @author mrdoob / http://mrdoob.com/
  4687. * @author mikael emtinger / http://gomo.se/
  4688. */
  4689. THREE.Camera = function () {
  4690. THREE.Object3D.call( this );
  4691. this.matrixWorldInverse = new THREE.Matrix4();
  4692. this.projectionMatrix = new THREE.Matrix4();
  4693. this.projectionMatrixInverse = new THREE.Matrix4();
  4694. };
  4695. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  4696. THREE.Camera.prototype.lookAt = function ( vector ) {
  4697. // TODO: Add hierarchy support.
  4698. this.matrix.lookAt( this.position, vector, this.up );
  4699. if ( this.rotationAutoUpdate === true ) {
  4700. if ( this.useQuaternion === false ) {
  4701. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  4702. } else {
  4703. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  4704. }
  4705. }
  4706. };
  4707. /**
  4708. * @author alteredq / http://alteredqualia.com/
  4709. */
  4710. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  4711. THREE.Camera.call( this );
  4712. this.left = left;
  4713. this.right = right;
  4714. this.top = top;
  4715. this.bottom = bottom;
  4716. this.near = ( near !== undefined ) ? near : 0.1;
  4717. this.far = ( far !== undefined ) ? far : 2000;
  4718. this.updateProjectionMatrix();
  4719. };
  4720. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  4721. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  4722. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  4723. };
  4724. /**
  4725. * @author mrdoob / http://mrdoob.com/
  4726. * @author greggman / http://games.greggman.com/
  4727. * @author zz85 / http://www.lab4games.net/zz85/blog
  4728. */
  4729. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  4730. THREE.Camera.call( this );
  4731. this.fov = fov !== undefined ? fov : 50;
  4732. this.aspect = aspect !== undefined ? aspect : 1;
  4733. this.near = near !== undefined ? near : 0.1;
  4734. this.far = far !== undefined ? far : 2000;
  4735. this.updateProjectionMatrix();
  4736. };
  4737. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  4738. /**
  4739. * Uses Focal Length (in mm) to estimate and set FOV
  4740. * 35mm (fullframe) camera is used if frame size is not specified;
  4741. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  4742. */
  4743. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  4744. if ( frameHeight === undefined ) frameHeight = 24;
  4745. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  4746. this.updateProjectionMatrix();
  4747. }
  4748. /**
  4749. * Sets an offset in a larger frustum. This is useful for multi-window or
  4750. * multi-monitor/multi-machine setups.
  4751. *
  4752. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  4753. * the monitors are in grid like this
  4754. *
  4755. * +---+---+---+
  4756. * | A | B | C |
  4757. * +---+---+---+
  4758. * | D | E | F |
  4759. * +---+---+---+
  4760. *
  4761. * then for each monitor you would call it like this
  4762. *
  4763. * var w = 1920;
  4764. * var h = 1080;
  4765. * var fullWidth = w * 3;
  4766. * var fullHeight = h * 2;
  4767. *
  4768. * --A--
  4769. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  4770. * --B--
  4771. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  4772. * --C--
  4773. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  4774. * --D--
  4775. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  4776. * --E--
  4777. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  4778. * --F--
  4779. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  4780. *
  4781. * Note there is no reason monitors have to be the same size or in a grid.
  4782. */
  4783. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  4784. this.fullWidth = fullWidth;
  4785. this.fullHeight = fullHeight;
  4786. this.x = x;
  4787. this.y = y;
  4788. this.width = width;
  4789. this.height = height;
  4790. this.updateProjectionMatrix();
  4791. };
  4792. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  4793. if ( this.fullWidth ) {
  4794. var aspect = this.fullWidth / this.fullHeight;
  4795. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  4796. var bottom = -top;
  4797. var left = aspect * bottom;
  4798. var right = aspect * top;
  4799. var width = Math.abs( right - left );
  4800. var height = Math.abs( top - bottom );
  4801. this.projectionMatrix.makeFrustum(
  4802. left + this.x * width / this.fullWidth,
  4803. left + ( this.x + this.width ) * width / this.fullWidth,
  4804. top - ( this.y + this.height ) * height / this.fullHeight,
  4805. top - this.y * height / this.fullHeight,
  4806. this.near,
  4807. this.far
  4808. );
  4809. } else {
  4810. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  4811. }
  4812. };
  4813. /**
  4814. * @author mrdoob / http://mrdoob.com/
  4815. * @author alteredq / http://alteredqualia.com/
  4816. */
  4817. THREE.Light = function ( hex ) {
  4818. THREE.Object3D.call( this );
  4819. this.color = new THREE.Color( hex );
  4820. };
  4821. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  4822. /**
  4823. * @author mrdoob / http://mrdoob.com/
  4824. */
  4825. THREE.AmbientLight = function ( hex ) {
  4826. THREE.Light.call( this, hex );
  4827. };
  4828. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  4829. /**
  4830. * @author mrdoob / http://mrdoob.com/
  4831. * @author alteredq / http://alteredqualia.com/
  4832. */
  4833. THREE.DirectionalLight = function ( hex, intensity ) {
  4834. THREE.Light.call( this, hex );
  4835. this.position = new THREE.Vector3( 0, 1, 0 );
  4836. this.target = new THREE.Object3D();
  4837. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4838. this.castShadow = false;
  4839. this.onlyShadow = false;
  4840. //
  4841. this.shadowCameraNear = 50;
  4842. this.shadowCameraFar = 5000;
  4843. this.shadowCameraLeft = -500;
  4844. this.shadowCameraRight = 500;
  4845. this.shadowCameraTop = 500;
  4846. this.shadowCameraBottom = -500;
  4847. this.shadowCameraVisible = false;
  4848. this.shadowBias = 0;
  4849. this.shadowDarkness = 0.5;
  4850. this.shadowMapWidth = 512;
  4851. this.shadowMapHeight = 512;
  4852. //
  4853. this.shadowCascade = false;
  4854. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  4855. this.shadowCascadeCount = 2;
  4856. this.shadowCascadeBias = [ 0, 0, 0 ];
  4857. this.shadowCascadeWidth = [ 512, 512, 512 ];
  4858. this.shadowCascadeHeight = [ 512, 512, 512 ];
  4859. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  4860. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  4861. this.shadowCascadeArray = [];
  4862. //
  4863. this.shadowMap = null;
  4864. this.shadowMapSize = null;
  4865. this.shadowCamera = null;
  4866. this.shadowMatrix = null;
  4867. };
  4868. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  4869. /**
  4870. * @author alteredq / http://alteredqualia.com/
  4871. */
  4872. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  4873. THREE.Light.call( this, skyColorHex );
  4874. this.groundColor = new THREE.Color( groundColorHex );
  4875. this.position = new THREE.Vector3( 0, 100, 0 );
  4876. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4877. };
  4878. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  4879. /**
  4880. * @author mrdoob / http://mrdoob.com/
  4881. */
  4882. THREE.PointLight = function ( hex, intensity, distance ) {
  4883. THREE.Light.call( this, hex );
  4884. this.position = new THREE.Vector3( 0, 0, 0 );
  4885. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4886. this.distance = ( distance !== undefined ) ? distance : 0;
  4887. };
  4888. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  4889. /**
  4890. * @author alteredq / http://alteredqualia.com/
  4891. */
  4892. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  4893. THREE.Light.call( this, hex );
  4894. this.position = new THREE.Vector3( 0, 1, 0 );
  4895. this.target = new THREE.Object3D();
  4896. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4897. this.distance = ( distance !== undefined ) ? distance : 0;
  4898. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  4899. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  4900. this.castShadow = false;
  4901. this.onlyShadow = false;
  4902. //
  4903. this.shadowCameraNear = 50;
  4904. this.shadowCameraFar = 5000;
  4905. this.shadowCameraFov = 50;
  4906. this.shadowCameraVisible = false;
  4907. this.shadowBias = 0;
  4908. this.shadowDarkness = 0.5;
  4909. this.shadowMapWidth = 512;
  4910. this.shadowMapHeight = 512;
  4911. //
  4912. this.shadowMap = null;
  4913. this.shadowMapSize = null;
  4914. this.shadowCamera = null;
  4915. this.shadowMatrix = null;
  4916. };
  4917. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  4918. /**
  4919. * @author alteredq / http://alteredqualia.com/
  4920. */
  4921. THREE.Loader = function ( showStatus ) {
  4922. this.showStatus = showStatus;
  4923. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  4924. this.onLoadStart = function () {};
  4925. this.onLoadProgress = function () {};
  4926. this.onLoadComplete = function () {};
  4927. };
  4928. THREE.Loader.prototype = {
  4929. constructor: THREE.Loader,
  4930. crossOrigin: 'anonymous',
  4931. addStatusElement: function () {
  4932. var e = document.createElement( "div" );
  4933. e.style.position = "absolute";
  4934. e.style.right = "0px";
  4935. e.style.top = "0px";
  4936. e.style.fontSize = "0.8em";
  4937. e.style.textAlign = "left";
  4938. e.style.background = "rgba(0,0,0,0.25)";
  4939. e.style.color = "#fff";
  4940. e.style.width = "120px";
  4941. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  4942. e.style.zIndex = 1000;
  4943. e.innerHTML = "Loading ...";
  4944. return e;
  4945. },
  4946. updateProgress: function ( progress ) {
  4947. var message = "Loaded ";
  4948. if ( progress.total ) {
  4949. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  4950. } else {
  4951. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  4952. }
  4953. this.statusDomElement.innerHTML = message;
  4954. },
  4955. extractUrlBase: function ( url ) {
  4956. var parts = url.split( '/' );
  4957. parts.pop();
  4958. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  4959. },
  4960. initMaterials: function ( materials, texturePath ) {
  4961. var array = [];
  4962. for ( var i = 0; i < materials.length; ++ i ) {
  4963. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  4964. }
  4965. return array;
  4966. },
  4967. needsTangents: function ( materials ) {
  4968. for( var i = 0, il = materials.length; i < il; i ++ ) {
  4969. var m = materials[ i ];
  4970. if ( m instanceof THREE.ShaderMaterial ) return true;
  4971. }
  4972. return false;
  4973. },
  4974. createMaterial: function ( m, texturePath ) {
  4975. var _this = this;
  4976. function is_pow2( n ) {
  4977. var l = Math.log( n ) / Math.LN2;
  4978. return Math.floor( l ) == l;
  4979. }
  4980. function nearest_pow2( n ) {
  4981. var l = Math.log( n ) / Math.LN2;
  4982. return Math.pow( 2, Math.round( l ) );
  4983. }
  4984. function load_image( where, url ) {
  4985. var image = new Image();
  4986. image.onload = function () {
  4987. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  4988. var width = nearest_pow2( this.width );
  4989. var height = nearest_pow2( this.height );
  4990. where.image.width = width;
  4991. where.image.height = height;
  4992. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  4993. } else {
  4994. where.image = this;
  4995. }
  4996. where.needsUpdate = true;
  4997. };
  4998. image.crossOrigin = _this.crossOrigin;
  4999. image.src = url;
  5000. }
  5001. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5002. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  5003. var fullPath = texturePath + "/" + sourceFile;
  5004. if ( isCompressed ) {
  5005. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5006. where[ name ] = texture;
  5007. } else {
  5008. var texture = document.createElement( 'canvas' );
  5009. where[ name ] = new THREE.Texture( texture );
  5010. }
  5011. where[ name ].sourceFile = sourceFile;
  5012. if( repeat ) {
  5013. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5014. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5015. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5016. }
  5017. if ( offset ) {
  5018. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5019. }
  5020. if ( wrap ) {
  5021. var wrapMap = {
  5022. "repeat": THREE.RepeatWrapping,
  5023. "mirror": THREE.MirroredRepeatWrapping
  5024. }
  5025. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5026. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5027. }
  5028. if ( anisotropy ) {
  5029. where[ name ].anisotropy = anisotropy;
  5030. }
  5031. if ( ! isCompressed ) {
  5032. load_image( where[ name ], fullPath );
  5033. }
  5034. }
  5035. function rgb2hex( rgb ) {
  5036. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5037. }
  5038. // defaults
  5039. var mtype = "MeshLambertMaterial";
  5040. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5041. // parameters from model file
  5042. if ( m.shading ) {
  5043. var shading = m.shading.toLowerCase();
  5044. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5045. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5046. }
  5047. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5048. mpars.blending = THREE[ m.blending ];
  5049. }
  5050. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5051. mpars.transparent = m.transparent;
  5052. }
  5053. if ( m.depthTest !== undefined ) {
  5054. mpars.depthTest = m.depthTest;
  5055. }
  5056. if ( m.depthWrite !== undefined ) {
  5057. mpars.depthWrite = m.depthWrite;
  5058. }
  5059. if ( m.visible !== undefined ) {
  5060. mpars.visible = m.visible;
  5061. }
  5062. if ( m.flipSided !== undefined ) {
  5063. mpars.side = THREE.BackSide;
  5064. }
  5065. if ( m.doubleSided !== undefined ) {
  5066. mpars.side = THREE.DoubleSide;
  5067. }
  5068. if ( m.wireframe !== undefined ) {
  5069. mpars.wireframe = m.wireframe;
  5070. }
  5071. if ( m.vertexColors !== undefined ) {
  5072. if ( m.vertexColors === "face" ) {
  5073. mpars.vertexColors = THREE.FaceColors;
  5074. } else if ( m.vertexColors ) {
  5075. mpars.vertexColors = THREE.VertexColors;
  5076. }
  5077. }
  5078. // colors
  5079. if ( m.colorDiffuse ) {
  5080. mpars.color = rgb2hex( m.colorDiffuse );
  5081. } else if ( m.DbgColor ) {
  5082. mpars.color = m.DbgColor;
  5083. }
  5084. if ( m.colorSpecular ) {
  5085. mpars.specular = rgb2hex( m.colorSpecular );
  5086. }
  5087. if ( m.colorAmbient ) {
  5088. mpars.ambient = rgb2hex( m.colorAmbient );
  5089. }
  5090. // modifiers
  5091. if ( m.transparency ) {
  5092. mpars.opacity = m.transparency;
  5093. }
  5094. if ( m.specularCoef ) {
  5095. mpars.shininess = m.specularCoef;
  5096. }
  5097. // textures
  5098. if ( m.mapDiffuse && texturePath ) {
  5099. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5100. }
  5101. if ( m.mapLight && texturePath ) {
  5102. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5103. }
  5104. if ( m.mapBump && texturePath ) {
  5105. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5106. }
  5107. if ( m.mapNormal && texturePath ) {
  5108. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5109. }
  5110. if ( m.mapSpecular && texturePath ) {
  5111. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5112. }
  5113. //
  5114. if ( m.mapBumpScale ) {
  5115. mpars.bumpScale = m.mapBumpScale;
  5116. }
  5117. // special case for normal mapped material
  5118. if ( m.mapNormal ) {
  5119. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5120. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5121. uniforms[ "tNormal" ].value = mpars.normalMap;
  5122. if ( m.mapNormalFactor ) {
  5123. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5124. }
  5125. if ( mpars.map ) {
  5126. uniforms[ "tDiffuse" ].value = mpars.map;
  5127. uniforms[ "enableDiffuse" ].value = true;
  5128. }
  5129. if ( mpars.specularMap ) {
  5130. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5131. uniforms[ "enableSpecular" ].value = true;
  5132. }
  5133. if ( mpars.lightMap ) {
  5134. uniforms[ "tAO" ].value = mpars.lightMap;
  5135. uniforms[ "enableAO" ].value = true;
  5136. }
  5137. // for the moment don't handle displacement texture
  5138. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5139. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5140. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5141. uniforms[ "uShininess" ].value = mpars.shininess;
  5142. if ( mpars.opacity !== undefined ) {
  5143. uniforms[ "uOpacity" ].value = mpars.opacity;
  5144. }
  5145. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5146. var material = new THREE.ShaderMaterial( parameters );
  5147. if ( mpars.transparent ) {
  5148. material.transparent = true;
  5149. }
  5150. } else {
  5151. var material = new THREE[ mtype ]( mpars );
  5152. }
  5153. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5154. return material;
  5155. }
  5156. };
  5157. /**
  5158. * @author alteredq / http://alteredqualia.com/
  5159. */
  5160. THREE.BinaryLoader = function ( showStatus ) {
  5161. THREE.Loader.call( this, showStatus );
  5162. };
  5163. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  5164. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  5165. // - binary models consist of two files: JS and BIN
  5166. // - parameters
  5167. // - url (required)
  5168. // - callback (required)
  5169. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  5170. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  5171. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  5172. // todo: unify load API to for easier SceneLoader use
  5173. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5174. binaryPath = binaryPath && ( typeof binaryPath === "string" ) ? binaryPath : this.extractUrlBase( url );
  5175. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  5176. this.onLoadStart();
  5177. // #1 load JS part via web worker
  5178. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  5179. };
  5180. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  5181. var xhr = new XMLHttpRequest();
  5182. xhr.onreadystatechange = function () {
  5183. if ( xhr.readyState == 4 ) {
  5184. if ( xhr.status == 200 || xhr.status == 0 ) {
  5185. var json = JSON.parse( xhr.responseText );
  5186. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  5187. } else {
  5188. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5189. }
  5190. }
  5191. };
  5192. xhr.open( "GET", url, true );
  5193. xhr.send( null );
  5194. };
  5195. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  5196. var xhr = new XMLHttpRequest(),
  5197. url = binaryPath + "/" + json.buffers;
  5198. var length = 0;
  5199. xhr.onreadystatechange = function () {
  5200. if ( xhr.readyState == 4 ) {
  5201. if ( xhr.status == 200 || xhr.status == 0 ) {
  5202. var buffer = xhr.response;
  5203. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  5204. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  5205. } else {
  5206. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5207. }
  5208. } else if ( xhr.readyState == 3 ) {
  5209. if ( callbackProgress ) {
  5210. if ( length == 0 ) {
  5211. length = xhr.getResponseHeader( "Content-Length" );
  5212. }
  5213. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5214. }
  5215. } else if ( xhr.readyState == 2 ) {
  5216. length = xhr.getResponseHeader( "Content-Length" );
  5217. }
  5218. };
  5219. xhr.open( "GET", url, true );
  5220. xhr.responseType = "arraybuffer";
  5221. xhr.send( null );
  5222. };
  5223. // Binary AJAX parser
  5224. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, jsonMaterials ) {
  5225. var Model = function ( texturePath ) {
  5226. var scope = this,
  5227. currentOffset = 0,
  5228. md,
  5229. normals = [],
  5230. uvs = [],
  5231. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  5232. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  5233. tri_size, quad_size,
  5234. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  5235. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  5236. THREE.Geometry.call( this );
  5237. md = parseMetaData( data, currentOffset );
  5238. currentOffset += md.header_bytes;
  5239. /*
  5240. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  5241. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  5242. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  5243. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  5244. */
  5245. // buffers sizes
  5246. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  5247. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  5248. len_tri_flat = md.ntri_flat * ( tri_size );
  5249. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  5250. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  5251. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  5252. len_quad_flat = md.nquad_flat * ( quad_size );
  5253. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  5254. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  5255. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  5256. // read buffers
  5257. currentOffset += init_vertices( currentOffset );
  5258. currentOffset += init_normals( currentOffset );
  5259. currentOffset += handlePadding( md.nnormals * 3 );
  5260. currentOffset += init_uvs( currentOffset );
  5261. start_tri_flat = currentOffset;
  5262. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  5263. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  5264. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  5265. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  5266. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  5267. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  5268. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  5269. // have to first process faces with uvs
  5270. // so that face and uv indices match
  5271. init_triangles_flat_uv( start_tri_flat_uv );
  5272. init_triangles_smooth_uv( start_tri_smooth_uv );
  5273. init_quads_flat_uv( start_quad_flat_uv );
  5274. init_quads_smooth_uv( start_quad_smooth_uv );
  5275. // now we can process untextured faces
  5276. init_triangles_flat( start_tri_flat );
  5277. init_triangles_smooth( start_tri_smooth );
  5278. init_quads_flat( start_quad_flat );
  5279. init_quads_smooth( start_quad_smooth );
  5280. this.computeCentroids();
  5281. this.computeFaceNormals();
  5282. function handlePadding( n ) {
  5283. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  5284. };
  5285. function parseMetaData( data, offset ) {
  5286. var metaData = {
  5287. 'signature' :parseString( data, offset, 12 ),
  5288. 'header_bytes' :parseUChar8( data, offset + 12 ),
  5289. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  5290. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  5291. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  5292. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  5293. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  5294. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  5295. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  5296. 'nvertices' :parseUInt32( data, offset + 20 ),
  5297. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  5298. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  5299. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  5300. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  5301. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  5302. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  5303. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  5304. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  5305. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  5306. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  5307. };
  5308. /*
  5309. console.log( "signature: " + metaData.signature );
  5310. console.log( "header_bytes: " + metaData.header_bytes );
  5311. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  5312. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  5313. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  5314. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  5315. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  5316. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  5317. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  5318. console.log( "nvertices: " + metaData.nvertices );
  5319. console.log( "nnormals: " + metaData.nnormals );
  5320. console.log( "nuvs: " + metaData.nuvs );
  5321. console.log( "ntri_flat: " + metaData.ntri_flat );
  5322. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  5323. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  5324. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  5325. console.log( "nquad_flat: " + metaData.nquad_flat );
  5326. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  5327. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  5328. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  5329. var total = metaData.header_bytes
  5330. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  5331. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  5332. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  5333. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  5334. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  5335. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  5336. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  5337. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  5338. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  5339. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  5340. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  5341. console.log( "total bytes: " + total );
  5342. */
  5343. return metaData;
  5344. };
  5345. function parseString( data, offset, length ) {
  5346. var charArray = new Uint8Array( data, offset, length );
  5347. var text = "";
  5348. for ( var i = 0; i < length; i ++ ) {
  5349. text += String.fromCharCode( charArray[ offset + i ] );
  5350. }
  5351. return text;
  5352. };
  5353. function parseUChar8( data, offset ) {
  5354. var charArray = new Uint8Array( data, offset, 1 );
  5355. return charArray[ 0 ];
  5356. };
  5357. function parseUInt32( data, offset ) {
  5358. var intArray = new Uint32Array( data, offset, 1 );
  5359. return intArray[ 0 ];
  5360. };
  5361. function init_vertices( start ) {
  5362. var nElements = md.nvertices;
  5363. var coordArray = new Float32Array( data, start, nElements * 3 );
  5364. var i, x, y, z;
  5365. for( i = 0; i < nElements; i ++ ) {
  5366. x = coordArray[ i * 3 ];
  5367. y = coordArray[ i * 3 + 1 ];
  5368. z = coordArray[ i * 3 + 2 ];
  5369. vertex( scope, x, y, z );
  5370. }
  5371. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  5372. };
  5373. function init_normals( start ) {
  5374. var nElements = md.nnormals;
  5375. if ( nElements ) {
  5376. var normalArray = new Int8Array( data, start, nElements * 3 );
  5377. var i, x, y, z;
  5378. for( i = 0; i < nElements; i ++ ) {
  5379. x = normalArray[ i * 3 ];
  5380. y = normalArray[ i * 3 + 1 ];
  5381. z = normalArray[ i * 3 + 2 ];
  5382. normals.push( x/127, y/127, z/127 );
  5383. }
  5384. }
  5385. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  5386. };
  5387. function init_uvs( start ) {
  5388. var nElements = md.nuvs;
  5389. if ( nElements ) {
  5390. var uvArray = new Float32Array( data, start, nElements * 2 );
  5391. var i, u, v;
  5392. for( i = 0; i < nElements; i ++ ) {
  5393. u = uvArray[ i * 2 ];
  5394. v = uvArray[ i * 2 + 1 ];
  5395. uvs.push( u, v );
  5396. }
  5397. }
  5398. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  5399. };
  5400. function init_uvs3( nElements, offset ) {
  5401. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  5402. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  5403. for( i = 0; i < nElements; i ++ ) {
  5404. uva = uvIndexBuffer[ i * 3 ];
  5405. uvb = uvIndexBuffer[ i * 3 + 1 ];
  5406. uvc = uvIndexBuffer[ i * 3 + 2 ];
  5407. u1 = uvs[ uva*2 ];
  5408. v1 = uvs[ uva*2 + 1 ];
  5409. u2 = uvs[ uvb*2 ];
  5410. v2 = uvs[ uvb*2 + 1 ];
  5411. u3 = uvs[ uvc*2 ];
  5412. v3 = uvs[ uvc*2 + 1 ];
  5413. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  5414. }
  5415. };
  5416. function init_uvs4( nElements, offset ) {
  5417. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  5418. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  5419. for( i = 0; i < nElements; i ++ ) {
  5420. uva = uvIndexBuffer[ i * 4 ];
  5421. uvb = uvIndexBuffer[ i * 4 + 1 ];
  5422. uvc = uvIndexBuffer[ i * 4 + 2 ];
  5423. uvd = uvIndexBuffer[ i * 4 + 3 ];
  5424. u1 = uvs[ uva*2 ];
  5425. v1 = uvs[ uva*2 + 1 ];
  5426. u2 = uvs[ uvb*2 ];
  5427. v2 = uvs[ uvb*2 + 1 ];
  5428. u3 = uvs[ uvc*2 ];
  5429. v3 = uvs[ uvc*2 + 1 ];
  5430. u4 = uvs[ uvd*2 ];
  5431. v4 = uvs[ uvd*2 + 1 ];
  5432. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  5433. }
  5434. };
  5435. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  5436. var i, a, b, c, m;
  5437. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  5438. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5439. for( i = 0; i < nElements; i ++ ) {
  5440. a = vertexIndexBuffer[ i * 3 ];
  5441. b = vertexIndexBuffer[ i * 3 + 1 ];
  5442. c = vertexIndexBuffer[ i * 3 + 2 ];
  5443. m = materialIndexBuffer[ i ];
  5444. f3( scope, a, b, c, m );
  5445. }
  5446. };
  5447. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  5448. var i, a, b, c, d, m;
  5449. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  5450. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5451. for( i = 0; i < nElements; i ++ ) {
  5452. a = vertexIndexBuffer[ i * 4 ];
  5453. b = vertexIndexBuffer[ i * 4 + 1 ];
  5454. c = vertexIndexBuffer[ i * 4 + 2 ];
  5455. d = vertexIndexBuffer[ i * 4 + 3 ];
  5456. m = materialIndexBuffer[ i ];
  5457. f4( scope, a, b, c, d, m );
  5458. }
  5459. };
  5460. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  5461. var i, a, b, c, m;
  5462. var na, nb, nc;
  5463. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  5464. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  5465. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5466. for( i = 0; i < nElements; i ++ ) {
  5467. a = vertexIndexBuffer[ i * 3 ];
  5468. b = vertexIndexBuffer[ i * 3 + 1 ];
  5469. c = vertexIndexBuffer[ i * 3 + 2 ];
  5470. na = normalIndexBuffer[ i * 3 ];
  5471. nb = normalIndexBuffer[ i * 3 + 1 ];
  5472. nc = normalIndexBuffer[ i * 3 + 2 ];
  5473. m = materialIndexBuffer[ i ];
  5474. f3n( scope, normals, a, b, c, m, na, nb, nc );
  5475. }
  5476. };
  5477. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  5478. var i, a, b, c, d, m;
  5479. var na, nb, nc, nd;
  5480. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  5481. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  5482. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5483. for( i = 0; i < nElements; i ++ ) {
  5484. a = vertexIndexBuffer[ i * 4 ];
  5485. b = vertexIndexBuffer[ i * 4 + 1 ];
  5486. c = vertexIndexBuffer[ i * 4 + 2 ];
  5487. d = vertexIndexBuffer[ i * 4 + 3 ];
  5488. na = normalIndexBuffer[ i * 4 ];
  5489. nb = normalIndexBuffer[ i * 4 + 1 ];
  5490. nc = normalIndexBuffer[ i * 4 + 2 ];
  5491. nd = normalIndexBuffer[ i * 4 + 3 ];
  5492. m = materialIndexBuffer[ i ];
  5493. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  5494. }
  5495. };
  5496. function init_triangles_flat( start ) {
  5497. var nElements = md.ntri_flat;
  5498. if ( nElements ) {
  5499. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5500. init_faces3_flat( nElements, start, offsetMaterials );
  5501. }
  5502. };
  5503. function init_triangles_flat_uv( start ) {
  5504. var nElements = md.ntri_flat_uv;
  5505. if ( nElements ) {
  5506. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5507. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5508. init_faces3_flat( nElements, start, offsetMaterials );
  5509. init_uvs3( nElements, offsetUvs );
  5510. }
  5511. };
  5512. function init_triangles_smooth( start ) {
  5513. var nElements = md.ntri_smooth;
  5514. if ( nElements ) {
  5515. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5516. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5517. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  5518. }
  5519. };
  5520. function init_triangles_smooth_uv( start ) {
  5521. var nElements = md.ntri_smooth_uv;
  5522. if ( nElements ) {
  5523. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5524. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5525. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5526. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  5527. init_uvs3( nElements, offsetUvs );
  5528. }
  5529. };
  5530. function init_quads_flat( start ) {
  5531. var nElements = md.nquad_flat;
  5532. if ( nElements ) {
  5533. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5534. init_faces4_flat( nElements, start, offsetMaterials );
  5535. }
  5536. };
  5537. function init_quads_flat_uv( start ) {
  5538. var nElements = md.nquad_flat_uv;
  5539. if ( nElements ) {
  5540. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5541. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5542. init_faces4_flat( nElements, start, offsetMaterials );
  5543. init_uvs4( nElements, offsetUvs );
  5544. }
  5545. };
  5546. function init_quads_smooth( start ) {
  5547. var nElements = md.nquad_smooth;
  5548. if ( nElements ) {
  5549. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5550. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5551. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  5552. }
  5553. };
  5554. function init_quads_smooth_uv( start ) {
  5555. var nElements = md.nquad_smooth_uv;
  5556. if ( nElements ) {
  5557. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5558. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5559. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5560. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  5561. init_uvs4( nElements, offsetUvs );
  5562. }
  5563. };
  5564. };
  5565. function vertex ( scope, x, y, z ) {
  5566. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  5567. };
  5568. function f3 ( scope, a, b, c, mi ) {
  5569. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  5570. };
  5571. function f4 ( scope, a, b, c, d, mi ) {
  5572. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  5573. };
  5574. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  5575. var nax = normals[ na*3 ],
  5576. nay = normals[ na*3 + 1 ],
  5577. naz = normals[ na*3 + 2 ],
  5578. nbx = normals[ nb*3 ],
  5579. nby = normals[ nb*3 + 1 ],
  5580. nbz = normals[ nb*3 + 2 ],
  5581. ncx = normals[ nc*3 ],
  5582. ncy = normals[ nc*3 + 1 ],
  5583. ncz = normals[ nc*3 + 2 ];
  5584. scope.faces.push( new THREE.Face3( a, b, c,
  5585. [new THREE.Vector3( nax, nay, naz ),
  5586. new THREE.Vector3( nbx, nby, nbz ),
  5587. new THREE.Vector3( ncx, ncy, ncz )],
  5588. null,
  5589. mi ) );
  5590. };
  5591. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  5592. var nax = normals[ na*3 ],
  5593. nay = normals[ na*3 + 1 ],
  5594. naz = normals[ na*3 + 2 ],
  5595. nbx = normals[ nb*3 ],
  5596. nby = normals[ nb*3 + 1 ],
  5597. nbz = normals[ nb*3 + 2 ],
  5598. ncx = normals[ nc*3 ],
  5599. ncy = normals[ nc*3 + 1 ],
  5600. ncz = normals[ nc*3 + 2 ],
  5601. ndx = normals[ nd*3 ],
  5602. ndy = normals[ nd*3 + 1 ],
  5603. ndz = normals[ nd*3 + 2 ];
  5604. scope.faces.push( new THREE.Face4( a, b, c, d,
  5605. [new THREE.Vector3( nax, nay, naz ),
  5606. new THREE.Vector3( nbx, nby, nbz ),
  5607. new THREE.Vector3( ncx, ncy, ncz ),
  5608. new THREE.Vector3( ndx, ndy, ndz )],
  5609. null,
  5610. mi ) );
  5611. };
  5612. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  5613. where.push( [
  5614. new THREE.Vector2( u1, v1 ),
  5615. new THREE.Vector2( u2, v2 ),
  5616. new THREE.Vector2( u3, v3 )
  5617. ] );
  5618. };
  5619. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  5620. where.push( [
  5621. new THREE.Vector2( u1, v1 ),
  5622. new THREE.Vector2( u2, v2 ),
  5623. new THREE.Vector2( u3, v3 ),
  5624. new THREE.Vector2( u4, v4 )
  5625. ] );
  5626. };
  5627. Model.prototype = Object.create( THREE.Geometry.prototype );
  5628. var geometry = new Model( texturePath );
  5629. var materials = this.initMaterials( jsonMaterials, texturePath );
  5630. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5631. callback( geometry, materials );
  5632. };
  5633. /**
  5634. * @author mrdoob / http://mrdoob.com/
  5635. */
  5636. THREE.ImageLoader = function () {
  5637. THREE.EventDispatcher.call( this );
  5638. this.crossOrigin = null;
  5639. };
  5640. THREE.ImageLoader.prototype = {
  5641. constructor: THREE.ImageLoader,
  5642. load: function ( url, image ) {
  5643. var scope = this;
  5644. if ( image === undefined ) image = new Image();
  5645. image.addEventListener( 'load', function () {
  5646. scope.dispatchEvent( { type: 'load', content: image } );
  5647. }, false );
  5648. image.addEventListener( 'error', function () {
  5649. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5650. }, false );
  5651. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5652. image.src = url;
  5653. }
  5654. }
  5655. /**
  5656. * @author mrdoob / http://mrdoob.com/
  5657. * @author alteredq / http://alteredqualia.com/
  5658. */
  5659. THREE.JSONLoader = function ( showStatus ) {
  5660. THREE.Loader.call( this, showStatus );
  5661. this.withCredentials = false;
  5662. };
  5663. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5664. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5665. var scope = this;
  5666. // todo: unify load API to for easier SceneLoader use
  5667. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5668. this.onLoadStart();
  5669. this.loadAjaxJSON( this, url, callback, texturePath );
  5670. };
  5671. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5672. var xhr = new XMLHttpRequest();
  5673. var length = 0;
  5674. xhr.withCredentials = this.withCredentials;
  5675. xhr.onreadystatechange = function () {
  5676. if ( xhr.readyState === xhr.DONE ) {
  5677. if ( xhr.status === 200 || xhr.status === 0 ) {
  5678. if ( xhr.responseText ) {
  5679. var json = JSON.parse( xhr.responseText );
  5680. context.createModel( json, callback, texturePath );
  5681. } else {
  5682. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5683. }
  5684. // in context of more complex asset initialization
  5685. // do not block on single failed file
  5686. // maybe should go even one more level up
  5687. context.onLoadComplete();
  5688. } else {
  5689. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5690. }
  5691. } else if ( xhr.readyState === xhr.LOADING ) {
  5692. if ( callbackProgress ) {
  5693. if ( length === 0 ) {
  5694. length = xhr.getResponseHeader( "Content-Length" );
  5695. }
  5696. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5697. }
  5698. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5699. length = xhr.getResponseHeader( "Content-Length" );
  5700. }
  5701. };
  5702. xhr.open( "GET", url, true );
  5703. xhr.send( null );
  5704. };
  5705. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  5706. var scope = this,
  5707. geometry = new THREE.Geometry(),
  5708. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5709. parseModel( scale );
  5710. parseSkin();
  5711. parseMorphing( scale );
  5712. geometry.computeCentroids();
  5713. geometry.computeFaceNormals();
  5714. function parseModel( scale ) {
  5715. function isBitSet( value, position ) {
  5716. return value & ( 1 << position );
  5717. }
  5718. var i, j, fi,
  5719. offset, zLength, nVertices,
  5720. colorIndex, normalIndex, uvIndex, materialIndex,
  5721. type,
  5722. isQuad,
  5723. hasMaterial,
  5724. hasFaceUv, hasFaceVertexUv,
  5725. hasFaceNormal, hasFaceVertexNormal,
  5726. hasFaceColor, hasFaceVertexColor,
  5727. vertex, face, color, normal,
  5728. uvLayer, uvs, u, v,
  5729. faces = json.faces,
  5730. vertices = json.vertices,
  5731. normals = json.normals,
  5732. colors = json.colors,
  5733. nUvLayers = 0;
  5734. // disregard empty arrays
  5735. for ( i = 0; i < json.uvs.length; i++ ) {
  5736. if ( json.uvs[ i ].length ) nUvLayers ++;
  5737. }
  5738. for ( i = 0; i < nUvLayers; i++ ) {
  5739. geometry.faceUvs[ i ] = [];
  5740. geometry.faceVertexUvs[ i ] = [];
  5741. }
  5742. offset = 0;
  5743. zLength = vertices.length;
  5744. while ( offset < zLength ) {
  5745. vertex = new THREE.Vector3();
  5746. vertex.x = vertices[ offset ++ ] * scale;
  5747. vertex.y = vertices[ offset ++ ] * scale;
  5748. vertex.z = vertices[ offset ++ ] * scale;
  5749. geometry.vertices.push( vertex );
  5750. }
  5751. offset = 0;
  5752. zLength = faces.length;
  5753. while ( offset < zLength ) {
  5754. type = faces[ offset ++ ];
  5755. isQuad = isBitSet( type, 0 );
  5756. hasMaterial = isBitSet( type, 1 );
  5757. hasFaceUv = isBitSet( type, 2 );
  5758. hasFaceVertexUv = isBitSet( type, 3 );
  5759. hasFaceNormal = isBitSet( type, 4 );
  5760. hasFaceVertexNormal = isBitSet( type, 5 );
  5761. hasFaceColor = isBitSet( type, 6 );
  5762. hasFaceVertexColor = isBitSet( type, 7 );
  5763. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5764. if ( isQuad ) {
  5765. face = new THREE.Face4();
  5766. face.a = faces[ offset ++ ];
  5767. face.b = faces[ offset ++ ];
  5768. face.c = faces[ offset ++ ];
  5769. face.d = faces[ offset ++ ];
  5770. nVertices = 4;
  5771. } else {
  5772. face = new THREE.Face3();
  5773. face.a = faces[ offset ++ ];
  5774. face.b = faces[ offset ++ ];
  5775. face.c = faces[ offset ++ ];
  5776. nVertices = 3;
  5777. }
  5778. if ( hasMaterial ) {
  5779. materialIndex = faces[ offset ++ ];
  5780. face.materialIndex = materialIndex;
  5781. }
  5782. // to get face <=> uv index correspondence
  5783. fi = geometry.faces.length;
  5784. if ( hasFaceUv ) {
  5785. for ( i = 0; i < nUvLayers; i++ ) {
  5786. uvLayer = json.uvs[ i ];
  5787. uvIndex = faces[ offset ++ ];
  5788. u = uvLayer[ uvIndex * 2 ];
  5789. v = uvLayer[ uvIndex * 2 + 1 ];
  5790. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  5791. }
  5792. }
  5793. if ( hasFaceVertexUv ) {
  5794. for ( i = 0; i < nUvLayers; i++ ) {
  5795. uvLayer = json.uvs[ i ];
  5796. uvs = [];
  5797. for ( j = 0; j < nVertices; j ++ ) {
  5798. uvIndex = faces[ offset ++ ];
  5799. u = uvLayer[ uvIndex * 2 ];
  5800. v = uvLayer[ uvIndex * 2 + 1 ];
  5801. uvs[ j ] = new THREE.Vector2( u, v );
  5802. }
  5803. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5804. }
  5805. }
  5806. if ( hasFaceNormal ) {
  5807. normalIndex = faces[ offset ++ ] * 3;
  5808. normal = new THREE.Vector3();
  5809. normal.x = normals[ normalIndex ++ ];
  5810. normal.y = normals[ normalIndex ++ ];
  5811. normal.z = normals[ normalIndex ];
  5812. face.normal = normal;
  5813. }
  5814. if ( hasFaceVertexNormal ) {
  5815. for ( i = 0; i < nVertices; i++ ) {
  5816. normalIndex = faces[ offset ++ ] * 3;
  5817. normal = new THREE.Vector3();
  5818. normal.x = normals[ normalIndex ++ ];
  5819. normal.y = normals[ normalIndex ++ ];
  5820. normal.z = normals[ normalIndex ];
  5821. face.vertexNormals.push( normal );
  5822. }
  5823. }
  5824. if ( hasFaceColor ) {
  5825. colorIndex = faces[ offset ++ ];
  5826. color = new THREE.Color( colors[ colorIndex ] );
  5827. face.color = color;
  5828. }
  5829. if ( hasFaceVertexColor ) {
  5830. for ( i = 0; i < nVertices; i++ ) {
  5831. colorIndex = faces[ offset ++ ];
  5832. color = new THREE.Color( colors[ colorIndex ] );
  5833. face.vertexColors.push( color );
  5834. }
  5835. }
  5836. geometry.faces.push( face );
  5837. }
  5838. };
  5839. function parseSkin() {
  5840. var i, l, x, y, z, w, a, b, c, d;
  5841. if ( json.skinWeights ) {
  5842. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5843. x = json.skinWeights[ i ];
  5844. y = json.skinWeights[ i + 1 ];
  5845. z = 0;
  5846. w = 0;
  5847. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5848. }
  5849. }
  5850. if ( json.skinIndices ) {
  5851. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5852. a = json.skinIndices[ i ];
  5853. b = json.skinIndices[ i + 1 ];
  5854. c = 0;
  5855. d = 0;
  5856. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5857. }
  5858. }
  5859. geometry.bones = json.bones;
  5860. geometry.animation = json.animation;
  5861. };
  5862. function parseMorphing( scale ) {
  5863. if ( json.morphTargets !== undefined ) {
  5864. var i, l, v, vl, dstVertices, srcVertices;
  5865. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5866. geometry.morphTargets[ i ] = {};
  5867. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5868. geometry.morphTargets[ i ].vertices = [];
  5869. dstVertices = geometry.morphTargets[ i ].vertices;
  5870. srcVertices = json.morphTargets [ i ].vertices;
  5871. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5872. var vertex = new THREE.Vector3();
  5873. vertex.x = srcVertices[ v ] * scale;
  5874. vertex.y = srcVertices[ v + 1 ] * scale;
  5875. vertex.z = srcVertices[ v + 2 ] * scale;
  5876. dstVertices.push( vertex );
  5877. }
  5878. }
  5879. }
  5880. if ( json.morphColors !== undefined ) {
  5881. var i, l, c, cl, dstColors, srcColors, color;
  5882. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5883. geometry.morphColors[ i ] = {};
  5884. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5885. geometry.morphColors[ i ].colors = [];
  5886. dstColors = geometry.morphColors[ i ].colors;
  5887. srcColors = json.morphColors [ i ].colors;
  5888. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5889. color = new THREE.Color( 0xffaa00 );
  5890. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5891. dstColors.push( color );
  5892. }
  5893. }
  5894. }
  5895. };
  5896. var materials = this.initMaterials( json.materials, texturePath );
  5897. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5898. callback( geometry, materials );
  5899. };
  5900. /**
  5901. * @author mrdoob / http://mrdoob.com/
  5902. */
  5903. THREE.LoadingMonitor = function () {
  5904. THREE.EventDispatcher.call( this );
  5905. var scope = this;
  5906. var loaded = 0;
  5907. var total = 0;
  5908. var onLoad = function ( event ) {
  5909. loaded ++;
  5910. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5911. if ( loaded === total ) {
  5912. scope.dispatchEvent( { type: 'load' } );
  5913. }
  5914. };
  5915. this.add = function ( loader ) {
  5916. total ++;
  5917. loader.addEventListener( 'load', onLoad, false );
  5918. };
  5919. };
  5920. /**
  5921. * @author alteredq / http://alteredqualia.com/
  5922. */
  5923. THREE.SceneLoader = function () {
  5924. this.onLoadStart = function () {};
  5925. this.onLoadProgress = function() {};
  5926. this.onLoadComplete = function () {};
  5927. this.callbackSync = function () {};
  5928. this.callbackProgress = function () {};
  5929. this.geometryHandlerMap = {};
  5930. this.hierarchyHandlerMap = {};
  5931. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5932. this.addGeometryHandler( "binary", THREE.BinaryLoader );
  5933. };
  5934. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5935. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5936. var scope = this;
  5937. var xhr = new XMLHttpRequest();
  5938. xhr.onreadystatechange = function () {
  5939. if ( xhr.readyState === 4 ) {
  5940. if ( xhr.status === 200 || xhr.status === 0 ) {
  5941. var json = JSON.parse( xhr.responseText );
  5942. scope.parse( json, callbackFinished, url );
  5943. } else {
  5944. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5945. }
  5946. }
  5947. };
  5948. xhr.open( "GET", url, true );
  5949. xhr.send( null );
  5950. };
  5951. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5952. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5953. };
  5954. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5955. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5956. };
  5957. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5958. var scope = this;
  5959. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5960. var geometry, material, camera, fog,
  5961. texture, images, color,
  5962. light, hex, intensity,
  5963. counter_models, counter_textures,
  5964. total_models, total_textures,
  5965. result;
  5966. var target_array = [];
  5967. var data = json;
  5968. // async geometry loaders
  5969. for ( var typeID in this.geometryHandlerMap ) {
  5970. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5971. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5972. }
  5973. // async hierachy loaders
  5974. for ( var typeID in this.hierarchyHandlerMap ) {
  5975. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5976. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5977. }
  5978. counter_models = 0;
  5979. counter_textures = 0;
  5980. result = {
  5981. scene: new THREE.Scene(),
  5982. geometries: {},
  5983. face_materials: {},
  5984. materials: {},
  5985. textures: {},
  5986. objects: {},
  5987. cameras: {},
  5988. lights: {},
  5989. fogs: {},
  5990. empties: {}
  5991. };
  5992. if ( data.transform ) {
  5993. var position = data.transform.position,
  5994. rotation = data.transform.rotation,
  5995. scale = data.transform.scale;
  5996. if ( position )
  5997. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5998. if ( rotation )
  5999. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  6000. if ( scale )
  6001. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  6002. if ( position || rotation || scale ) {
  6003. result.scene.updateMatrix();
  6004. result.scene.updateMatrixWorld();
  6005. }
  6006. }
  6007. function get_url( source_url, url_type ) {
  6008. if ( url_type == "relativeToHTML" ) {
  6009. return source_url;
  6010. } else {
  6011. return urlBase + "/" + source_url;
  6012. }
  6013. };
  6014. // toplevel loader function, delegates to handle_children
  6015. function handle_objects() {
  6016. handle_children( result.scene, data.objects );
  6017. }
  6018. // handle all the children from the loaded json and attach them to given parent
  6019. function handle_children( parent, children ) {
  6020. var mat, dst, pos, rot, scl, quat;
  6021. for ( var objID in children ) {
  6022. // check by id if child has already been handled,
  6023. // if not, create new object
  6024. if ( result.objects[ objID ] === undefined ) {
  6025. var objJSON = children[ objID ];
  6026. var object = null;
  6027. // meshes
  6028. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {
  6029. if ( objJSON.loading === undefined ) {
  6030. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  6031. "position": 1, "rotation": 1, "scale" : 1,
  6032. "visible": 1, "children": 1, "properties": 1,
  6033. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  6034. var loaderParameters = {};
  6035. for ( var parType in objJSON ) {
  6036. if ( ! ( parType in reservedTypes ) ) {
  6037. loaderParameters[ parType ] = objJSON[ parType ];
  6038. }
  6039. }
  6040. material = result.materials[ objJSON.material ];
  6041. objJSON.loading = true;
  6042. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  6043. // ColladaLoader
  6044. if ( loader.options ) {
  6045. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6046. // UTF8Loader
  6047. // OBJLoader
  6048. } else {
  6049. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6050. }
  6051. }
  6052. } else if ( objJSON.geometry !== undefined ) {
  6053. geometry = result.geometries[ objJSON.geometry ];
  6054. // geometry already loaded
  6055. if ( geometry ) {
  6056. var needsTangents = false;
  6057. material = result.materials[ objJSON.material ];
  6058. needsTangents = material instanceof THREE.ShaderMaterial;
  6059. pos = objJSON.position;
  6060. rot = objJSON.rotation;
  6061. scl = objJSON.scale;
  6062. mat = objJSON.matrix;
  6063. quat = objJSON.quaternion;
  6064. // turn off quaternions, for the moment
  6065. quat = 0;
  6066. // use materials from the model file
  6067. // if there is no material specified in the object
  6068. if ( ! objJSON.material ) {
  6069. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6070. }
  6071. // use materials from the model file
  6072. // if there is just empty face material
  6073. // (must create new material as each model has its own face material)
  6074. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6075. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6076. }
  6077. if ( material instanceof THREE.MeshFaceMaterial ) {
  6078. for ( var i = 0; i < material.materials.length; i ++ ) {
  6079. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6080. }
  6081. }
  6082. if ( needsTangents ) {
  6083. geometry.computeTangents();
  6084. }
  6085. if ( objJSON.skin ) {
  6086. object = new THREE.SkinnedMesh( geometry, material );
  6087. } else if ( objJSON.morph ) {
  6088. object = new THREE.MorphAnimMesh( geometry, material );
  6089. if ( objJSON.duration !== undefined ) {
  6090. object.duration = objJSON.duration;
  6091. }
  6092. if ( objJSON.time !== undefined ) {
  6093. object.time = objJSON.time;
  6094. }
  6095. if ( objJSON.mirroredLoop !== undefined ) {
  6096. object.mirroredLoop = objJSON.mirroredLoop;
  6097. }
  6098. if ( material.morphNormals ) {
  6099. geometry.computeMorphNormals();
  6100. }
  6101. } else {
  6102. object = new THREE.Mesh( geometry, material );
  6103. }
  6104. object.name = objID;
  6105. if ( mat ) {
  6106. object.matrixAutoUpdate = false;
  6107. object.matrix.set(
  6108. mat[0], mat[1], mat[2], mat[3],
  6109. mat[4], mat[5], mat[6], mat[7],
  6110. mat[8], mat[9], mat[10], mat[11],
  6111. mat[12], mat[13], mat[14], mat[15]
  6112. );
  6113. } else {
  6114. object.position.set( pos[0], pos[1], pos[2] );
  6115. if ( quat ) {
  6116. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6117. object.useQuaternion = true;
  6118. } else {
  6119. object.rotation.set( rot[0], rot[1], rot[2] );
  6120. }
  6121. object.scale.set( scl[0], scl[1], scl[2] );
  6122. }
  6123. object.visible = objJSON.visible;
  6124. object.castShadow = objJSON.castShadow;
  6125. object.receiveShadow = objJSON.receiveShadow;
  6126. parent.add( object );
  6127. result.objects[ objID ] = object;
  6128. }
  6129. // lights
  6130. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6131. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6132. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6133. if ( objJSON.type === "DirectionalLight" ) {
  6134. pos = objJSON.direction;
  6135. light = new THREE.DirectionalLight( hex, intensity );
  6136. light.position.set( pos[0], pos[1], pos[2] );
  6137. if ( objJSON.target ) {
  6138. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6139. // kill existing default target
  6140. // otherwise it gets added to scene when parent gets added
  6141. light.target = null;
  6142. }
  6143. } else if ( objJSON.type === "PointLight" ) {
  6144. pos = objJSON.position;
  6145. dst = objJSON.distance;
  6146. light = new THREE.PointLight( hex, intensity, dst );
  6147. light.position.set( pos[0], pos[1], pos[2] );
  6148. } else if ( objJSON.type === "AmbientLight" ) {
  6149. light = new THREE.AmbientLight( hex );
  6150. }
  6151. parent.add( light );
  6152. light.name = objID;
  6153. result.lights[ objID ] = light;
  6154. result.objects[ objID ] = light;
  6155. // cameras
  6156. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6157. if ( objJSON.type === "PerspectiveCamera" ) {
  6158. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6159. } else if ( objJSON.type === "OrthographicCamera" ) {
  6160. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6161. }
  6162. pos = objJSON.position;
  6163. camera.position.set( pos[0], pos[1], pos[2] );
  6164. parent.add( camera );
  6165. camera.name = objID;
  6166. result.cameras[ objID ] = camera;
  6167. result.objects[ objID ] = camera;
  6168. // pure Object3D
  6169. } else {
  6170. pos = objJSON.position;
  6171. rot = objJSON.rotation;
  6172. scl = objJSON.scale;
  6173. quat = objJSON.quaternion;
  6174. // turn off quaternions, for the moment
  6175. quat = 0;
  6176. object = new THREE.Object3D();
  6177. object.name = objID;
  6178. object.position.set( pos[0], pos[1], pos[2] );
  6179. if ( quat ) {
  6180. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6181. object.useQuaternion = true;
  6182. } else {
  6183. object.rotation.set( rot[0], rot[1], rot[2] );
  6184. }
  6185. object.scale.set( scl[0], scl[1], scl[2] );
  6186. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6187. parent.add( object );
  6188. result.objects[ objID ] = object;
  6189. result.empties[ objID ] = object;
  6190. }
  6191. if ( object ) {
  6192. if ( objJSON.properties !== undefined ) {
  6193. for ( var key in objJSON.properties ) {
  6194. var value = objJSON.properties[ key ];
  6195. object.properties[ key ] = value;
  6196. }
  6197. }
  6198. if ( objJSON.children !== undefined ) {
  6199. handle_children( object, objJSON.children );
  6200. }
  6201. }
  6202. }
  6203. }
  6204. };
  6205. function handle_mesh( geo, mat, id ) {
  6206. result.geometries[ id ] = geo;
  6207. result.face_materials[ id ] = mat;
  6208. handle_objects();
  6209. };
  6210. function handle_hierarchy( node, id, parent, material, obj ) {
  6211. var p = obj.position;
  6212. var r = obj.rotation;
  6213. var q = obj.quaternion;
  6214. var s = obj.scale;
  6215. node.position.set( p[0], p[1], p[2] );
  6216. if ( q ) {
  6217. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6218. node.useQuaternion = true;
  6219. } else {
  6220. node.rotation.set( r[0], r[1], r[2] );
  6221. }
  6222. node.scale.set( s[0], s[1], s[2] );
  6223. // override children materials
  6224. // if object material was specified in JSON explicitly
  6225. if ( material ) {
  6226. node.traverse( function ( child ) {
  6227. child.material = material;
  6228. } );
  6229. }
  6230. // override children visibility
  6231. // with root node visibility as specified in JSON
  6232. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6233. node.traverse( function ( child ) {
  6234. child.visible = visible;
  6235. } );
  6236. parent.add( node );
  6237. node.name = id;
  6238. result.objects[ id ] = node;
  6239. handle_objects();
  6240. };
  6241. function create_callback_geometry( id ) {
  6242. return function( geo, mat ) {
  6243. handle_mesh( geo, mat, id );
  6244. counter_models -= 1;
  6245. scope.onLoadComplete();
  6246. async_callback_gate();
  6247. }
  6248. };
  6249. function create_callback_hierachy( id, parent, material, obj ) {
  6250. return function( event ) {
  6251. var result;
  6252. // loaders which use EventDispatcher
  6253. if ( event.content ) {
  6254. result = event.content;
  6255. // ColladaLoader
  6256. } else if ( event.dae ) {
  6257. result = event.scene;
  6258. // UTF8Loader
  6259. } else {
  6260. result = event;
  6261. }
  6262. handle_hierarchy( result, id, parent, material, obj );
  6263. counter_models -= 1;
  6264. scope.onLoadComplete();
  6265. async_callback_gate();
  6266. }
  6267. };
  6268. function create_callback_embed( id ) {
  6269. return function( geo, mat ) {
  6270. result.geometries[ id ] = geo;
  6271. result.face_materials[ id ] = mat;
  6272. }
  6273. };
  6274. function async_callback_gate() {
  6275. var progress = {
  6276. totalModels : total_models,
  6277. totalTextures : total_textures,
  6278. loadedModels : total_models - counter_models,
  6279. loadedTextures : total_textures - counter_textures
  6280. };
  6281. scope.callbackProgress( progress, result );
  6282. scope.onLoadProgress();
  6283. if ( counter_models === 0 && counter_textures === 0 ) {
  6284. finalize();
  6285. callbackFinished( result );
  6286. }
  6287. };
  6288. function finalize() {
  6289. // take care of targets which could be asynchronously loaded objects
  6290. for ( var i = 0; i < target_array.length; i ++ ) {
  6291. var ta = target_array[ i ];
  6292. var target = result.objects[ ta.targetName ];
  6293. if ( target ) {
  6294. ta.object.target = target;
  6295. } else {
  6296. // if there was error and target of specified name doesn't exist in the scene file
  6297. // create instead dummy target
  6298. // (target must be added to scene explicitly as parent is already added)
  6299. ta.object.target = new THREE.Object3D();
  6300. result.scene.add( ta.object.target );
  6301. }
  6302. ta.object.target.properties.targetInverse = ta.object;
  6303. }
  6304. };
  6305. var callbackTexture = function ( count ) {
  6306. counter_textures -= count;
  6307. async_callback_gate();
  6308. scope.onLoadComplete();
  6309. };
  6310. // must use this instead of just directly calling callbackTexture
  6311. // because of closure in the calling context loop
  6312. var generateTextureCallback = function ( count ) {
  6313. return function() {
  6314. callbackTexture( count );
  6315. };
  6316. };
  6317. // first go synchronous elements
  6318. // fogs
  6319. var fogID, fogJSON;
  6320. for ( fogID in data.fogs ) {
  6321. fogJSON = data.fogs[ fogID ];
  6322. if ( fogJSON.type === "linear" ) {
  6323. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6324. } else if ( fogJSON.type === "exp2" ) {
  6325. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6326. }
  6327. color = fogJSON.color;
  6328. fog.color.setRGB( color[0], color[1], color[2] );
  6329. result.fogs[ fogID ] = fog;
  6330. }
  6331. // now come potentially asynchronous elements
  6332. // geometries
  6333. // count how many geometries will be loaded asynchronously
  6334. var geoID, geoJSON;
  6335. for ( geoID in data.geometries ) {
  6336. geoJSON = data.geometries[ geoID ];
  6337. if ( geoJSON.type in this.geometryHandlerMap ) {
  6338. counter_models += 1;
  6339. scope.onLoadStart();
  6340. }
  6341. }
  6342. // count how many hierarchies will be loaded asynchronously
  6343. var objID, objJSON;
  6344. for ( objID in data.objects ) {
  6345. objJSON = data.objects[ objID ];
  6346. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6347. counter_models += 1;
  6348. scope.onLoadStart();
  6349. }
  6350. }
  6351. total_models = counter_models;
  6352. for ( geoID in data.geometries ) {
  6353. geoJSON = data.geometries[ geoID ];
  6354. if ( geoJSON.type === "cube" ) {
  6355. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6356. result.geometries[ geoID ] = geometry;
  6357. } else if ( geoJSON.type === "plane" ) {
  6358. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6359. result.geometries[ geoID ] = geometry;
  6360. } else if ( geoJSON.type === "sphere" ) {
  6361. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6362. result.geometries[ geoID ] = geometry;
  6363. } else if ( geoJSON.type === "cylinder" ) {
  6364. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6365. result.geometries[ geoID ] = geometry;
  6366. } else if ( geoJSON.type === "torus" ) {
  6367. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6368. result.geometries[ geoID ] = geometry;
  6369. } else if ( geoJSON.type === "icosahedron" ) {
  6370. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6371. result.geometries[ geoID ] = geometry;
  6372. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6373. var loaderParameters = {};
  6374. for ( var parType in geoJSON ) {
  6375. if ( parType !== "type" && parType !== "url" ) {
  6376. loaderParameters[ parType ] = geoJSON[ parType ];
  6377. }
  6378. }
  6379. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6380. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6381. } else if ( geoJSON.type === "embedded" ) {
  6382. var modelJson = data.embeds[ geoJSON.id ],
  6383. texture_path = "";
  6384. // pass metadata along to jsonLoader so it knows the format version
  6385. modelJson.metadata = data.metadata;
  6386. if ( modelJson ) {
  6387. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6388. jsonLoader.createModel( modelJson, create_callback_embed( geoID ), texture_path );
  6389. }
  6390. }
  6391. }
  6392. // textures
  6393. // count how many textures will be loaded asynchronously
  6394. var textureID, textureJSON;
  6395. for ( textureID in data.textures ) {
  6396. textureJSON = data.textures[ textureID ];
  6397. if ( textureJSON.url instanceof Array ) {
  6398. counter_textures += textureJSON.url.length;
  6399. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6400. scope.onLoadStart();
  6401. }
  6402. } else {
  6403. counter_textures += 1;
  6404. scope.onLoadStart();
  6405. }
  6406. }
  6407. total_textures = counter_textures;
  6408. for ( textureID in data.textures ) {
  6409. textureJSON = data.textures[ textureID ];
  6410. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6411. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6412. }
  6413. if ( textureJSON.url instanceof Array ) {
  6414. var count = textureJSON.url.length;
  6415. var url_array = [];
  6416. for( var i = 0; i < count; i ++ ) {
  6417. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6418. }
  6419. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  6420. if ( isCompressed ) {
  6421. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6422. } else {
  6423. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6424. }
  6425. } else {
  6426. var isCompressed = textureJSON.url.toLowerCase().endsWith( ".dds" );
  6427. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6428. var textureCallback = generateTextureCallback( 1 );
  6429. if ( isCompressed ) {
  6430. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6431. } else {
  6432. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6433. }
  6434. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6435. texture.minFilter = THREE[ textureJSON.minFilter ];
  6436. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6437. texture.magFilter = THREE[ textureJSON.magFilter ];
  6438. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6439. if ( textureJSON.repeat ) {
  6440. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6441. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6442. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6443. }
  6444. if ( textureJSON.offset ) {
  6445. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6446. }
  6447. // handle wrap after repeat so that default repeat can be overriden
  6448. if ( textureJSON.wrap ) {
  6449. var wrapMap = {
  6450. "repeat" : THREE.RepeatWrapping,
  6451. "mirror" : THREE.MirroredRepeatWrapping
  6452. }
  6453. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6454. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6455. }
  6456. }
  6457. result.textures[ textureID ] = texture;
  6458. }
  6459. // materials
  6460. var matID, matJSON;
  6461. var parID;
  6462. for ( matID in data.materials ) {
  6463. matJSON = data.materials[ matID ];
  6464. for ( parID in matJSON.parameters ) {
  6465. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6466. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6467. } else if ( parID === "shading" ) {
  6468. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6469. } else if ( parID === "side" ) {
  6470. if ( matJSON.parameters[ parID ] == "double" ) {
  6471. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6472. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6473. matJSON.parameters[ parID ] = THREE.BackSide;
  6474. } else {
  6475. matJSON.parameters[ parID ] = THREE.FrontSide;
  6476. }
  6477. } else if ( parID === "blending" ) {
  6478. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6479. } else if ( parID === "combine" ) {
  6480. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  6481. } else if ( parID === "vertexColors" ) {
  6482. if ( matJSON.parameters[ parID ] == "face" ) {
  6483. matJSON.parameters[ parID ] = THREE.FaceColors;
  6484. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6485. } else if ( matJSON.parameters[ parID ] ) {
  6486. matJSON.parameters[ parID ] = THREE.VertexColors;
  6487. }
  6488. } else if ( parID === "wrapRGB" ) {
  6489. var v3 = matJSON.parameters[ parID ];
  6490. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6491. }
  6492. }
  6493. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6494. matJSON.parameters.transparent = true;
  6495. }
  6496. if ( matJSON.parameters.normalMap ) {
  6497. var shader = THREE.ShaderUtils.lib[ "normal" ];
  6498. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6499. var diffuse = matJSON.parameters.color;
  6500. var specular = matJSON.parameters.specular;
  6501. var ambient = matJSON.parameters.ambient;
  6502. var shininess = matJSON.parameters.shininess;
  6503. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6504. if ( matJSON.parameters.normalScale ) {
  6505. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6506. }
  6507. if ( matJSON.parameters.map ) {
  6508. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6509. uniforms[ "enableDiffuse" ].value = true;
  6510. }
  6511. if ( matJSON.parameters.envMap ) {
  6512. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6513. uniforms[ "enableReflection" ].value = true;
  6514. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6515. }
  6516. if ( matJSON.parameters.lightMap ) {
  6517. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6518. uniforms[ "enableAO" ].value = true;
  6519. }
  6520. if ( matJSON.parameters.specularMap ) {
  6521. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6522. uniforms[ "enableSpecular" ].value = true;
  6523. }
  6524. if ( matJSON.parameters.displacementMap ) {
  6525. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6526. uniforms[ "enableDisplacement" ].value = true;
  6527. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6528. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6529. }
  6530. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6531. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6532. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6533. uniforms[ "uShininess" ].value = shininess;
  6534. if ( matJSON.parameters.opacity ) {
  6535. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6536. }
  6537. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6538. material = new THREE.ShaderMaterial( parameters );
  6539. } else {
  6540. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6541. }
  6542. result.materials[ matID ] = material;
  6543. }
  6544. // second pass through all materials to initialize MeshFaceMaterials
  6545. // that could be referring to other materials out of order
  6546. for ( matID in data.materials ) {
  6547. matJSON = data.materials[ matID ];
  6548. if ( matJSON.parameters.materials ) {
  6549. var materialArray = [];
  6550. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6551. var label = matJSON.parameters.materials[ i ];
  6552. materialArray.push( result.materials[ label ] );
  6553. }
  6554. result.materials[ matID ].materials = materialArray;
  6555. }
  6556. }
  6557. // objects ( synchronous init of procedural primitives )
  6558. handle_objects();
  6559. // defaults
  6560. if ( result.cameras && data.defaults.camera ) {
  6561. result.currentCamera = result.cameras[ data.defaults.camera ];
  6562. }
  6563. if ( result.fogs && data.defaults.fog ) {
  6564. result.scene.fog = result.fogs[ data.defaults.fog ];
  6565. }
  6566. color = data.defaults.bgcolor;
  6567. result.bgColor = new THREE.Color();
  6568. result.bgColor.setRGB( color[0], color[1], color[2] );
  6569. result.bgColorAlpha = data.defaults.bgalpha;
  6570. // synchronous callback
  6571. scope.callbackSync( result );
  6572. // just in case there are no async elements
  6573. async_callback_gate();
  6574. };
  6575. /**
  6576. * @author mrdoob / http://mrdoob.com/
  6577. */
  6578. THREE.TextureLoader = function () {
  6579. THREE.EventDispatcher.call( this );
  6580. this.crossOrigin = null;
  6581. };
  6582. THREE.TextureLoader.prototype = {
  6583. constructor: THREE.TextureLoader,
  6584. load: function ( url ) {
  6585. var scope = this;
  6586. var image = new Image();
  6587. image.addEventListener( 'load', function () {
  6588. var texture = new THREE.Texture( image );
  6589. texture.needsUpdate = true;
  6590. scope.dispatchEvent( { type: 'load', content: texture } );
  6591. }, false );
  6592. image.addEventListener( 'error', function () {
  6593. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6594. }, false );
  6595. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6596. image.src = url;
  6597. }
  6598. }
  6599. /**
  6600. * @author mrdoob / http://mrdoob.com/
  6601. * @author alteredq / http://alteredqualia.com/
  6602. */
  6603. THREE.Material = function () {
  6604. THREE.EventDispatcher.call( this );
  6605. this.id = THREE.MaterialIdCount ++;
  6606. this.name = '';
  6607. this.side = THREE.FrontSide;
  6608. this.opacity = 1;
  6609. this.transparent = false;
  6610. this.blending = THREE.NormalBlending;
  6611. this.blendSrc = THREE.SrcAlphaFactor;
  6612. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6613. this.blendEquation = THREE.AddEquation;
  6614. this.depthTest = true;
  6615. this.depthWrite = true;
  6616. this.polygonOffset = false;
  6617. this.polygonOffsetFactor = 0;
  6618. this.polygonOffsetUnits = 0;
  6619. this.alphaTest = 0;
  6620. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6621. this.visible = true;
  6622. this.needsUpdate = true;
  6623. };
  6624. THREE.Material.prototype.setValues = function ( values ) {
  6625. if ( values === undefined ) return;
  6626. for ( var key in values ) {
  6627. var newValue = values[ key ];
  6628. if ( newValue === undefined ) {
  6629. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6630. continue;
  6631. }
  6632. if ( key in this ) {
  6633. var currentValue = this[ key ];
  6634. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  6635. currentValue.copy( newValue );
  6636. } else if ( currentValue instanceof THREE.Color ) {
  6637. currentValue.set( newValue );
  6638. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6639. currentValue.copy( newValue );
  6640. } else {
  6641. this[ key ] = newValue;
  6642. }
  6643. }
  6644. }
  6645. };
  6646. THREE.Material.prototype.clone = function ( material ) {
  6647. if ( material === undefined ) material = new THREE.Material();
  6648. material.name = this.name;
  6649. material.side = this.side;
  6650. material.opacity = this.opacity;
  6651. material.transparent = this.transparent;
  6652. material.blending = this.blending;
  6653. material.blendSrc = this.blendSrc;
  6654. material.blendDst = this.blendDst;
  6655. material.blendEquation = this.blendEquation;
  6656. material.depthTest = this.depthTest;
  6657. material.depthWrite = this.depthWrite;
  6658. material.polygonOffset = this.polygonOffset;
  6659. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6660. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6661. material.alphaTest = this.alphaTest;
  6662. material.overdraw = this.overdraw;
  6663. material.visible = this.visible;
  6664. return material;
  6665. };
  6666. THREE.Material.prototype.dispose = function () {
  6667. this.dispatchEvent( { type: 'dispose' } );
  6668. };
  6669. THREE.MaterialIdCount = 0;
  6670. /**
  6671. * @author mrdoob / http://mrdoob.com/
  6672. * @author alteredq / http://alteredqualia.com/
  6673. *
  6674. * parameters = {
  6675. * color: <hex>,
  6676. * opacity: <float>,
  6677. *
  6678. * blending: THREE.NormalBlending,
  6679. * depthTest: <bool>,
  6680. * depthWrite: <bool>,
  6681. *
  6682. * linewidth: <float>,
  6683. * linecap: "round",
  6684. * linejoin: "round",
  6685. *
  6686. * vertexColors: <bool>
  6687. *
  6688. * fog: <bool>
  6689. * }
  6690. */
  6691. THREE.LineBasicMaterial = function ( parameters ) {
  6692. THREE.Material.call( this );
  6693. this.color = new THREE.Color( 0xffffff );
  6694. this.linewidth = 1;
  6695. this.linecap = 'round';
  6696. this.linejoin = 'round';
  6697. this.vertexColors = false;
  6698. this.fog = true;
  6699. this.setValues( parameters );
  6700. };
  6701. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6702. THREE.LineBasicMaterial.prototype.clone = function () {
  6703. var material = new THREE.LineBasicMaterial();
  6704. THREE.Material.prototype.clone.call( this, material );
  6705. material.color.copy( this.color );
  6706. material.linewidth = this.linewidth;
  6707. material.linecap = this.linecap;
  6708. material.linejoin = this.linejoin;
  6709. material.vertexColors = this.vertexColors;
  6710. material.fog = this.fog;
  6711. return material;
  6712. };
  6713. /**
  6714. * @author alteredq / http://alteredqualia.com/
  6715. *
  6716. * parameters = {
  6717. * color: <hex>,
  6718. * opacity: <float>,
  6719. *
  6720. * blending: THREE.NormalBlending,
  6721. * depthTest: <bool>,
  6722. * depthWrite: <bool>,
  6723. *
  6724. * linewidth: <float>,
  6725. *
  6726. * scale: <float>,
  6727. * dashSize: <float>,
  6728. * gapSize: <float>,
  6729. *
  6730. * vertexColors: <bool>
  6731. *
  6732. * fog: <bool>
  6733. * }
  6734. */
  6735. THREE.LineDashedMaterial = function ( parameters ) {
  6736. THREE.Material.call( this );
  6737. this.color = new THREE.Color( 0xffffff );
  6738. this.linewidth = 1;
  6739. this.scale = 1;
  6740. this.dashSize = 3;
  6741. this.gapSize = 1;
  6742. this.vertexColors = false;
  6743. this.fog = true;
  6744. this.setValues( parameters );
  6745. };
  6746. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6747. THREE.LineDashedMaterial.prototype.clone = function () {
  6748. var material = new THREE.LineDashedMaterial();
  6749. THREE.Material.prototype.clone.call( this, material );
  6750. material.color.copy( this.color );
  6751. material.linewidth = this.linewidth;
  6752. material.scale = this.scale;
  6753. material.dashSize = this.dashSize;
  6754. material.gapSize = this.gapSize;
  6755. material.vertexColors = this.vertexColors;
  6756. material.fog = this.fog;
  6757. return material;
  6758. };
  6759. /**
  6760. * @author mrdoob / http://mrdoob.com/
  6761. * @author alteredq / http://alteredqualia.com/
  6762. *
  6763. * parameters = {
  6764. * color: <hex>,
  6765. * opacity: <float>,
  6766. * map: new THREE.Texture( <Image> ),
  6767. *
  6768. * lightMap: new THREE.Texture( <Image> ),
  6769. *
  6770. * specularMap: new THREE.Texture( <Image> ),
  6771. *
  6772. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6773. * combine: THREE.Multiply,
  6774. * reflectivity: <float>,
  6775. * refractionRatio: <float>,
  6776. *
  6777. * shading: THREE.SmoothShading,
  6778. * blending: THREE.NormalBlending,
  6779. * depthTest: <bool>,
  6780. * depthWrite: <bool>,
  6781. *
  6782. * wireframe: <boolean>,
  6783. * wireframeLinewidth: <float>,
  6784. *
  6785. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6786. *
  6787. * skinning: <bool>,
  6788. * morphTargets: <bool>,
  6789. *
  6790. * fog: <bool>
  6791. * }
  6792. */
  6793. THREE.MeshBasicMaterial = function ( parameters ) {
  6794. THREE.Material.call( this );
  6795. this.color = new THREE.Color( 0xffffff ); // emissive
  6796. this.map = null;
  6797. this.lightMap = null;
  6798. this.specularMap = null;
  6799. this.envMap = null;
  6800. this.combine = THREE.MultiplyOperation;
  6801. this.reflectivity = 1;
  6802. this.refractionRatio = 0.98;
  6803. this.fog = true;
  6804. this.shading = THREE.SmoothShading;
  6805. this.wireframe = false;
  6806. this.wireframeLinewidth = 1;
  6807. this.wireframeLinecap = 'round';
  6808. this.wireframeLinejoin = 'round';
  6809. this.vertexColors = THREE.NoColors;
  6810. this.skinning = false;
  6811. this.morphTargets = false;
  6812. this.setValues( parameters );
  6813. };
  6814. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6815. THREE.MeshBasicMaterial.prototype.clone = function () {
  6816. var material = new THREE.MeshBasicMaterial();
  6817. THREE.Material.prototype.clone.call( this, material );
  6818. material.color.copy( this.color );
  6819. material.map = this.map;
  6820. material.lightMap = this.lightMap;
  6821. material.specularMap = this.specularMap;
  6822. material.envMap = this.envMap;
  6823. material.combine = this.combine;
  6824. material.reflectivity = this.reflectivity;
  6825. material.refractionRatio = this.refractionRatio;
  6826. material.fog = this.fog;
  6827. material.shading = this.shading;
  6828. material.wireframe = this.wireframe;
  6829. material.wireframeLinewidth = this.wireframeLinewidth;
  6830. material.wireframeLinecap = this.wireframeLinecap;
  6831. material.wireframeLinejoin = this.wireframeLinejoin;
  6832. material.vertexColors = this.vertexColors;
  6833. material.skinning = this.skinning;
  6834. material.morphTargets = this.morphTargets;
  6835. return material;
  6836. };
  6837. /**
  6838. * @author mrdoob / http://mrdoob.com/
  6839. * @author alteredq / http://alteredqualia.com/
  6840. *
  6841. * parameters = {
  6842. * color: <hex>,
  6843. * ambient: <hex>,
  6844. * emissive: <hex>,
  6845. * opacity: <float>,
  6846. *
  6847. * map: new THREE.Texture( <Image> ),
  6848. *
  6849. * lightMap: new THREE.Texture( <Image> ),
  6850. *
  6851. * specularMap: new THREE.Texture( <Image> ),
  6852. *
  6853. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6854. * combine: THREE.Multiply,
  6855. * reflectivity: <float>,
  6856. * refractionRatio: <float>,
  6857. *
  6858. * shading: THREE.SmoothShading,
  6859. * blending: THREE.NormalBlending,
  6860. * depthTest: <bool>,
  6861. * depthWrite: <bool>,
  6862. *
  6863. * wireframe: <boolean>,
  6864. * wireframeLinewidth: <float>,
  6865. *
  6866. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6867. *
  6868. * skinning: <bool>,
  6869. * morphTargets: <bool>,
  6870. * morphNormals: <bool>,
  6871. *
  6872. * fog: <bool>
  6873. * }
  6874. */
  6875. THREE.MeshLambertMaterial = function ( parameters ) {
  6876. THREE.Material.call( this );
  6877. this.color = new THREE.Color( 0xffffff ); // diffuse
  6878. this.ambient = new THREE.Color( 0xffffff );
  6879. this.emissive = new THREE.Color( 0x000000 );
  6880. this.wrapAround = false;
  6881. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6882. this.map = null;
  6883. this.lightMap = null;
  6884. this.specularMap = null;
  6885. this.envMap = null;
  6886. this.combine = THREE.MultiplyOperation;
  6887. this.reflectivity = 1;
  6888. this.refractionRatio = 0.98;
  6889. this.fog = true;
  6890. this.shading = THREE.SmoothShading;
  6891. this.wireframe = false;
  6892. this.wireframeLinewidth = 1;
  6893. this.wireframeLinecap = 'round';
  6894. this.wireframeLinejoin = 'round';
  6895. this.vertexColors = THREE.NoColors;
  6896. this.skinning = false;
  6897. this.morphTargets = false;
  6898. this.morphNormals = false;
  6899. this.setValues( parameters );
  6900. };
  6901. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6902. THREE.MeshLambertMaterial.prototype.clone = function () {
  6903. var material = new THREE.MeshLambertMaterial();
  6904. THREE.Material.prototype.clone.call( this, material );
  6905. material.color.copy( this.color );
  6906. material.ambient.copy( this.ambient );
  6907. material.emissive.copy( this.emissive );
  6908. material.wrapAround = this.wrapAround;
  6909. material.wrapRGB.copy( this.wrapRGB );
  6910. material.map = this.map;
  6911. material.lightMap = this.lightMap;
  6912. material.specularMap = this.specularMap;
  6913. material.envMap = this.envMap;
  6914. material.combine = this.combine;
  6915. material.reflectivity = this.reflectivity;
  6916. material.refractionRatio = this.refractionRatio;
  6917. material.fog = this.fog;
  6918. material.shading = this.shading;
  6919. material.wireframe = this.wireframe;
  6920. material.wireframeLinewidth = this.wireframeLinewidth;
  6921. material.wireframeLinecap = this.wireframeLinecap;
  6922. material.wireframeLinejoin = this.wireframeLinejoin;
  6923. material.vertexColors = this.vertexColors;
  6924. material.skinning = this.skinning;
  6925. material.morphTargets = this.morphTargets;
  6926. material.morphNormals = this.morphNormals;
  6927. return material;
  6928. };
  6929. /**
  6930. * @author mrdoob / http://mrdoob.com/
  6931. * @author alteredq / http://alteredqualia.com/
  6932. *
  6933. * parameters = {
  6934. * color: <hex>,
  6935. * ambient: <hex>,
  6936. * emissive: <hex>,
  6937. * specular: <hex>,
  6938. * shininess: <float>,
  6939. * opacity: <float>,
  6940. *
  6941. * map: new THREE.Texture( <Image> ),
  6942. *
  6943. * lightMap: new THREE.Texture( <Image> ),
  6944. *
  6945. * bumpMap: new THREE.Texture( <Image> ),
  6946. * bumpScale: <float>,
  6947. *
  6948. * normalMap: new THREE.Texture( <Image> ),
  6949. * normalScale: <Vector2>,
  6950. *
  6951. * specularMap: new THREE.Texture( <Image> ),
  6952. *
  6953. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6954. * combine: THREE.Multiply,
  6955. * reflectivity: <float>,
  6956. * refractionRatio: <float>,
  6957. *
  6958. * shading: THREE.SmoothShading,
  6959. * blending: THREE.NormalBlending,
  6960. * depthTest: <bool>,
  6961. * depthWrite: <bool>,
  6962. *
  6963. * wireframe: <boolean>,
  6964. * wireframeLinewidth: <float>,
  6965. *
  6966. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6967. *
  6968. * skinning: <bool>,
  6969. * morphTargets: <bool>,
  6970. * morphNormals: <bool>,
  6971. *
  6972. * fog: <bool>
  6973. * }
  6974. */
  6975. THREE.MeshPhongMaterial = function ( parameters ) {
  6976. THREE.Material.call( this );
  6977. this.color = new THREE.Color( 0xffffff ); // diffuse
  6978. this.ambient = new THREE.Color( 0xffffff );
  6979. this.emissive = new THREE.Color( 0x000000 );
  6980. this.specular = new THREE.Color( 0x111111 );
  6981. this.shininess = 30;
  6982. this.metal = false;
  6983. this.perPixel = true;
  6984. this.wrapAround = false;
  6985. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6986. this.map = null;
  6987. this.lightMap = null;
  6988. this.bumpMap = null;
  6989. this.bumpScale = 1;
  6990. this.normalMap = null;
  6991. this.normalScale = new THREE.Vector2( 1, 1 );
  6992. this.specularMap = null;
  6993. this.envMap = null;
  6994. this.combine = THREE.MultiplyOperation;
  6995. this.reflectivity = 1;
  6996. this.refractionRatio = 0.98;
  6997. this.fog = true;
  6998. this.shading = THREE.SmoothShading;
  6999. this.wireframe = false;
  7000. this.wireframeLinewidth = 1;
  7001. this.wireframeLinecap = 'round';
  7002. this.wireframeLinejoin = 'round';
  7003. this.vertexColors = THREE.NoColors;
  7004. this.skinning = false;
  7005. this.morphTargets = false;
  7006. this.morphNormals = false;
  7007. this.setValues( parameters );
  7008. };
  7009. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7010. THREE.MeshPhongMaterial.prototype.clone = function () {
  7011. var material = new THREE.MeshPhongMaterial();
  7012. THREE.Material.prototype.clone.call( this, material );
  7013. material.color.copy( this.color );
  7014. material.ambient.copy( this.ambient );
  7015. material.emissive.copy( this.emissive );
  7016. material.specular.copy( this.specular );
  7017. material.shininess = this.shininess;
  7018. material.metal = this.metal;
  7019. material.perPixel = this.perPixel;
  7020. material.wrapAround = this.wrapAround;
  7021. material.wrapRGB.copy( this.wrapRGB );
  7022. material.map = this.map;
  7023. material.lightMap = this.lightMap;
  7024. material.bumpMap = this.bumpMap;
  7025. material.bumpScale = this.bumpScale;
  7026. material.normalMap = this.normalMap;
  7027. material.normalScale.copy( this.normalScale );
  7028. material.specularMap = this.specularMap;
  7029. material.envMap = this.envMap;
  7030. material.combine = this.combine;
  7031. material.reflectivity = this.reflectivity;
  7032. material.refractionRatio = this.refractionRatio;
  7033. material.fog = this.fog;
  7034. material.shading = this.shading;
  7035. material.wireframe = this.wireframe;
  7036. material.wireframeLinewidth = this.wireframeLinewidth;
  7037. material.wireframeLinecap = this.wireframeLinecap;
  7038. material.wireframeLinejoin = this.wireframeLinejoin;
  7039. material.vertexColors = this.vertexColors;
  7040. material.skinning = this.skinning;
  7041. material.morphTargets = this.morphTargets;
  7042. material.morphNormals = this.morphNormals;
  7043. return material;
  7044. };
  7045. /**
  7046. * @author mrdoob / http://mrdoob.com/
  7047. * @author alteredq / http://alteredqualia.com/
  7048. *
  7049. * parameters = {
  7050. * opacity: <float>,
  7051. *
  7052. * blending: THREE.NormalBlending,
  7053. * depthTest: <bool>,
  7054. * depthWrite: <bool>,
  7055. *
  7056. * wireframe: <boolean>,
  7057. * wireframeLinewidth: <float>
  7058. * }
  7059. */
  7060. THREE.MeshDepthMaterial = function ( parameters ) {
  7061. THREE.Material.call( this );
  7062. this.wireframe = false;
  7063. this.wireframeLinewidth = 1;
  7064. this.setValues( parameters );
  7065. };
  7066. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7067. THREE.MeshDepthMaterial.prototype.clone = function () {
  7068. var material = new THREE.LineBasicMaterial();
  7069. THREE.Material.prototype.clone.call( this, material );
  7070. material.wireframe = this.wireframe;
  7071. material.wireframeLinewidth = this.wireframeLinewidth;
  7072. return material;
  7073. };
  7074. /**
  7075. * @author mrdoob / http://mrdoob.com/
  7076. *
  7077. * parameters = {
  7078. * opacity: <float>,
  7079. *
  7080. * shading: THREE.FlatShading,
  7081. * blending: THREE.NormalBlending,
  7082. * depthTest: <bool>,
  7083. * depthWrite: <bool>,
  7084. *
  7085. * wireframe: <boolean>,
  7086. * wireframeLinewidth: <float>
  7087. * }
  7088. */
  7089. THREE.MeshNormalMaterial = function ( parameters ) {
  7090. THREE.Material.call( this, parameters );
  7091. this.shading = THREE.FlatShading;
  7092. this.wireframe = false;
  7093. this.wireframeLinewidth = 1;
  7094. this.setValues( parameters );
  7095. };
  7096. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7097. THREE.MeshNormalMaterial.prototype.clone = function () {
  7098. var material = new THREE.MeshNormalMaterial();
  7099. THREE.Material.prototype.clone.call( this, material );
  7100. material.shading = this.shading;
  7101. material.wireframe = this.wireframe;
  7102. material.wireframeLinewidth = this.wireframeLinewidth;
  7103. return material;
  7104. };
  7105. /**
  7106. * @author mrdoob / http://mrdoob.com/
  7107. */
  7108. THREE.MeshFaceMaterial = function ( materials ) {
  7109. this.materials = materials instanceof Array ? materials : [];
  7110. };
  7111. THREE.MeshFaceMaterial.prototype.clone = function () {
  7112. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7113. };
  7114. /**
  7115. * @author mrdoob / http://mrdoob.com/
  7116. * @author alteredq / http://alteredqualia.com/
  7117. *
  7118. * parameters = {
  7119. * color: <hex>,
  7120. * opacity: <float>,
  7121. * map: new THREE.Texture( <Image> ),
  7122. *
  7123. * size: <float>,
  7124. *
  7125. * blending: THREE.NormalBlending,
  7126. * depthTest: <bool>,
  7127. * depthWrite: <bool>,
  7128. *
  7129. * vertexColors: <bool>,
  7130. *
  7131. * fog: <bool>
  7132. * }
  7133. */
  7134. THREE.ParticleBasicMaterial = function ( parameters ) {
  7135. THREE.Material.call( this );
  7136. this.color = new THREE.Color( 0xffffff );
  7137. this.map = null;
  7138. this.size = 1;
  7139. this.sizeAttenuation = true;
  7140. this.vertexColors = false;
  7141. this.fog = true;
  7142. this.setValues( parameters );
  7143. };
  7144. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7145. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7146. var material = new THREE.ParticleBasicMaterial();
  7147. THREE.Material.prototype.clone.call( this, material );
  7148. material.color.copy( this.color );
  7149. material.map = this.map;
  7150. material.size = this.size;
  7151. material.sizeAttenuation = this.sizeAttenuation;
  7152. material.vertexColors = this.vertexColors;
  7153. material.fog = this.fog;
  7154. return material;
  7155. };
  7156. /**
  7157. * @author mrdoob / http://mrdoob.com/
  7158. *
  7159. * parameters = {
  7160. * color: <hex>,
  7161. * program: <function>,
  7162. * opacity: <float>,
  7163. * blending: THREE.NormalBlending
  7164. * }
  7165. */
  7166. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7167. THREE.Material.call( this );
  7168. this.color = new THREE.Color( 0xffffff );
  7169. this.program = function ( context, color ) {};
  7170. this.setValues( parameters );
  7171. };
  7172. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7173. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7174. var material = new THREE.ParticleCanvasMaterial();
  7175. THREE.Material.prototype.clone.call( this, material );
  7176. material.color.copy( this.color );
  7177. material.program = this.program;
  7178. return material;
  7179. };
  7180. /**
  7181. * @author mrdoob / http://mrdoob.com/
  7182. */
  7183. THREE.ParticleDOMMaterial = function ( element ) {
  7184. this.element = element;
  7185. };
  7186. THREE.ParticleDOMMaterial.prototype.clone = function(){
  7187. return new THREE.ParticleDOMMaterial( this.element );
  7188. };
  7189. /**
  7190. * @author alteredq / http://alteredqualia.com/
  7191. *
  7192. * parameters = {
  7193. * fragmentShader: <string>,
  7194. * vertexShader: <string>,
  7195. *
  7196. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7197. *
  7198. * defines: { "label" : "value" },
  7199. *
  7200. * shading: THREE.SmoothShading,
  7201. * blending: THREE.NormalBlending,
  7202. * depthTest: <bool>,
  7203. * depthWrite: <bool>,
  7204. *
  7205. * wireframe: <boolean>,
  7206. * wireframeLinewidth: <float>,
  7207. *
  7208. * lights: <bool>,
  7209. *
  7210. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7211. *
  7212. * skinning: <bool>,
  7213. * morphTargets: <bool>,
  7214. * morphNormals: <bool>,
  7215. *
  7216. * fog: <bool>
  7217. * }
  7218. */
  7219. THREE.ShaderMaterial = function ( parameters ) {
  7220. THREE.Material.call( this );
  7221. this.fragmentShader = "void main() {}";
  7222. this.vertexShader = "void main() {}";
  7223. this.uniforms = {};
  7224. this.defines = {};
  7225. this.attributes = null;
  7226. this.shading = THREE.SmoothShading;
  7227. this.wireframe = false;
  7228. this.wireframeLinewidth = 1;
  7229. this.fog = false; // set to use scene fog
  7230. this.lights = false; // set to use scene lights
  7231. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7232. this.skinning = false; // set to use skinning attribute streams
  7233. this.morphTargets = false; // set to use morph targets
  7234. this.morphNormals = false; // set to use morph normals
  7235. this.setValues( parameters );
  7236. };
  7237. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7238. THREE.ShaderMaterial.prototype.clone = function () {
  7239. var material = new THREE.ShaderMaterial();
  7240. THREE.Material.prototype.clone.call( this, material );
  7241. material.fragmentShader = this.fragmentShader;
  7242. material.vertexShader = this.vertexShader;
  7243. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7244. material.attributes = this.attributes;
  7245. material.defines = this.defines;
  7246. material.shading = this.shading;
  7247. material.wireframe = this.wireframe;
  7248. material.wireframeLinewidth = this.wireframeLinewidth;
  7249. material.fog = this.fog;
  7250. material.lights = this.lights;
  7251. material.vertexColors = this.vertexColors;
  7252. material.skinning = this.skinning;
  7253. material.morphTargets = this.morphTargets;
  7254. material.morphNormals = this.morphNormals;
  7255. return material;
  7256. };
  7257. /**
  7258. * @author alteredq / http://alteredqualia.com/
  7259. *
  7260. * parameters = {
  7261. * color: <hex>,
  7262. * opacity: <float>,
  7263. * map: new THREE.Texture( <Image> ),
  7264. *
  7265. * blending: THREE.NormalBlending,
  7266. * depthTest: <bool>,
  7267. * depthWrite: <bool>,
  7268. *
  7269. * useScreenCoordinates: <bool>,
  7270. * sizeAttenuation: <bool>,
  7271. * scaleByViewport: <bool>,
  7272. * alignment: THREE.SpriteAlignment.center,
  7273. *
  7274. * uvOffset: new THREE.Vector2(),
  7275. * uvScale: new THREE.Vector2(),
  7276. *
  7277. * fog: <bool>
  7278. * }
  7279. */
  7280. THREE.SpriteMaterial = function ( parameters ) {
  7281. THREE.Material.call( this );
  7282. // defaults
  7283. this.color = new THREE.Color( 0xffffff );
  7284. this.map = new THREE.Texture();
  7285. this.useScreenCoordinates = true;
  7286. this.depthTest = !this.useScreenCoordinates;
  7287. this.sizeAttenuation = !this.useScreenCoordinates;
  7288. this.scaleByViewport = !this.sizeAttenuation;
  7289. this.alignment = THREE.SpriteAlignment.center.clone();
  7290. this.fog = false;
  7291. this.uvOffset = new THREE.Vector2( 0, 0 );
  7292. this.uvScale = new THREE.Vector2( 1, 1 );
  7293. // set parameters
  7294. this.setValues( parameters );
  7295. // override coupled defaults if not specified explicitly by parameters
  7296. parameters = parameters || {};
  7297. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7298. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7299. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7300. };
  7301. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7302. THREE.SpriteMaterial.prototype.clone = function () {
  7303. var material = new THREE.SpriteMaterial();
  7304. THREE.Material.prototype.clone.call( this, material );
  7305. material.color.copy( this.color );
  7306. material.map = this.map;
  7307. material.useScreenCoordinates = this.useScreenCoordinates;
  7308. material.sizeAttenuation = this.sizeAttenuation;
  7309. material.scaleByViewport = this.scaleByViewport;
  7310. material.alignment.copy( this.alignment );
  7311. material.uvOffset.copy( this.uvOffset );
  7312. material.uvScale.copy( this.uvScale );
  7313. material.fog = this.fog;
  7314. return material;
  7315. };
  7316. // Alignment enums
  7317. THREE.SpriteAlignment = {};
  7318. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7319. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7320. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7321. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7322. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7323. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7324. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7325. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7326. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7327. /**
  7328. * @author mrdoob / http://mrdoob.com/
  7329. * @author alteredq / http://alteredqualia.com/
  7330. * @author szimek / https://github.com/szimek/
  7331. */
  7332. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7333. THREE.EventDispatcher.call( this );
  7334. this.id = THREE.TextureIdCount ++;
  7335. this.name = '';
  7336. this.image = image;
  7337. this.mipmaps = [];
  7338. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7339. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7340. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7341. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7342. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7343. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7344. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7345. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7346. this.offset = new THREE.Vector2( 0, 0 );
  7347. this.repeat = new THREE.Vector2( 1, 1 );
  7348. this.generateMipmaps = true;
  7349. this.premultiplyAlpha = false;
  7350. this.flipY = true;
  7351. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7352. this.needsUpdate = false;
  7353. this.onUpdate = null;
  7354. };
  7355. THREE.Texture.prototype = {
  7356. constructor: THREE.Texture,
  7357. clone: function ( texture ) {
  7358. if ( texture === undefined ) texture = new THREE.Texture();
  7359. texture.image = this.image;
  7360. texture.mipmaps = this.mipmaps.slice(0);
  7361. texture.mapping = this.mapping;
  7362. texture.wrapS = this.wrapS;
  7363. texture.wrapT = this.wrapT;
  7364. texture.magFilter = this.magFilter;
  7365. texture.minFilter = this.minFilter;
  7366. texture.anisotropy = this.anisotropy;
  7367. texture.format = this.format;
  7368. texture.type = this.type;
  7369. texture.offset.copy( this.offset );
  7370. texture.repeat.copy( this.repeat );
  7371. texture.generateMipmaps = this.generateMipmaps;
  7372. texture.premultiplyAlpha = this.premultiplyAlpha;
  7373. texture.flipY = this.flipY;
  7374. texture.unpackAlignment = this.unpackAlignment;
  7375. return texture;
  7376. },
  7377. dispose: function () {
  7378. this.dispatchEvent( { type: 'dispose' } );
  7379. }
  7380. };
  7381. THREE.TextureIdCount = 0;
  7382. /**
  7383. * @author alteredq / http://alteredqualia.com/
  7384. */
  7385. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7386. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7387. this.image = { width: width, height: height };
  7388. this.mipmaps = mipmaps;
  7389. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7390. };
  7391. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7392. THREE.CompressedTexture.prototype.clone = function () {
  7393. var texture = new THREE.CompressedTexture();
  7394. THREE.Texture.prototype.clone.call( this, texture );
  7395. return texture;
  7396. };
  7397. /**
  7398. * @author alteredq / http://alteredqualia.com/
  7399. */
  7400. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7401. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7402. this.image = { data: data, width: width, height: height };
  7403. };
  7404. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7405. THREE.DataTexture.prototype.clone = function () {
  7406. var texture = new THREE.DataTexture();
  7407. THREE.Texture.prototype.clone.call( this, texture );
  7408. return texture;
  7409. };
  7410. /**
  7411. * @author mrdoob / http://mrdoob.com/
  7412. */
  7413. THREE.Particle = function ( material ) {
  7414. THREE.Object3D.call( this );
  7415. this.material = material;
  7416. };
  7417. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7418. THREE.Particle.prototype.clone = function ( object ) {
  7419. if ( object === undefined ) object = new THREE.Particle( this.material );
  7420. THREE.Object3D.prototype.clone.call( this, object );
  7421. return object;
  7422. };
  7423. /**
  7424. * @author alteredq / http://alteredqualia.com/
  7425. */
  7426. THREE.ParticleSystem = function ( geometry, material ) {
  7427. THREE.Object3D.call( this );
  7428. this.geometry = geometry;
  7429. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7430. this.sortParticles = false;
  7431. if ( this.geometry ) {
  7432. // calc bound radius
  7433. if( this.geometry.boundingSphere === null ) {
  7434. this.geometry.computeBoundingSphere();
  7435. }
  7436. }
  7437. this.frustumCulled = false;
  7438. };
  7439. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7440. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7441. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7442. object.sortParticles = this.sortParticles;
  7443. THREE.Object3D.prototype.clone.call( this, object );
  7444. return object;
  7445. };
  7446. /**
  7447. * @author mrdoob / http://mrdoob.com/
  7448. */
  7449. THREE.Line = function ( geometry, material, type ) {
  7450. THREE.Object3D.call( this );
  7451. this.geometry = geometry;
  7452. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7453. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7454. if ( this.geometry ) {
  7455. if ( ! this.geometry.boundingSphere ) {
  7456. this.geometry.computeBoundingSphere();
  7457. }
  7458. }
  7459. };
  7460. THREE.LineStrip = 0;
  7461. THREE.LinePieces = 1;
  7462. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7463. THREE.Line.prototype.clone = function ( object ) {
  7464. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7465. THREE.Object3D.prototype.clone.call( this, object );
  7466. return object;
  7467. };
  7468. /**
  7469. * @author mrdoob / http://mrdoob.com/
  7470. * @author alteredq / http://alteredqualia.com/
  7471. * @author mikael emtinger / http://gomo.se/
  7472. */
  7473. THREE.Mesh = function ( geometry, material ) {
  7474. THREE.Object3D.call( this );
  7475. this.geometry = geometry;
  7476. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7477. if ( this.geometry ) {
  7478. // calc bound radius
  7479. if ( this.geometry.boundingSphere === null ) {
  7480. this.geometry.computeBoundingSphere();
  7481. }
  7482. // setup morph targets
  7483. if ( this.geometry.morphTargets.length ) {
  7484. this.morphTargetBase = -1;
  7485. this.morphTargetForcedOrder = [];
  7486. this.morphTargetInfluences = [];
  7487. this.morphTargetDictionary = {};
  7488. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  7489. this.morphTargetInfluences.push( 0 );
  7490. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7491. }
  7492. }
  7493. }
  7494. }
  7495. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7496. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7497. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7498. return this.morphTargetDictionary[ name ];
  7499. }
  7500. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7501. return 0;
  7502. };
  7503. THREE.Mesh.prototype.clone = function ( object ) {
  7504. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7505. THREE.Object3D.prototype.clone.call( this, object );
  7506. return object;
  7507. };
  7508. /**
  7509. * @author mikael emtinger / http://gomo.se/
  7510. * @author alteredq / http://alteredqualia.com/
  7511. */
  7512. THREE.Bone = function( belongsToSkin ) {
  7513. THREE.Object3D.call( this );
  7514. this.skin = belongsToSkin;
  7515. this.skinMatrix = new THREE.Matrix4();
  7516. };
  7517. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7518. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  7519. // update local
  7520. if ( this.matrixAutoUpdate ) {
  7521. forceUpdate |= this.updateMatrix();
  7522. }
  7523. // update skin matrix
  7524. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7525. if( parentSkinMatrix ) {
  7526. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  7527. } else {
  7528. this.skinMatrix.copy( this.matrix );
  7529. }
  7530. this.matrixWorldNeedsUpdate = false;
  7531. forceUpdate = true;
  7532. }
  7533. // update children
  7534. var child, i, l = this.children.length;
  7535. for ( i = 0; i < l; i ++ ) {
  7536. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7537. }
  7538. };
  7539. /**
  7540. * @author mikael emtinger / http://gomo.se/
  7541. * @author alteredq / http://alteredqualia.com/
  7542. */
  7543. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7544. THREE.Mesh.call( this, geometry, material );
  7545. //
  7546. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7547. // init bones
  7548. this.identityMatrix = new THREE.Matrix4();
  7549. this.bones = [];
  7550. this.boneMatrices = [];
  7551. var b, bone, gbone, p, q, s;
  7552. if ( this.geometry && this.geometry.bones !== undefined ) {
  7553. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7554. gbone = this.geometry.bones[ b ];
  7555. p = gbone.pos;
  7556. q = gbone.rotq;
  7557. s = gbone.scl;
  7558. bone = this.addBone();
  7559. bone.name = gbone.name;
  7560. bone.position.set( p[0], p[1], p[2] );
  7561. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7562. bone.useQuaternion = true;
  7563. if ( s !== undefined ) {
  7564. bone.scale.set( s[0], s[1], s[2] );
  7565. } else {
  7566. bone.scale.set( 1, 1, 1 );
  7567. }
  7568. }
  7569. for ( b = 0; b < this.bones.length; b ++ ) {
  7570. gbone = this.geometry.bones[ b ];
  7571. bone = this.bones[ b ];
  7572. if ( gbone.parent === -1 ) {
  7573. this.add( bone );
  7574. } else {
  7575. this.bones[ gbone.parent ].add( bone );
  7576. }
  7577. }
  7578. //
  7579. var nBones = this.bones.length;
  7580. if ( this.useVertexTexture ) {
  7581. // layout (1 matrix = 4 pixels)
  7582. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7583. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7584. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7585. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7586. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7587. var size;
  7588. if ( nBones > 256 )
  7589. size = 64;
  7590. else if ( nBones > 64 )
  7591. size = 32;
  7592. else if ( nBones > 16 )
  7593. size = 16;
  7594. else
  7595. size = 8;
  7596. this.boneTextureWidth = size;
  7597. this.boneTextureHeight = size;
  7598. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7599. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7600. this.boneTexture.minFilter = THREE.NearestFilter;
  7601. this.boneTexture.magFilter = THREE.NearestFilter;
  7602. this.boneTexture.generateMipmaps = false;
  7603. this.boneTexture.flipY = false;
  7604. } else {
  7605. this.boneMatrices = new Float32Array( 16 * nBones );
  7606. }
  7607. this.pose();
  7608. }
  7609. };
  7610. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7611. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7612. if ( bone === undefined ) {
  7613. bone = new THREE.Bone( this );
  7614. }
  7615. this.bones.push( bone );
  7616. return bone;
  7617. };
  7618. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7619. this.matrixAutoUpdate && this.updateMatrix();
  7620. // update matrixWorld
  7621. if ( this.matrixWorldNeedsUpdate || force ) {
  7622. if ( this.parent ) {
  7623. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  7624. } else {
  7625. this.matrixWorld.copy( this.matrix );
  7626. }
  7627. this.matrixWorldNeedsUpdate = false;
  7628. force = true;
  7629. }
  7630. // update children
  7631. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7632. var child = this.children[ i ];
  7633. if ( child instanceof THREE.Bone ) {
  7634. child.update( this.identityMatrix, false );
  7635. } else {
  7636. child.updateMatrixWorld( true );
  7637. }
  7638. }
  7639. // make a snapshot of the bones' rest position
  7640. if ( this.boneInverses == undefined ) {
  7641. this.boneInverses = [];
  7642. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7643. var inverse = new THREE.Matrix4();
  7644. inverse.getInverse( this.bones[ b ].skinMatrix );
  7645. this.boneInverses.push( inverse );
  7646. }
  7647. }
  7648. // flatten bone matrices to array
  7649. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7650. // compute the offset between the current and the original transform;
  7651. //TODO: we could get rid of this multiplication step if the skinMatrix
  7652. // was already representing the offset; however, this requires some
  7653. // major changes to the animation system
  7654. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7655. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7656. }
  7657. if ( this.useVertexTexture ) {
  7658. this.boneTexture.needsUpdate = true;
  7659. }
  7660. };
  7661. THREE.SkinnedMesh.prototype.pose = function() {
  7662. this.updateMatrixWorld( true );
  7663. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7664. // normalize weights
  7665. var sw = this.geometry.skinWeights[ i ];
  7666. var scale = 1.0 / sw.lengthManhattan();
  7667. if ( scale !== Infinity ) {
  7668. sw.multiplyScalar( scale );
  7669. } else {
  7670. sw.set( 1 ); // this will be normalized by the shader anyway
  7671. }
  7672. }
  7673. };
  7674. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7675. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7676. THREE.Mesh.prototype.clone.call( this, object );
  7677. return object;
  7678. };
  7679. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7680. /**
  7681. * @author alteredq / http://alteredqualia.com/
  7682. */
  7683. THREE.MorphAnimMesh = function ( geometry, material ) {
  7684. THREE.Mesh.call( this, geometry, material );
  7685. // API
  7686. this.duration = 1000; // milliseconds
  7687. this.mirroredLoop = false;
  7688. this.time = 0;
  7689. // internals
  7690. this.lastKeyframe = 0;
  7691. this.currentKeyframe = 0;
  7692. this.direction = 1;
  7693. this.directionBackwards = false;
  7694. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7695. };
  7696. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7697. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7698. this.startKeyframe = start;
  7699. this.endKeyframe = end;
  7700. this.length = this.endKeyframe - this.startKeyframe + 1;
  7701. };
  7702. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7703. this.direction = 1;
  7704. this.directionBackwards = false;
  7705. };
  7706. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7707. this.direction = -1;
  7708. this.directionBackwards = true;
  7709. };
  7710. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7711. var geometry = this.geometry;
  7712. if ( ! geometry.animations ) geometry.animations = {};
  7713. var firstAnimation, animations = geometry.animations;
  7714. var pattern = /([a-z]+)(\d+)/;
  7715. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7716. var morph = geometry.morphTargets[ i ];
  7717. var parts = morph.name.match( pattern );
  7718. if ( parts && parts.length > 1 ) {
  7719. var label = parts[ 1 ];
  7720. var num = parts[ 2 ];
  7721. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7722. var animation = animations[ label ];
  7723. if ( i < animation.start ) animation.start = i;
  7724. if ( i > animation.end ) animation.end = i;
  7725. if ( ! firstAnimation ) firstAnimation = label;
  7726. }
  7727. }
  7728. geometry.firstAnimation = firstAnimation;
  7729. };
  7730. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7731. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7732. this.geometry.animations[ label ] = { start: start, end: end };
  7733. };
  7734. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7735. var animation = this.geometry.animations[ label ];
  7736. if ( animation ) {
  7737. this.setFrameRange( animation.start, animation.end );
  7738. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7739. this.time = 0;
  7740. } else {
  7741. console.warn( "animation[" + label + "] undefined" );
  7742. }
  7743. };
  7744. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7745. var frameTime = this.duration / this.length;
  7746. this.time += this.direction * delta;
  7747. if ( this.mirroredLoop ) {
  7748. if ( this.time > this.duration || this.time < 0 ) {
  7749. this.direction *= -1;
  7750. if ( this.time > this.duration ) {
  7751. this.time = this.duration;
  7752. this.directionBackwards = true;
  7753. }
  7754. if ( this.time < 0 ) {
  7755. this.time = 0;
  7756. this.directionBackwards = false;
  7757. }
  7758. }
  7759. } else {
  7760. this.time = this.time % this.duration;
  7761. if ( this.time < 0 ) this.time += this.duration;
  7762. }
  7763. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7764. if ( keyframe !== this.currentKeyframe ) {
  7765. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7766. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7767. this.morphTargetInfluences[ keyframe ] = 0;
  7768. this.lastKeyframe = this.currentKeyframe;
  7769. this.currentKeyframe = keyframe;
  7770. }
  7771. var mix = ( this.time % frameTime ) / frameTime;
  7772. if ( this.directionBackwards ) {
  7773. mix = 1 - mix;
  7774. }
  7775. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7776. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7777. };
  7778. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7779. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7780. object.duration = this.duration;
  7781. object.mirroredLoop = this.mirroredLoop;
  7782. object.time = this.time;
  7783. object.lastKeyframe = this.lastKeyframe;
  7784. object.currentKeyframe = this.currentKeyframe;
  7785. object.direction = this.direction;
  7786. object.directionBackwards = this.directionBackwards;
  7787. THREE.Mesh.prototype.clone.call( this, object );
  7788. return object;
  7789. };
  7790. /**
  7791. * @author alteredq / http://alteredqualia.com/
  7792. */
  7793. THREE.Ribbon = function ( geometry, material ) {
  7794. THREE.Object3D.call( this );
  7795. this.geometry = geometry;
  7796. this.material = material;
  7797. };
  7798. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7799. THREE.Ribbon.prototype.clone = function ( object ) {
  7800. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7801. THREE.Object3D.prototype.clone.call( this, object );
  7802. return object;
  7803. };
  7804. /**
  7805. * @author mikael emtinger / http://gomo.se/
  7806. * @author alteredq / http://alteredqualia.com/
  7807. * @author mrdoob / http://mrdoob.com/
  7808. */
  7809. THREE.LOD = function () {
  7810. THREE.Object3D.call( this );
  7811. this.LODs = [];
  7812. };
  7813. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7814. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7815. if ( visibleAtDistance === undefined ) {
  7816. visibleAtDistance = 0;
  7817. }
  7818. visibleAtDistance = Math.abs( visibleAtDistance );
  7819. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7820. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7821. break;
  7822. }
  7823. }
  7824. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7825. this.add( object3D );
  7826. };
  7827. THREE.LOD.prototype.update = function ( camera ) {
  7828. if ( this.LODs.length > 1 ) {
  7829. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7830. var inverse = camera.matrixWorldInverse;
  7831. 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] );
  7832. this.LODs[ 0 ].object3D.visible = true;
  7833. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7834. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7835. this.LODs[ l - 1 ].object3D.visible = false;
  7836. this.LODs[ l ].object3D.visible = true;
  7837. } else {
  7838. break;
  7839. }
  7840. }
  7841. for( ; l < this.LODs.length; l ++ ) {
  7842. this.LODs[ l ].object3D.visible = false;
  7843. }
  7844. }
  7845. };
  7846. THREE.LOD.prototype.clone = function () {
  7847. // TODO
  7848. };
  7849. /**
  7850. * @author mikael emtinger / http://gomo.se/
  7851. * @author alteredq / http://alteredqualia.com/
  7852. */
  7853. THREE.Sprite = function ( material ) {
  7854. THREE.Object3D.call( this );
  7855. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7856. this.rotation3d = this.rotation;
  7857. this.rotation = 0;
  7858. };
  7859. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7860. /*
  7861. * Custom update matrix
  7862. */
  7863. THREE.Sprite.prototype.updateMatrix = function () {
  7864. this.matrix.setPosition( this.position );
  7865. this.rotation3d.set( 0, 0, this.rotation );
  7866. this.matrix.setRotationFromEuler( this.rotation3d );
  7867. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7868. this.matrix.scale( this.scale );
  7869. }
  7870. this.matrixWorldNeedsUpdate = true;
  7871. };
  7872. THREE.Sprite.prototype.clone = function ( object ) {
  7873. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7874. THREE.Object3D.prototype.clone.call( this, object );
  7875. return object;
  7876. };
  7877. /**
  7878. * @author mrdoob / http://mrdoob.com/
  7879. */
  7880. THREE.Scene = function () {
  7881. THREE.Object3D.call( this );
  7882. this.fog = null;
  7883. this.overrideMaterial = null;
  7884. this.matrixAutoUpdate = false;
  7885. this.__objects = [];
  7886. this.__lights = [];
  7887. this.__objectsAdded = [];
  7888. this.__objectsRemoved = [];
  7889. };
  7890. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7891. THREE.Scene.prototype.__addObject = function ( object ) {
  7892. if ( object instanceof THREE.Light ) {
  7893. if ( this.__lights.indexOf( object ) === - 1 ) {
  7894. this.__lights.push( object );
  7895. }
  7896. if ( object.target && object.target.parent === undefined ) {
  7897. this.add( object.target );
  7898. }
  7899. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7900. if ( this.__objects.indexOf( object ) === - 1 ) {
  7901. this.__objects.push( object );
  7902. this.__objectsAdded.push( object );
  7903. // check if previously removed
  7904. var i = this.__objectsRemoved.indexOf( object );
  7905. if ( i !== -1 ) {
  7906. this.__objectsRemoved.splice( i, 1 );
  7907. }
  7908. }
  7909. }
  7910. for ( var c = 0; c < object.children.length; c ++ ) {
  7911. this.__addObject( object.children[ c ] );
  7912. }
  7913. };
  7914. THREE.Scene.prototype.__removeObject = function ( object ) {
  7915. if ( object instanceof THREE.Light ) {
  7916. var i = this.__lights.indexOf( object );
  7917. if ( i !== -1 ) {
  7918. this.__lights.splice( i, 1 );
  7919. }
  7920. } else if ( !( object instanceof THREE.Camera ) ) {
  7921. var i = this.__objects.indexOf( object );
  7922. if( i !== -1 ) {
  7923. this.__objects.splice( i, 1 );
  7924. this.__objectsRemoved.push( object );
  7925. // check if previously added
  7926. var ai = this.__objectsAdded.indexOf( object );
  7927. if ( ai !== -1 ) {
  7928. this.__objectsAdded.splice( ai, 1 );
  7929. }
  7930. }
  7931. }
  7932. for ( var c = 0; c < object.children.length; c ++ ) {
  7933. this.__removeObject( object.children[ c ] );
  7934. }
  7935. };
  7936. /**
  7937. * @author mrdoob / http://mrdoob.com/
  7938. * @author alteredq / http://alteredqualia.com/
  7939. */
  7940. THREE.Fog = function ( hex, near, far ) {
  7941. this.name = '';
  7942. this.color = new THREE.Color( hex );
  7943. this.near = ( near !== undefined ) ? near : 1;
  7944. this.far = ( far !== undefined ) ? far : 1000;
  7945. };
  7946. THREE.Fog.prototype.clone = function () {
  7947. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7948. };
  7949. /**
  7950. * @author mrdoob / http://mrdoob.com/
  7951. * @author alteredq / http://alteredqualia.com/
  7952. */
  7953. THREE.FogExp2 = function ( hex, density ) {
  7954. this.name = '';
  7955. this.color = new THREE.Color( hex );
  7956. this.density = ( density !== undefined ) ? density : 0.00025;
  7957. };
  7958. THREE.FogExp2.prototype.clone = function () {
  7959. return new THREE.FogExp2( this.color.getHex(), this.density );
  7960. };
  7961. /**
  7962. * @author mrdoob / http://mrdoob.com/
  7963. */
  7964. THREE.CanvasRenderer = function ( parameters ) {
  7965. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7966. parameters = parameters || {};
  7967. var _this = this,
  7968. _renderData, _elements, _lights,
  7969. _projector = new THREE.Projector(),
  7970. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  7971. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7972. _context = _canvas.getContext( '2d' ),
  7973. _clearColor = new THREE.Color( 0x000000 ),
  7974. _clearOpacity = 0,
  7975. _contextGlobalAlpha = 1,
  7976. _contextGlobalCompositeOperation = 0,
  7977. _contextStrokeStyle = null,
  7978. _contextFillStyle = null,
  7979. _contextLineWidth = null,
  7980. _contextLineCap = null,
  7981. _contextLineJoin = null,
  7982. _v1, _v2, _v3, _v4,
  7983. _v5 = new THREE.RenderableVertex(),
  7984. _v6 = new THREE.RenderableVertex(),
  7985. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7986. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7987. _color = new THREE.Color(),
  7988. _color1 = new THREE.Color(),
  7989. _color2 = new THREE.Color(),
  7990. _color3 = new THREE.Color(),
  7991. _color4 = new THREE.Color(),
  7992. _diffuseColor = new THREE.Color(),
  7993. _emissiveColor = new THREE.Color(),
  7994. _patterns = {}, _imagedatas = {},
  7995. _near, _far,
  7996. _image, _uvs,
  7997. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7998. _clipBox = new THREE.Box2(),
  7999. _clearBox = new THREE.Box2(),
  8000. _elemBox = new THREE.Box2(),
  8001. _enableLighting = false,
  8002. _ambientLight = new THREE.Color(),
  8003. _directionalLights = new THREE.Color(),
  8004. _pointLights = new THREE.Color(),
  8005. _pi2 = Math.PI * 2,
  8006. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8007. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8008. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8009. _pixelMap = document.createElement( 'canvas' );
  8010. _pixelMap.width = _pixelMap.height = 2;
  8011. _pixelMapContext = _pixelMap.getContext( '2d' );
  8012. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8013. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8014. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8015. _pixelMapData = _pixelMapImage.data;
  8016. _gradientMap = document.createElement( 'canvas' );
  8017. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8018. _gradientMapContext = _gradientMap.getContext( '2d' );
  8019. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8020. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8021. _gradientMapQuality --; // Fix UVs
  8022. this.domElement = _canvas;
  8023. this.autoClear = true;
  8024. this.sortObjects = true;
  8025. this.sortElements = true;
  8026. this.info = {
  8027. render: {
  8028. vertices: 0,
  8029. faces: 0
  8030. }
  8031. }
  8032. this.setSize = function ( width, height ) {
  8033. _canvasWidth = width;
  8034. _canvasHeight = height;
  8035. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8036. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8037. _canvas.width = _canvasWidth;
  8038. _canvas.height = _canvasHeight;
  8039. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8040. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8041. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8042. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8043. _contextGlobalAlpha = 1;
  8044. _contextGlobalCompositeOperation = 0;
  8045. _contextStrokeStyle = null;
  8046. _contextFillStyle = null;
  8047. _contextLineWidth = null;
  8048. _contextLineCap = null;
  8049. _contextLineJoin = null;
  8050. };
  8051. this.setClearColor = function ( color, opacity ) {
  8052. _clearColor.copy( color );
  8053. _clearOpacity = opacity !== undefined ? opacity : 1;
  8054. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8055. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8056. };
  8057. this.setClearColorHex = function ( hex, opacity ) {
  8058. _clearColor.setHex( hex );
  8059. _clearOpacity = opacity !== undefined ? opacity : 1;
  8060. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8061. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8062. };
  8063. this.getMaxAnisotropy = function () {
  8064. return 0;
  8065. };
  8066. this.clear = function () {
  8067. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8068. if ( _clearBox.empty() === false ) {
  8069. _clearBox.intersect( _clipBox );
  8070. _clearBox.expandByScalar( 2 );
  8071. if ( _clearOpacity < 1 ) {
  8072. _context.clearRect( _clearBox.min.x | 0, _clearBox.min.y | 0, ( _clearBox.max.x - _clearBox.min.x ) | 0, ( _clearBox.max.y - _clearBox.min.y ) | 0 );
  8073. }
  8074. if ( _clearOpacity > 0 ) {
  8075. setBlending( THREE.NormalBlending );
  8076. setOpacity( 1 );
  8077. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  8078. _context.fillRect( _clearBox.min.x | 0, _clearBox.min.y | 0, ( _clearBox.max.x - _clearBox.min.x ) | 0, ( _clearBox.max.y - _clearBox.min.y ) | 0 );
  8079. }
  8080. _clearBox.makeEmpty();
  8081. }
  8082. };
  8083. this.render = function ( scene, camera ) {
  8084. if ( camera instanceof THREE.Camera === false ) {
  8085. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8086. return;
  8087. }
  8088. var e, el, element, material;
  8089. this.autoClear === true
  8090. ? this.clear()
  8091. : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8092. _this.info.render.vertices = 0;
  8093. _this.info.render.faces = 0;
  8094. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8095. _elements = _renderData.elements;
  8096. _lights = _renderData.lights;
  8097. /* DEBUG
  8098. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  8099. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8100. */
  8101. _enableLighting = _lights.length > 0;
  8102. if ( _enableLighting === true ) {
  8103. calculateLights();
  8104. }
  8105. for ( e = 0, el = _elements.length; e < el; e++ ) {
  8106. element = _elements[ e ];
  8107. material = element.material;
  8108. if ( material === undefined || material.visible === false ) continue;
  8109. _elemBox.makeEmpty();
  8110. if ( element instanceof THREE.RenderableParticle ) {
  8111. _v1 = element;
  8112. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8113. renderParticle( _v1, element, material, scene );
  8114. } else if ( element instanceof THREE.RenderableLine ) {
  8115. _v1 = element.v1; _v2 = element.v2;
  8116. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8117. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8118. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] );
  8119. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8120. renderLine( _v1, _v2, element, material, scene );
  8121. }
  8122. } else if ( element instanceof THREE.RenderableFace3 ) {
  8123. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8124. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8125. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8126. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8127. if ( material.overdraw === true ) {
  8128. expand( _v1.positionScreen, _v2.positionScreen );
  8129. expand( _v2.positionScreen, _v3.positionScreen );
  8130. expand( _v3.positionScreen, _v1.positionScreen );
  8131. }
  8132. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen ] );
  8133. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8134. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  8135. }
  8136. } else if ( element instanceof THREE.RenderableFace4 ) {
  8137. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8138. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8139. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8140. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8141. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8142. _v5.positionScreen.copy( _v2.positionScreen );
  8143. _v6.positionScreen.copy( _v4.positionScreen );
  8144. if ( material.overdraw === true ) {
  8145. expand( _v1.positionScreen, _v2.positionScreen );
  8146. expand( _v2.positionScreen, _v4.positionScreen );
  8147. expand( _v4.positionScreen, _v1.positionScreen );
  8148. expand( _v3.positionScreen, _v5.positionScreen );
  8149. expand( _v3.positionScreen, _v6.positionScreen );
  8150. }
  8151. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen, _v4.positionScreen ] );
  8152. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8153. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  8154. }
  8155. }
  8156. /* DEBUG
  8157. _context.lineWidth = 1;
  8158. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  8159. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8160. */
  8161. _clearBox.union( _elemBox );
  8162. }
  8163. /* DEBUG
  8164. _context.lineWidth = 1;
  8165. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  8166. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8167. */
  8168. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8169. //
  8170. function calculateLights() {
  8171. _ambientLight.setRGB( 0, 0, 0 );
  8172. _directionalLights.setRGB( 0, 0, 0 );
  8173. _pointLights.setRGB( 0, 0, 0 );
  8174. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8175. var light = _lights[ l ];
  8176. var lightColor = light.color;
  8177. if ( light instanceof THREE.AmbientLight ) {
  8178. _ambientLight.r += lightColor.r;
  8179. _ambientLight.g += lightColor.g;
  8180. _ambientLight.b += lightColor.b;
  8181. } else if ( light instanceof THREE.DirectionalLight ) {
  8182. // for particles
  8183. _directionalLights.r += lightColor.r;
  8184. _directionalLights.g += lightColor.g;
  8185. _directionalLights.b += lightColor.b;
  8186. } else if ( light instanceof THREE.PointLight ) {
  8187. // for particles
  8188. _pointLights.r += lightColor.r;
  8189. _pointLights.g += lightColor.g;
  8190. _pointLights.b += lightColor.b;
  8191. }
  8192. }
  8193. }
  8194. function calculateLight( position, normal, color ) {
  8195. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8196. var light = _lights[ l ];
  8197. var lightColor = light.color;
  8198. if ( light instanceof THREE.DirectionalLight ) {
  8199. var lightPosition = light.matrixWorld.getPosition().normalize();
  8200. var amount = normal.dot( lightPosition );
  8201. if ( amount <= 0 ) continue;
  8202. amount *= light.intensity;
  8203. color.r += lightColor.r * amount;
  8204. color.g += lightColor.g * amount;
  8205. color.b += lightColor.b * amount;
  8206. } else if ( light instanceof THREE.PointLight ) {
  8207. var lightPosition = light.matrixWorld.getPosition();
  8208. var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  8209. if ( amount <= 0 ) continue;
  8210. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8211. if ( amount == 0 ) continue;
  8212. amount *= light.intensity;
  8213. color.r += lightColor.r * amount;
  8214. color.g += lightColor.g * amount;
  8215. color.b += lightColor.b * amount;
  8216. }
  8217. }
  8218. }
  8219. function renderParticle( v1, element, material, scene ) {
  8220. setOpacity( material.opacity );
  8221. setBlending( material.blending );
  8222. var width, height, scaleX, scaleY,
  8223. bitmap, bitmapWidth, bitmapHeight;
  8224. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8225. if ( material.map === null ) {
  8226. scaleX = element.object.scale.x;
  8227. scaleY = element.object.scale.y;
  8228. // TODO: Be able to disable this
  8229. scaleX *= element.scale.x * _canvasWidthHalf;
  8230. scaleY *= element.scale.y * _canvasHeightHalf;
  8231. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8232. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8233. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8234. return;
  8235. }
  8236. setFillStyle( material.color.getStyle() );
  8237. _context.save();
  8238. _context.translate( v1.x, v1.y );
  8239. _context.rotate( - element.rotation );
  8240. _context.scale( scaleX, scaleY );
  8241. _context.fillRect( -1, -1, 2, 2 );
  8242. _context.restore();
  8243. } else {
  8244. bitmap = material.map.image;
  8245. bitmapWidth = bitmap.width >> 1;
  8246. bitmapHeight = bitmap.height >> 1;
  8247. scaleX = element.scale.x * _canvasWidthHalf;
  8248. scaleY = element.scale.y * _canvasHeightHalf;
  8249. width = scaleX * bitmapWidth;
  8250. height = scaleY * bitmapHeight;
  8251. // TODO: Rotations break this...
  8252. _elemBox.min.set( v1.x - width, v1.y - height );
  8253. _elemBox.max.set( v1.x + width, v1.y + height );
  8254. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8255. return;
  8256. }
  8257. _context.save();
  8258. _context.translate( v1.x, v1.y );
  8259. _context.rotate( - element.rotation );
  8260. _context.scale( scaleX, - scaleY );
  8261. _context.translate( - bitmapWidth, - bitmapHeight );
  8262. _context.drawImage( bitmap, 0, 0 );
  8263. _context.restore();
  8264. }
  8265. /* DEBUG
  8266. setStrokeStyle( 'rgb(255,255,0)' );
  8267. _context.beginPath();
  8268. _context.moveTo( v1.x - 10, v1.y );
  8269. _context.lineTo( v1.x + 10, v1.y );
  8270. _context.moveTo( v1.x, v1.y - 10 );
  8271. _context.lineTo( v1.x, v1.y + 10 );
  8272. _context.stroke();
  8273. */
  8274. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8275. width = element.scale.x * _canvasWidthHalf;
  8276. height = element.scale.y * _canvasHeightHalf;
  8277. _elemBox.min.set( v1.x - width, v1.y - height );
  8278. _elemBox.max.set( v1.x + width, v1.y + height );
  8279. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8280. return;
  8281. }
  8282. setStrokeStyle( material.color.getStyle() );
  8283. setFillStyle( material.color.getStyle() );
  8284. _context.save();
  8285. _context.translate( v1.x, v1.y );
  8286. _context.rotate( - element.rotation );
  8287. _context.scale( width, height );
  8288. material.program( _context );
  8289. _context.restore();
  8290. }
  8291. }
  8292. function renderLine( v1, v2, element, material, scene ) {
  8293. setOpacity( material.opacity );
  8294. setBlending( material.blending );
  8295. _context.beginPath();
  8296. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8297. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8298. if ( material instanceof THREE.LineBasicMaterial ) {
  8299. setLineWidth( material.linewidth );
  8300. setLineCap( material.linecap );
  8301. setLineJoin( material.linejoin );
  8302. setStrokeStyle( material.color.getStyle() );
  8303. _context.stroke();
  8304. _elemBox.expandByScalar( material.linewidth * 2 );
  8305. }
  8306. }
  8307. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  8308. _this.info.render.vertices += 3;
  8309. _this.info.render.faces ++;
  8310. setOpacity( material.opacity );
  8311. setBlending( material.blending );
  8312. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8313. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8314. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8315. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8316. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  8317. _diffuseColor.copy( material.color );
  8318. _emissiveColor.copy( material.emissive );
  8319. if ( material.vertexColors === THREE.FaceColors ) {
  8320. _diffuseColor.r *= element.color.r;
  8321. _diffuseColor.g *= element.color.g;
  8322. _diffuseColor.b *= element.color.b;
  8323. }
  8324. if ( _enableLighting === true ) {
  8325. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8326. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  8327. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  8328. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  8329. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  8330. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  8331. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  8332. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  8333. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  8334. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  8335. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  8336. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  8337. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  8338. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  8339. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  8340. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  8341. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  8342. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  8343. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  8344. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8345. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8346. } else {
  8347. _color.r = _ambientLight.r;
  8348. _color.g = _ambientLight.g;
  8349. _color.b = _ambientLight.b;
  8350. calculateLight( element.centroidWorld, element.normalWorld, _color );
  8351. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  8352. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  8353. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  8354. material.wireframe === true
  8355. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8356. : fillPath( _color );
  8357. }
  8358. } else {
  8359. material.wireframe === true
  8360. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8361. : fillPath( material.color );
  8362. }
  8363. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8364. if ( material.map !== null ) {
  8365. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8366. _uvs = element.uvs[ 0 ];
  8367. 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 );
  8368. }
  8369. } else if ( material.envMap !== null ) {
  8370. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8371. var cameraMatrix = camera.matrixWorldInverse;
  8372. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  8373. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  8374. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  8375. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  8376. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  8377. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  8378. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  8379. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  8380. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  8381. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8382. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8383. }*/
  8384. } else {
  8385. _color.copy( material.color );
  8386. if ( material.vertexColors === THREE.FaceColors ) {
  8387. _color.r *= element.color.r;
  8388. _color.g *= element.color.g;
  8389. _color.b *= element.color.b;
  8390. }
  8391. material.wireframe === true
  8392. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8393. : fillPath( _color );
  8394. }
  8395. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8396. _near = camera.near;
  8397. _far = camera.far;
  8398. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8399. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  8400. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8401. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  8402. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  8403. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  8404. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8405. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8406. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8407. _color.r = normalToComponent( element.normalWorld.x );
  8408. _color.g = normalToComponent( element.normalWorld.y );
  8409. _color.b = normalToComponent( element.normalWorld.z );
  8410. material.wireframe === true
  8411. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8412. : fillPath( _color );
  8413. }
  8414. }
  8415. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  8416. _this.info.render.vertices += 4;
  8417. _this.info.render.faces ++;
  8418. setOpacity( material.opacity );
  8419. setBlending( material.blending );
  8420. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8421. // Let renderFace3() handle this
  8422. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  8423. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  8424. return;
  8425. }
  8426. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8427. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8428. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8429. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8430. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8431. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8432. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8433. _diffuseColor.copy( material.color );
  8434. _emissiveColor.copy( material.emissive );
  8435. if ( material.vertexColors === THREE.FaceColors ) {
  8436. _diffuseColor.r *= element.color.r;
  8437. _diffuseColor.g *= element.color.g;
  8438. _diffuseColor.b *= element.color.b;
  8439. }
  8440. if ( _enableLighting === true ) {
  8441. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8442. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  8443. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  8444. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  8445. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  8446. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  8447. calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  8448. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  8449. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  8450. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  8451. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  8452. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  8453. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  8454. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  8455. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  8456. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  8457. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  8458. _color4.r = _color4.r * _diffuseColor.r + _emissiveColor.r;
  8459. _color4.g = _color4.g * _diffuseColor.g + _emissiveColor.g;
  8460. _color4.b = _color4.b * _diffuseColor.b + _emissiveColor.b;
  8461. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8462. // TODO: UVs are incorrect, v4->v3?
  8463. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8464. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8465. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8466. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8467. } else {
  8468. _color.r = _ambientLight.r;
  8469. _color.g = _ambientLight.g;
  8470. _color.b = _ambientLight.b;
  8471. calculateLight( element.centroidWorld, element.normalWorld, _color );
  8472. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  8473. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  8474. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  8475. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8476. material.wireframe === true
  8477. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8478. : fillPath( _color );
  8479. }
  8480. } else {
  8481. _color.r = _diffuseColor.r + _emissiveColor.r;
  8482. _color.g = _diffuseColor.g + _emissiveColor.g;
  8483. _color.b = _diffuseColor.b + _emissiveColor.b;
  8484. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8485. material.wireframe === true
  8486. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8487. : fillPath( _color );
  8488. }
  8489. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8490. _color.copy( material.color );
  8491. if ( material.vertexColors === THREE.FaceColors ) {
  8492. _color.r *= element.color.r;
  8493. _color.g *= element.color.g;
  8494. _color.b *= element.color.b;
  8495. }
  8496. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8497. material.wireframe === true
  8498. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8499. : fillPath( _color );
  8500. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8501. _color.r = normalToComponent( element.normalWorld.x );
  8502. _color.g = normalToComponent( element.normalWorld.y );
  8503. _color.b = normalToComponent( element.normalWorld.z );
  8504. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8505. material.wireframe === true
  8506. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8507. : fillPath( _color );
  8508. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8509. _near = camera.near;
  8510. _far = camera.far;
  8511. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8512. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  8513. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  8514. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8515. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8516. // TODO: UVs are incorrect, v4->v3?
  8517. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8518. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8519. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8520. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8521. }
  8522. }
  8523. //
  8524. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8525. _context.beginPath();
  8526. _context.moveTo( x0, y0 );
  8527. _context.lineTo( x1, y1 );
  8528. _context.lineTo( x2, y2 );
  8529. _context.closePath();
  8530. }
  8531. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8532. _context.beginPath();
  8533. _context.moveTo( x0, y0 );
  8534. _context.lineTo( x1, y1 );
  8535. _context.lineTo( x2, y2 );
  8536. _context.lineTo( x3, y3 );
  8537. _context.closePath();
  8538. }
  8539. function strokePath( color, linewidth, linecap, linejoin ) {
  8540. setLineWidth( linewidth );
  8541. setLineCap( linecap );
  8542. setLineJoin( linejoin );
  8543. setStrokeStyle( color.getStyle() );
  8544. _context.stroke();
  8545. _elemBox.expandByScalar( linewidth * 2 );
  8546. }
  8547. function fillPath( color ) {
  8548. setFillStyle( color.getStyle() );
  8549. _context.fill();
  8550. }
  8551. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8552. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8553. if ( texture.needsUpdate === true ) {
  8554. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8555. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8556. _patterns[ texture.id ] = _context.createPattern(
  8557. texture.image, repeatX === true && repeatY === true
  8558. ? 'repeat'
  8559. : repeatX === true && repeatY === false
  8560. ? 'repeat-x'
  8561. : repeatX === false && repeatY === true
  8562. ? 'repeat-y'
  8563. : 'no-repeat'
  8564. );
  8565. texture.needsUpdate = false;
  8566. }
  8567. _patterns[ texture.id ] === undefined
  8568. ? setFillStyle( 'rgba(0,0,0,1)' )
  8569. : setFillStyle( _patterns[ texture.id ] );
  8570. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8571. var a, b, c, d, e, f, det, idet,
  8572. offsetX = texture.offset.x / texture.repeat.x,
  8573. offsetY = texture.offset.y / texture.repeat.y,
  8574. width = texture.image.width * texture.repeat.x,
  8575. height = texture.image.height * texture.repeat.y;
  8576. u0 = ( u0 + offsetX ) * width;
  8577. v0 = ( 1.0 - v0 + offsetY ) * height;
  8578. u1 = ( u1 + offsetX ) * width;
  8579. v1 = ( 1.0 - v1 + offsetY ) * height;
  8580. u2 = ( u2 + offsetX ) * width;
  8581. v2 = ( 1.0 - v2 + offsetY ) * height;
  8582. x1 -= x0; y1 -= y0;
  8583. x2 -= x0; y2 -= y0;
  8584. u1 -= u0; v1 -= v0;
  8585. u2 -= u0; v2 -= v0;
  8586. det = u1 * v2 - u2 * v1;
  8587. if ( det === 0 ) {
  8588. if ( _imagedatas[ texture.id ] === undefined ) {
  8589. var canvas = document.createElement( 'canvas' )
  8590. canvas.width = texture.image.width;
  8591. canvas.height = texture.image.height;
  8592. var context = canvas.getContext( '2d' );
  8593. context.drawImage( texture.image, 0, 0 );
  8594. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8595. }
  8596. var data = _imagedatas[ texture.id ];
  8597. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8598. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8599. fillPath( _color );
  8600. return;
  8601. }
  8602. idet = 1 / det;
  8603. a = ( v2 * x1 - v1 * x2 ) * idet;
  8604. b = ( v2 * y1 - v1 * y2 ) * idet;
  8605. c = ( u1 * x2 - u2 * x1 ) * idet;
  8606. d = ( u1 * y2 - u2 * y1 ) * idet;
  8607. e = x0 - a * u0 - c * v0;
  8608. f = y0 - b * u0 - d * v0;
  8609. _context.save();
  8610. _context.transform( a, b, c, d, e, f );
  8611. _context.fill();
  8612. _context.restore();
  8613. }
  8614. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8615. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8616. var a, b, c, d, e, f, det, idet,
  8617. width = image.width - 1,
  8618. height = image.height - 1;
  8619. u0 *= width; v0 *= height;
  8620. u1 *= width; v1 *= height;
  8621. u2 *= width; v2 *= height;
  8622. x1 -= x0; y1 -= y0;
  8623. x2 -= x0; y2 -= y0;
  8624. u1 -= u0; v1 -= v0;
  8625. u2 -= u0; v2 -= v0;
  8626. det = u1 * v2 - u2 * v1;
  8627. idet = 1 / det;
  8628. a = ( v2 * x1 - v1 * x2 ) * idet;
  8629. b = ( v2 * y1 - v1 * y2 ) * idet;
  8630. c = ( u1 * x2 - u2 * x1 ) * idet;
  8631. d = ( u1 * y2 - u2 * y1 ) * idet;
  8632. e = x0 - a * u0 - c * v0;
  8633. f = y0 - b * u0 - d * v0;
  8634. _context.save();
  8635. _context.transform( a, b, c, d, e, f );
  8636. _context.clip();
  8637. _context.drawImage( image, 0, 0 );
  8638. _context.restore();
  8639. }
  8640. function getGradientTexture( color1, color2, color3, color4 ) {
  8641. // http://mrdoob.com/blog/post/710
  8642. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  8643. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  8644. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  8645. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  8646. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  8647. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  8648. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  8649. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  8650. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  8651. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  8652. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  8653. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  8654. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  8655. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  8656. return _gradientMap;
  8657. }
  8658. function smoothstep( value, min, max ) {
  8659. var x = ( value - min ) / ( max - min );
  8660. return x * x * ( 3 - 2 * x );
  8661. }
  8662. function normalToComponent( normal ) {
  8663. var component = ( normal + 1 ) * 0.5;
  8664. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  8665. }
  8666. // Hide anti-alias gaps
  8667. function expand( v1, v2 ) {
  8668. var x = v2.x - v1.x, y = v2.y - v1.y,
  8669. det = x * x + y * y, idet;
  8670. if ( det === 0 ) return;
  8671. idet = 1 / Math.sqrt( det );
  8672. x *= idet; y *= idet;
  8673. v2.x += x; v2.y += y;
  8674. v1.x -= x; v1.y -= y;
  8675. }
  8676. };
  8677. // Context cached methods.
  8678. function setOpacity( value ) {
  8679. if ( _contextGlobalAlpha !== value ) {
  8680. _context.globalAlpha = value;
  8681. _contextGlobalAlpha = value;
  8682. }
  8683. }
  8684. function setBlending( value ) {
  8685. if ( _contextGlobalCompositeOperation !== value ) {
  8686. if ( value === THREE.NormalBlending ) {
  8687. _context.globalCompositeOperation = 'source-over';
  8688. } else if ( value === THREE.AdditiveBlending ) {
  8689. _context.globalCompositeOperation = 'lighter';
  8690. } else if ( value === THREE.SubtractiveBlending ) {
  8691. _context.globalCompositeOperation = 'darker';
  8692. }
  8693. _contextGlobalCompositeOperation = value;
  8694. }
  8695. }
  8696. function setLineWidth( value ) {
  8697. if ( _contextLineWidth !== value ) {
  8698. _context.lineWidth = value;
  8699. _contextLineWidth = value;
  8700. }
  8701. }
  8702. function setLineCap( value ) {
  8703. // "butt", "round", "square"
  8704. if ( _contextLineCap !== value ) {
  8705. _context.lineCap = value;
  8706. _contextLineCap = value;
  8707. }
  8708. }
  8709. function setLineJoin( value ) {
  8710. // "round", "bevel", "miter"
  8711. if ( _contextLineJoin !== value ) {
  8712. _context.lineJoin = value;
  8713. _contextLineJoin = value;
  8714. }
  8715. }
  8716. function setStrokeStyle( value ) {
  8717. if ( _contextStrokeStyle !== value ) {
  8718. _context.strokeStyle = value;
  8719. _contextStrokeStyle = value;
  8720. }
  8721. }
  8722. function setFillStyle( value ) {
  8723. if ( _contextFillStyle !== value ) {
  8724. _context.fillStyle = value;
  8725. _contextFillStyle = value;
  8726. }
  8727. }
  8728. };
  8729. /**
  8730. * @author alteredq / http://alteredqualia.com/
  8731. * @author mrdoob / http://mrdoob.com/
  8732. * @author mikael emtinger / http://gomo.se/
  8733. */
  8734. THREE.ShaderChunk = {
  8735. // FOG
  8736. fog_pars_fragment: [
  8737. "#ifdef USE_FOG",
  8738. "uniform vec3 fogColor;",
  8739. "#ifdef FOG_EXP2",
  8740. "uniform float fogDensity;",
  8741. "#else",
  8742. "uniform float fogNear;",
  8743. "uniform float fogFar;",
  8744. "#endif",
  8745. "#endif"
  8746. ].join("\n"),
  8747. fog_fragment: [
  8748. "#ifdef USE_FOG",
  8749. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8750. "#ifdef FOG_EXP2",
  8751. "const float LOG2 = 1.442695;",
  8752. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8753. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8754. "#else",
  8755. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8756. "#endif",
  8757. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8758. "#endif"
  8759. ].join("\n"),
  8760. // ENVIRONMENT MAP
  8761. envmap_pars_fragment: [
  8762. "#ifdef USE_ENVMAP",
  8763. "uniform float reflectivity;",
  8764. "uniform samplerCube envMap;",
  8765. "uniform float flipEnvMap;",
  8766. "uniform int combine;",
  8767. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8768. "uniform bool useRefract;",
  8769. "uniform float refractionRatio;",
  8770. "#else",
  8771. "varying vec3 vReflect;",
  8772. "#endif",
  8773. "#endif"
  8774. ].join("\n"),
  8775. envmap_fragment: [
  8776. "#ifdef USE_ENVMAP",
  8777. "vec3 reflectVec;",
  8778. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8779. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8780. "if ( useRefract ) {",
  8781. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8782. "} else { ",
  8783. "reflectVec = reflect( cameraToVertex, normal );",
  8784. "}",
  8785. "#else",
  8786. "reflectVec = vReflect;",
  8787. "#endif",
  8788. "#ifdef DOUBLE_SIDED",
  8789. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8790. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8791. "#else",
  8792. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8793. "#endif",
  8794. "#ifdef GAMMA_INPUT",
  8795. "cubeColor.xyz *= cubeColor.xyz;",
  8796. "#endif",
  8797. "if ( combine == 1 ) {",
  8798. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8799. "} else if ( combine == 2 ) {",
  8800. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8801. "} else {",
  8802. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8803. "}",
  8804. "#endif"
  8805. ].join("\n"),
  8806. envmap_pars_vertex: [
  8807. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8808. "varying vec3 vReflect;",
  8809. "uniform float refractionRatio;",
  8810. "uniform bool useRefract;",
  8811. "#endif"
  8812. ].join("\n"),
  8813. worldpos_vertex : [
  8814. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8815. "#ifdef USE_SKINNING",
  8816. "vec4 worldPosition = modelMatrix * skinned;",
  8817. "#endif",
  8818. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8819. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8820. "#endif",
  8821. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8822. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8823. "#endif",
  8824. "#endif"
  8825. ].join("\n"),
  8826. envmap_vertex : [
  8827. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8828. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8829. "worldNormal = normalize( worldNormal );",
  8830. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8831. "if ( useRefract ) {",
  8832. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8833. "} else {",
  8834. "vReflect = reflect( cameraToVertex, worldNormal );",
  8835. "}",
  8836. "#endif"
  8837. ].join("\n"),
  8838. // COLOR MAP (particles)
  8839. map_particle_pars_fragment: [
  8840. "#ifdef USE_MAP",
  8841. "uniform sampler2D map;",
  8842. "#endif"
  8843. ].join("\n"),
  8844. map_particle_fragment: [
  8845. "#ifdef USE_MAP",
  8846. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8847. "#endif"
  8848. ].join("\n"),
  8849. // COLOR MAP (triangles)
  8850. map_pars_vertex: [
  8851. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8852. "varying vec2 vUv;",
  8853. "uniform vec4 offsetRepeat;",
  8854. "#endif"
  8855. ].join("\n"),
  8856. map_pars_fragment: [
  8857. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8858. "varying vec2 vUv;",
  8859. "#endif",
  8860. "#ifdef USE_MAP",
  8861. "uniform sampler2D map;",
  8862. "#endif"
  8863. ].join("\n"),
  8864. map_vertex: [
  8865. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8866. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8867. "#endif"
  8868. ].join("\n"),
  8869. map_fragment: [
  8870. "#ifdef USE_MAP",
  8871. "vec4 texelColor = texture2D( map, vUv );",
  8872. "#ifdef GAMMA_INPUT",
  8873. "texelColor.xyz *= texelColor.xyz;",
  8874. "#endif",
  8875. "gl_FragColor = gl_FragColor * texelColor;",
  8876. "#endif"
  8877. ].join("\n"),
  8878. // LIGHT MAP
  8879. lightmap_pars_fragment: [
  8880. "#ifdef USE_LIGHTMAP",
  8881. "varying vec2 vUv2;",
  8882. "uniform sampler2D lightMap;",
  8883. "#endif"
  8884. ].join("\n"),
  8885. lightmap_pars_vertex: [
  8886. "#ifdef USE_LIGHTMAP",
  8887. "varying vec2 vUv2;",
  8888. "#endif"
  8889. ].join("\n"),
  8890. lightmap_fragment: [
  8891. "#ifdef USE_LIGHTMAP",
  8892. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8893. "#endif"
  8894. ].join("\n"),
  8895. lightmap_vertex: [
  8896. "#ifdef USE_LIGHTMAP",
  8897. "vUv2 = uv2;",
  8898. "#endif"
  8899. ].join("\n"),
  8900. // BUMP MAP
  8901. bumpmap_pars_fragment: [
  8902. "#ifdef USE_BUMPMAP",
  8903. "uniform sampler2D bumpMap;",
  8904. "uniform float bumpScale;",
  8905. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8906. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8907. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8908. "vec2 dHdxy_fwd() {",
  8909. "vec2 dSTdx = dFdx( vUv );",
  8910. "vec2 dSTdy = dFdy( vUv );",
  8911. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8912. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8913. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8914. "return vec2( dBx, dBy );",
  8915. "}",
  8916. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8917. "vec3 vSigmaX = dFdx( surf_pos );",
  8918. "vec3 vSigmaY = dFdy( surf_pos );",
  8919. "vec3 vN = surf_norm;", // normalized
  8920. "vec3 R1 = cross( vSigmaY, vN );",
  8921. "vec3 R2 = cross( vN, vSigmaX );",
  8922. "float fDet = dot( vSigmaX, R1 );",
  8923. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8924. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8925. "}",
  8926. "#endif"
  8927. ].join("\n"),
  8928. // NORMAL MAP
  8929. normalmap_pars_fragment: [
  8930. "#ifdef USE_NORMALMAP",
  8931. "uniform sampler2D normalMap;",
  8932. "uniform vec2 normalScale;",
  8933. // Per-Pixel Tangent Space Normal Mapping
  8934. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8935. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8936. "vec3 q0 = dFdx( eye_pos.xyz );",
  8937. "vec3 q1 = dFdy( eye_pos.xyz );",
  8938. "vec2 st0 = dFdx( vUv.st );",
  8939. "vec2 st1 = dFdy( vUv.st );",
  8940. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8941. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8942. "vec3 N = normalize( surf_norm );",
  8943. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8944. "mapN.xy = normalScale * mapN.xy;",
  8945. "mat3 tsn = mat3( S, T, N );",
  8946. "return normalize( tsn * mapN );",
  8947. "}",
  8948. "#endif"
  8949. ].join("\n"),
  8950. // SPECULAR MAP
  8951. specularmap_pars_fragment: [
  8952. "#ifdef USE_SPECULARMAP",
  8953. "uniform sampler2D specularMap;",
  8954. "#endif"
  8955. ].join("\n"),
  8956. specularmap_fragment: [
  8957. "float specularStrength;",
  8958. "#ifdef USE_SPECULARMAP",
  8959. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8960. "specularStrength = texelSpecular.r;",
  8961. "#else",
  8962. "specularStrength = 1.0;",
  8963. "#endif"
  8964. ].join("\n"),
  8965. // LIGHTS LAMBERT
  8966. lights_lambert_pars_vertex: [
  8967. "uniform vec3 ambient;",
  8968. "uniform vec3 diffuse;",
  8969. "uniform vec3 emissive;",
  8970. "uniform vec3 ambientLightColor;",
  8971. "#if MAX_DIR_LIGHTS > 0",
  8972. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8973. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8974. "#endif",
  8975. "#if MAX_HEMI_LIGHTS > 0",
  8976. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8977. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8978. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8979. "#endif",
  8980. "#if MAX_POINT_LIGHTS > 0",
  8981. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8982. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8983. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8984. "#endif",
  8985. "#if MAX_SPOT_LIGHTS > 0",
  8986. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8987. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8988. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8989. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8990. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8991. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8992. "#endif",
  8993. "#ifdef WRAP_AROUND",
  8994. "uniform vec3 wrapRGB;",
  8995. "#endif"
  8996. ].join("\n"),
  8997. lights_lambert_vertex: [
  8998. "vLightFront = vec3( 0.0 );",
  8999. "#ifdef DOUBLE_SIDED",
  9000. "vLightBack = vec3( 0.0 );",
  9001. "#endif",
  9002. "transformedNormal = normalize( transformedNormal );",
  9003. "#if MAX_DIR_LIGHTS > 0",
  9004. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9005. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9006. "vec3 dirVector = normalize( lDirection.xyz );",
  9007. "float dotProduct = dot( transformedNormal, dirVector );",
  9008. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9009. "#ifdef DOUBLE_SIDED",
  9010. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9011. "#ifdef WRAP_AROUND",
  9012. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9013. "#endif",
  9014. "#endif",
  9015. "#ifdef WRAP_AROUND",
  9016. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9017. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9018. "#ifdef DOUBLE_SIDED",
  9019. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9020. "#endif",
  9021. "#endif",
  9022. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9023. "#ifdef DOUBLE_SIDED",
  9024. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9025. "#endif",
  9026. "}",
  9027. "#endif",
  9028. "#if MAX_POINT_LIGHTS > 0",
  9029. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9030. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9031. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9032. "float lDistance = 1.0;",
  9033. "if ( pointLightDistance[ i ] > 0.0 )",
  9034. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9035. "lVector = normalize( lVector );",
  9036. "float dotProduct = dot( transformedNormal, lVector );",
  9037. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9038. "#ifdef DOUBLE_SIDED",
  9039. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9040. "#ifdef WRAP_AROUND",
  9041. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9042. "#endif",
  9043. "#endif",
  9044. "#ifdef WRAP_AROUND",
  9045. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9046. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9047. "#ifdef DOUBLE_SIDED",
  9048. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9049. "#endif",
  9050. "#endif",
  9051. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9052. "#ifdef DOUBLE_SIDED",
  9053. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9054. "#endif",
  9055. "}",
  9056. "#endif",
  9057. "#if MAX_SPOT_LIGHTS > 0",
  9058. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9059. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9060. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9061. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9062. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9063. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9064. "float lDistance = 1.0;",
  9065. "if ( spotLightDistance[ i ] > 0.0 )",
  9066. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9067. "lVector = normalize( lVector );",
  9068. "float dotProduct = dot( transformedNormal, lVector );",
  9069. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9070. "#ifdef DOUBLE_SIDED",
  9071. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9072. "#ifdef WRAP_AROUND",
  9073. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9074. "#endif",
  9075. "#endif",
  9076. "#ifdef WRAP_AROUND",
  9077. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9078. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9079. "#ifdef DOUBLE_SIDED",
  9080. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9081. "#endif",
  9082. "#endif",
  9083. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9084. "#ifdef DOUBLE_SIDED",
  9085. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9086. "#endif",
  9087. "}",
  9088. "}",
  9089. "#endif",
  9090. "#if MAX_HEMI_LIGHTS > 0",
  9091. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9092. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9093. "vec3 lVector = normalize( lDirection.xyz );",
  9094. "float dotProduct = dot( transformedNormal, lVector );",
  9095. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9096. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9097. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9098. "#ifdef DOUBLE_SIDED",
  9099. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9100. "#endif",
  9101. "}",
  9102. "#endif",
  9103. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9104. "#ifdef DOUBLE_SIDED",
  9105. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9106. "#endif"
  9107. ].join("\n"),
  9108. // LIGHTS PHONG
  9109. lights_phong_pars_vertex: [
  9110. "#ifndef PHONG_PER_PIXEL",
  9111. "#if MAX_POINT_LIGHTS > 0",
  9112. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9113. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9114. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9115. "#endif",
  9116. "#if MAX_SPOT_LIGHTS > 0",
  9117. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9118. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9119. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9120. "#endif",
  9121. "#endif",
  9122. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9123. "varying vec3 vWorldPosition;",
  9124. "#endif"
  9125. ].join("\n"),
  9126. lights_phong_vertex: [
  9127. "#ifndef PHONG_PER_PIXEL",
  9128. "#if MAX_POINT_LIGHTS > 0",
  9129. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9130. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9131. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9132. "float lDistance = 1.0;",
  9133. "if ( pointLightDistance[ i ] > 0.0 )",
  9134. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9135. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9136. "}",
  9137. "#endif",
  9138. "#if MAX_SPOT_LIGHTS > 0",
  9139. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9140. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9141. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9142. "float lDistance = 1.0;",
  9143. "if ( spotLightDistance[ i ] > 0.0 )",
  9144. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9145. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9146. "}",
  9147. "#endif",
  9148. "#endif",
  9149. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9150. "vWorldPosition = worldPosition.xyz;",
  9151. "#endif"
  9152. ].join("\n"),
  9153. lights_phong_pars_fragment: [
  9154. "uniform vec3 ambientLightColor;",
  9155. "#if MAX_DIR_LIGHTS > 0",
  9156. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9157. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9158. "#endif",
  9159. "#if MAX_HEMI_LIGHTS > 0",
  9160. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9161. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9162. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9163. "#endif",
  9164. "#if MAX_POINT_LIGHTS > 0",
  9165. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9166. "#ifdef PHONG_PER_PIXEL",
  9167. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9168. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9169. "#else",
  9170. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9171. "#endif",
  9172. "#endif",
  9173. "#if MAX_SPOT_LIGHTS > 0",
  9174. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9175. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9176. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9177. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9178. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9179. "#ifdef PHONG_PER_PIXEL",
  9180. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9181. "#else",
  9182. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9183. "#endif",
  9184. "#endif",
  9185. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9186. "varying vec3 vWorldPosition;",
  9187. "#endif",
  9188. "#ifdef WRAP_AROUND",
  9189. "uniform vec3 wrapRGB;",
  9190. "#endif",
  9191. "varying vec3 vViewPosition;",
  9192. "varying vec3 vNormal;"
  9193. ].join("\n"),
  9194. lights_phong_fragment: [
  9195. "vec3 normal = normalize( vNormal );",
  9196. "vec3 viewPosition = normalize( vViewPosition );",
  9197. "#ifdef DOUBLE_SIDED",
  9198. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9199. "#endif",
  9200. "#ifdef USE_NORMALMAP",
  9201. "normal = perturbNormal2Arb( -viewPosition, normal );",
  9202. "#elif defined( USE_BUMPMAP )",
  9203. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9204. "#endif",
  9205. "#if MAX_POINT_LIGHTS > 0",
  9206. "vec3 pointDiffuse = vec3( 0.0 );",
  9207. "vec3 pointSpecular = vec3( 0.0 );",
  9208. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9209. "#ifdef PHONG_PER_PIXEL",
  9210. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9211. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9212. "float lDistance = 1.0;",
  9213. "if ( pointLightDistance[ i ] > 0.0 )",
  9214. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9215. "lVector = normalize( lVector );",
  9216. "#else",
  9217. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9218. "float lDistance = vPointLight[ i ].w;",
  9219. "#endif",
  9220. // diffuse
  9221. "float dotProduct = dot( normal, lVector );",
  9222. "#ifdef WRAP_AROUND",
  9223. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9224. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9225. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9226. "#else",
  9227. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9228. "#endif",
  9229. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9230. // specular
  9231. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9232. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9233. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9234. "#ifdef PHYSICALLY_BASED_SHADING",
  9235. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9236. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9237. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9238. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9239. "#else",
  9240. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9241. "#endif",
  9242. "}",
  9243. "#endif",
  9244. "#if MAX_SPOT_LIGHTS > 0",
  9245. "vec3 spotDiffuse = vec3( 0.0 );",
  9246. "vec3 spotSpecular = vec3( 0.0 );",
  9247. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9248. "#ifdef PHONG_PER_PIXEL",
  9249. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9250. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9251. "float lDistance = 1.0;",
  9252. "if ( spotLightDistance[ i ] > 0.0 )",
  9253. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9254. "lVector = normalize( lVector );",
  9255. "#else",
  9256. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9257. "float lDistance = vSpotLight[ i ].w;",
  9258. "#endif",
  9259. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9260. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9261. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9262. // diffuse
  9263. "float dotProduct = dot( normal, lVector );",
  9264. "#ifdef WRAP_AROUND",
  9265. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9266. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9267. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9268. "#else",
  9269. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9270. "#endif",
  9271. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9272. // specular
  9273. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9274. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9275. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9276. "#ifdef PHYSICALLY_BASED_SHADING",
  9277. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9278. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9279. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9280. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9281. "#else",
  9282. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9283. "#endif",
  9284. "}",
  9285. "}",
  9286. "#endif",
  9287. "#if MAX_DIR_LIGHTS > 0",
  9288. "vec3 dirDiffuse = vec3( 0.0 );",
  9289. "vec3 dirSpecular = vec3( 0.0 );" ,
  9290. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9291. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9292. "vec3 dirVector = normalize( lDirection.xyz );",
  9293. // diffuse
  9294. "float dotProduct = dot( normal, dirVector );",
  9295. "#ifdef WRAP_AROUND",
  9296. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9297. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9298. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9299. "#else",
  9300. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9301. "#endif",
  9302. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9303. // specular
  9304. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9305. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9306. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9307. "#ifdef PHYSICALLY_BASED_SHADING",
  9308. /*
  9309. // fresnel term from skin shader
  9310. "const float F0 = 0.128;",
  9311. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9312. "float exponential = pow( base, 5.0 );",
  9313. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9314. */
  9315. /*
  9316. // fresnel term from fresnel shader
  9317. "const float mFresnelBias = 0.08;",
  9318. "const float mFresnelScale = 0.3;",
  9319. "const float mFresnelPower = 5.0;",
  9320. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9321. */
  9322. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9323. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9324. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9325. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9326. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9327. "#else",
  9328. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9329. "#endif",
  9330. "}",
  9331. "#endif",
  9332. "#if MAX_HEMI_LIGHTS > 0",
  9333. "vec3 hemiDiffuse = vec3( 0.0 );",
  9334. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9335. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9336. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9337. "vec3 lVector = normalize( lDirection.xyz );",
  9338. // diffuse
  9339. "float dotProduct = dot( normal, lVector );",
  9340. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9341. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9342. "hemiDiffuse += diffuse * hemiColor;",
  9343. // specular (sky light)
  9344. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9345. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9346. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9347. // specular (ground light)
  9348. "vec3 lVectorGround = -lVector;",
  9349. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9350. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9351. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9352. "#ifdef PHYSICALLY_BASED_SHADING",
  9353. "float dotProductGround = dot( normal, lVectorGround );",
  9354. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9355. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9356. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9357. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9358. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9359. "#else",
  9360. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9361. "#endif",
  9362. "}",
  9363. "#endif",
  9364. "vec3 totalDiffuse = vec3( 0.0 );",
  9365. "vec3 totalSpecular = vec3( 0.0 );",
  9366. "#if MAX_DIR_LIGHTS > 0",
  9367. "totalDiffuse += dirDiffuse;",
  9368. "totalSpecular += dirSpecular;",
  9369. "#endif",
  9370. "#if MAX_HEMI_LIGHTS > 0",
  9371. "totalDiffuse += hemiDiffuse;",
  9372. "totalSpecular += hemiSpecular;",
  9373. "#endif",
  9374. "#if MAX_POINT_LIGHTS > 0",
  9375. "totalDiffuse += pointDiffuse;",
  9376. "totalSpecular += pointSpecular;",
  9377. "#endif",
  9378. "#if MAX_SPOT_LIGHTS > 0",
  9379. "totalDiffuse += spotDiffuse;",
  9380. "totalSpecular += spotSpecular;",
  9381. "#endif",
  9382. "#ifdef METAL",
  9383. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9384. "#else",
  9385. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9386. "#endif"
  9387. ].join("\n"),
  9388. // VERTEX COLORS
  9389. color_pars_fragment: [
  9390. "#ifdef USE_COLOR",
  9391. "varying vec3 vColor;",
  9392. "#endif"
  9393. ].join("\n"),
  9394. color_fragment: [
  9395. "#ifdef USE_COLOR",
  9396. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9397. "#endif"
  9398. ].join("\n"),
  9399. color_pars_vertex: [
  9400. "#ifdef USE_COLOR",
  9401. "varying vec3 vColor;",
  9402. "#endif"
  9403. ].join("\n"),
  9404. color_vertex: [
  9405. "#ifdef USE_COLOR",
  9406. "#ifdef GAMMA_INPUT",
  9407. "vColor = color * color;",
  9408. "#else",
  9409. "vColor = color;",
  9410. "#endif",
  9411. "#endif"
  9412. ].join("\n"),
  9413. // SKINNING
  9414. skinning_pars_vertex: [
  9415. "#ifdef USE_SKINNING",
  9416. "#ifdef BONE_TEXTURE",
  9417. "uniform sampler2D boneTexture;",
  9418. "mat4 getBoneMatrix( const in float i ) {",
  9419. "float j = i * 4.0;",
  9420. "float x = mod( j, N_BONE_PIXEL_X );",
  9421. "float y = floor( j / N_BONE_PIXEL_X );",
  9422. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9423. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9424. "y = dy * ( y + 0.5 );",
  9425. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9426. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9427. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9428. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9429. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9430. "return bone;",
  9431. "}",
  9432. "#else",
  9433. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9434. "mat4 getBoneMatrix( const in float i ) {",
  9435. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9436. "return bone;",
  9437. "}",
  9438. "#endif",
  9439. "#endif"
  9440. ].join("\n"),
  9441. skinbase_vertex: [
  9442. "#ifdef USE_SKINNING",
  9443. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9444. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9445. "#endif"
  9446. ].join("\n"),
  9447. skinning_vertex: [
  9448. "#ifdef USE_SKINNING",
  9449. "#ifdef USE_MORPHTARGETS",
  9450. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9451. "#else",
  9452. "vec4 skinVertex = vec4( position, 1.0 );",
  9453. "#endif",
  9454. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9455. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9456. "#endif"
  9457. ].join("\n"),
  9458. // MORPHING
  9459. morphtarget_pars_vertex: [
  9460. "#ifdef USE_MORPHTARGETS",
  9461. "#ifndef USE_MORPHNORMALS",
  9462. "uniform float morphTargetInfluences[ 8 ];",
  9463. "#else",
  9464. "uniform float morphTargetInfluences[ 4 ];",
  9465. "#endif",
  9466. "#endif"
  9467. ].join("\n"),
  9468. morphtarget_vertex: [
  9469. "#ifdef USE_MORPHTARGETS",
  9470. "vec3 morphed = vec3( 0.0 );",
  9471. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9472. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9473. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9474. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9475. "#ifndef USE_MORPHNORMALS",
  9476. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9477. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9478. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9479. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9480. "#endif",
  9481. "morphed += position;",
  9482. "#endif"
  9483. ].join("\n"),
  9484. default_vertex : [
  9485. "vec4 mvPosition;",
  9486. "#ifdef USE_SKINNING",
  9487. "mvPosition = modelViewMatrix * skinned;",
  9488. "#endif",
  9489. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9490. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9491. "#endif",
  9492. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9493. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9494. "#endif",
  9495. "gl_Position = projectionMatrix * mvPosition;"
  9496. ].join("\n"),
  9497. morphnormal_vertex: [
  9498. "#ifdef USE_MORPHNORMALS",
  9499. "vec3 morphedNormal = vec3( 0.0 );",
  9500. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9501. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9502. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9503. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9504. "morphedNormal += normal;",
  9505. "#endif"
  9506. ].join("\n"),
  9507. skinnormal_vertex: [
  9508. "#ifdef USE_SKINNING",
  9509. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9510. "skinMatrix += skinWeight.y * boneMatY;",
  9511. "#ifdef USE_MORPHNORMALS",
  9512. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9513. "#else",
  9514. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9515. "#endif",
  9516. "#endif"
  9517. ].join("\n"),
  9518. defaultnormal_vertex: [
  9519. "vec3 objectNormal;",
  9520. "#ifdef USE_SKINNING",
  9521. "objectNormal = skinnedNormal.xyz;",
  9522. "#endif",
  9523. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9524. "objectNormal = morphedNormal;",
  9525. "#endif",
  9526. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9527. "objectNormal = normal;",
  9528. "#endif",
  9529. "#ifdef FLIP_SIDED",
  9530. "objectNormal = -objectNormal;",
  9531. "#endif",
  9532. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9533. ].join("\n"),
  9534. // SHADOW MAP
  9535. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9536. // http://spidergl.org/example.php?id=6
  9537. // http://fabiensanglard.net/shadowmapping
  9538. shadowmap_pars_fragment: [
  9539. "#ifdef USE_SHADOWMAP",
  9540. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9541. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9542. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9543. "uniform float shadowBias[ MAX_SHADOWS ];",
  9544. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9545. "float unpackDepth( const in vec4 rgba_depth ) {",
  9546. "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 );",
  9547. "float depth = dot( rgba_depth, bit_shift );",
  9548. "return depth;",
  9549. "}",
  9550. "#endif"
  9551. ].join("\n"),
  9552. shadowmap_fragment: [
  9553. "#ifdef USE_SHADOWMAP",
  9554. "#ifdef SHADOWMAP_DEBUG",
  9555. "vec3 frustumColors[3];",
  9556. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9557. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9558. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9559. "#endif",
  9560. "#ifdef SHADOWMAP_CASCADE",
  9561. "int inFrustumCount = 0;",
  9562. "#endif",
  9563. "float fDepth;",
  9564. "vec3 shadowColor = vec3( 1.0 );",
  9565. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9566. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9567. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9568. // "if ( all( something, something ) )" using this instead
  9569. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9570. "bool inFrustum = all( inFrustumVec );",
  9571. // don't shadow pixels outside of light frustum
  9572. // use just first frustum (for cascades)
  9573. // don't shadow pixels behind far plane of light frustum
  9574. "#ifdef SHADOWMAP_CASCADE",
  9575. "inFrustumCount += int( inFrustum );",
  9576. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9577. "#else",
  9578. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9579. "#endif",
  9580. "bool frustumTest = all( frustumTestVec );",
  9581. "if ( frustumTest ) {",
  9582. "shadowCoord.z += shadowBias[ i ];",
  9583. "#if defined( SHADOWMAP_TYPE_PCF )",
  9584. // Percentage-close filtering
  9585. // (9 pixel kernel)
  9586. // http://fabiensanglard.net/shadowmappingPCF/
  9587. "float shadow = 0.0;",
  9588. /*
  9589. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9590. // must enroll loop manually
  9591. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9592. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9593. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9594. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9595. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9596. "float fDepth = unpackDepth( rgbaDepth );",
  9597. "if ( fDepth < shadowCoord.z )",
  9598. "shadow += 1.0;",
  9599. "}",
  9600. "shadow /= 9.0;",
  9601. */
  9602. "const float shadowDelta = 1.0 / 9.0;",
  9603. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9604. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9605. "float dx0 = -1.25 * xPixelOffset;",
  9606. "float dy0 = -1.25 * yPixelOffset;",
  9607. "float dx1 = 1.25 * xPixelOffset;",
  9608. "float dy1 = 1.25 * yPixelOffset;",
  9609. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9610. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9611. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9612. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9613. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9614. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9615. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9616. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9617. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9618. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9619. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9620. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9621. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9622. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9623. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9624. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9625. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9626. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9627. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9628. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  9629. // Percentage-close filtering
  9630. // (9 pixel kernel)
  9631. // http://fabiensanglard.net/shadowmappingPCF/
  9632. "float shadow = 0.0;",
  9633. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9634. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9635. "float dx0 = -1.0 * xPixelOffset;",
  9636. "float dy0 = -1.0 * yPixelOffset;",
  9637. "float dx1 = 1.0 * xPixelOffset;",
  9638. "float dy1 = 1.0 * yPixelOffset;",
  9639. "mat3 shadowKernel;",
  9640. "mat3 depthKernel;",
  9641. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9642. "if ( depthKernel[0][0] < shadowCoord.z ) shadowKernel[0][0] = 0.25;",
  9643. "else shadowKernel[0][0] = 0.0;",
  9644. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9645. "if ( depthKernel[0][1] < shadowCoord.z ) shadowKernel[0][1] = 0.25;",
  9646. "else shadowKernel[0][1] = 0.0;",
  9647. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9648. "if ( depthKernel[0][2] < shadowCoord.z ) shadowKernel[0][2] = 0.25;",
  9649. "else shadowKernel[0][2] = 0.0;",
  9650. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9651. "if ( depthKernel[1][0] < shadowCoord.z ) shadowKernel[1][0] = 0.25;",
  9652. "else shadowKernel[1][0] = 0.0;",
  9653. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9654. "if ( depthKernel[1][1] < shadowCoord.z ) shadowKernel[1][1] = 0.25;",
  9655. "else shadowKernel[1][1] = 0.0;",
  9656. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9657. "if ( depthKernel[1][2] < shadowCoord.z ) shadowKernel[1][2] = 0.25;",
  9658. "else shadowKernel[1][2] = 0.0;",
  9659. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9660. "if ( depthKernel[2][0] < shadowCoord.z ) shadowKernel[2][0] = 0.25;",
  9661. "else shadowKernel[2][0] = 0.0;",
  9662. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9663. "if ( depthKernel[2][1] < shadowCoord.z ) shadowKernel[2][1] = 0.25;",
  9664. "else shadowKernel[2][1] = 0.0;",
  9665. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9666. "if ( depthKernel[2][2] < shadowCoord.z ) shadowKernel[2][2] = 0.25;",
  9667. "else shadowKernel[2][2] = 0.0;",
  9668. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  9669. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  9670. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  9671. "vec4 shadowValues;",
  9672. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  9673. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  9674. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  9675. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  9676. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  9677. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9678. "#else",
  9679. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  9680. "float fDepth = unpackDepth( rgbaDepth );",
  9681. "if ( fDepth < shadowCoord.z )",
  9682. // spot with multiple shadows is darker
  9683. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  9684. // spot with multiple shadows has the same color as single shadow spot
  9685. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  9686. "#endif",
  9687. "}",
  9688. "#ifdef SHADOWMAP_DEBUG",
  9689. "#ifdef SHADOWMAP_CASCADE",
  9690. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  9691. "#else",
  9692. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  9693. "#endif",
  9694. "#endif",
  9695. "}",
  9696. "#ifdef GAMMA_OUTPUT",
  9697. "shadowColor *= shadowColor;",
  9698. "#endif",
  9699. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  9700. "#endif"
  9701. ].join("\n"),
  9702. shadowmap_pars_vertex: [
  9703. "#ifdef USE_SHADOWMAP",
  9704. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9705. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  9706. "#endif"
  9707. ].join("\n"),
  9708. shadowmap_vertex: [
  9709. "#ifdef USE_SHADOWMAP",
  9710. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9711. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  9712. "}",
  9713. "#endif"
  9714. ].join("\n"),
  9715. // ALPHATEST
  9716. alphatest_fragment: [
  9717. "#ifdef ALPHATEST",
  9718. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  9719. "#endif"
  9720. ].join("\n"),
  9721. // LINEAR SPACE
  9722. linear_to_gamma_fragment: [
  9723. "#ifdef GAMMA_OUTPUT",
  9724. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9725. "#endif"
  9726. ].join("\n")
  9727. };
  9728. THREE.UniformsUtils = {
  9729. merge: function ( uniforms ) {
  9730. var u, p, tmp, merged = {};
  9731. for ( u = 0; u < uniforms.length; u ++ ) {
  9732. tmp = this.clone( uniforms[ u ] );
  9733. for ( p in tmp ) {
  9734. merged[ p ] = tmp[ p ];
  9735. }
  9736. }
  9737. return merged;
  9738. },
  9739. clone: function ( uniforms_src ) {
  9740. var u, p, parameter, parameter_src, uniforms_dst = {};
  9741. for ( u in uniforms_src ) {
  9742. uniforms_dst[ u ] = {};
  9743. for ( p in uniforms_src[ u ] ) {
  9744. parameter_src = uniforms_src[ u ][ p ];
  9745. if ( parameter_src instanceof THREE.Color ||
  9746. parameter_src instanceof THREE.Vector2 ||
  9747. parameter_src instanceof THREE.Vector3 ||
  9748. parameter_src instanceof THREE.Vector4 ||
  9749. parameter_src instanceof THREE.Matrix4 ||
  9750. parameter_src instanceof THREE.Texture ) {
  9751. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9752. } else if ( parameter_src instanceof Array ) {
  9753. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9754. } else {
  9755. uniforms_dst[ u ][ p ] = parameter_src;
  9756. }
  9757. }
  9758. }
  9759. return uniforms_dst;
  9760. }
  9761. };
  9762. THREE.UniformsLib = {
  9763. common: {
  9764. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9765. "opacity" : { type: "f", value: 1.0 },
  9766. "map" : { type: "t", value: null },
  9767. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9768. "lightMap" : { type: "t", value: null },
  9769. "specularMap" : { type: "t", value: null },
  9770. "envMap" : { type: "t", value: null },
  9771. "flipEnvMap" : { type: "f", value: -1 },
  9772. "useRefract" : { type: "i", value: 0 },
  9773. "reflectivity" : { type: "f", value: 1.0 },
  9774. "refractionRatio" : { type: "f", value: 0.98 },
  9775. "combine" : { type: "i", value: 0 },
  9776. "morphTargetInfluences" : { type: "f", value: 0 }
  9777. },
  9778. bump: {
  9779. "bumpMap" : { type: "t", value: null },
  9780. "bumpScale" : { type: "f", value: 1 }
  9781. },
  9782. normalmap: {
  9783. "normalMap" : { type: "t", value: null },
  9784. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9785. },
  9786. fog : {
  9787. "fogDensity" : { type: "f", value: 0.00025 },
  9788. "fogNear" : { type: "f", value: 1 },
  9789. "fogFar" : { type: "f", value: 2000 },
  9790. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9791. },
  9792. lights: {
  9793. "ambientLightColor" : { type: "fv", value: [] },
  9794. "directionalLightDirection" : { type: "fv", value: [] },
  9795. "directionalLightColor" : { type: "fv", value: [] },
  9796. "hemisphereLightDirection" : { type: "fv", value: [] },
  9797. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9798. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9799. "pointLightColor" : { type: "fv", value: [] },
  9800. "pointLightPosition" : { type: "fv", value: [] },
  9801. "pointLightDistance" : { type: "fv1", value: [] },
  9802. "spotLightColor" : { type: "fv", value: [] },
  9803. "spotLightPosition" : { type: "fv", value: [] },
  9804. "spotLightDirection" : { type: "fv", value: [] },
  9805. "spotLightDistance" : { type: "fv1", value: [] },
  9806. "spotLightAngleCos" : { type: "fv1", value: [] },
  9807. "spotLightExponent" : { type: "fv1", value: [] }
  9808. },
  9809. particle: {
  9810. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9811. "opacity" : { type: "f", value: 1.0 },
  9812. "size" : { type: "f", value: 1.0 },
  9813. "scale" : { type: "f", value: 1.0 },
  9814. "map" : { type: "t", value: null },
  9815. "fogDensity" : { type: "f", value: 0.00025 },
  9816. "fogNear" : { type: "f", value: 1 },
  9817. "fogFar" : { type: "f", value: 2000 },
  9818. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9819. },
  9820. shadowmap: {
  9821. "shadowMap": { type: "tv", value: [] },
  9822. "shadowMapSize": { type: "v2v", value: [] },
  9823. "shadowBias" : { type: "fv1", value: [] },
  9824. "shadowDarkness": { type: "fv1", value: [] },
  9825. "shadowMatrix" : { type: "m4v", value: [] }
  9826. }
  9827. };
  9828. THREE.ShaderLib = {
  9829. 'depth': {
  9830. uniforms: {
  9831. "mNear": { type: "f", value: 1.0 },
  9832. "mFar" : { type: "f", value: 2000.0 },
  9833. "opacity" : { type: "f", value: 1.0 }
  9834. },
  9835. vertexShader: [
  9836. "void main() {",
  9837. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  9838. "}"
  9839. ].join("\n"),
  9840. fragmentShader: [
  9841. "uniform float mNear;",
  9842. "uniform float mFar;",
  9843. "uniform float opacity;",
  9844. "void main() {",
  9845. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9846. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  9847. "gl_FragColor = vec4( vec3( color ), opacity );",
  9848. "}"
  9849. ].join("\n")
  9850. },
  9851. 'normal': {
  9852. uniforms: {
  9853. "opacity" : { type: "f", value: 1.0 }
  9854. },
  9855. vertexShader: [
  9856. "varying vec3 vNormal;",
  9857. "void main() {",
  9858. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9859. "vNormal = normalize( normalMatrix * normal );",
  9860. "gl_Position = projectionMatrix * mvPosition;",
  9861. "}"
  9862. ].join("\n"),
  9863. fragmentShader: [
  9864. "uniform float opacity;",
  9865. "varying vec3 vNormal;",
  9866. "void main() {",
  9867. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  9868. "}"
  9869. ].join("\n")
  9870. },
  9871. 'basic': {
  9872. uniforms: THREE.UniformsUtils.merge( [
  9873. THREE.UniformsLib[ "common" ],
  9874. THREE.UniformsLib[ "fog" ],
  9875. THREE.UniformsLib[ "shadowmap" ]
  9876. ] ),
  9877. vertexShader: [
  9878. THREE.ShaderChunk[ "map_pars_vertex" ],
  9879. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9880. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9881. THREE.ShaderChunk[ "color_pars_vertex" ],
  9882. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9883. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9884. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9885. "void main() {",
  9886. THREE.ShaderChunk[ "map_vertex" ],
  9887. THREE.ShaderChunk[ "lightmap_vertex" ],
  9888. THREE.ShaderChunk[ "color_vertex" ],
  9889. THREE.ShaderChunk[ "skinbase_vertex" ],
  9890. "#ifdef USE_ENVMAP",
  9891. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9892. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9893. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9894. "#endif",
  9895. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9896. THREE.ShaderChunk[ "skinning_vertex" ],
  9897. THREE.ShaderChunk[ "default_vertex" ],
  9898. THREE.ShaderChunk[ "worldpos_vertex" ],
  9899. THREE.ShaderChunk[ "envmap_vertex" ],
  9900. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9901. "}"
  9902. ].join("\n"),
  9903. fragmentShader: [
  9904. "uniform vec3 diffuse;",
  9905. "uniform float opacity;",
  9906. THREE.ShaderChunk[ "color_pars_fragment" ],
  9907. THREE.ShaderChunk[ "map_pars_fragment" ],
  9908. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9909. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9910. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9911. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9912. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9913. "void main() {",
  9914. "gl_FragColor = vec4( diffuse, opacity );",
  9915. THREE.ShaderChunk[ "map_fragment" ],
  9916. THREE.ShaderChunk[ "alphatest_fragment" ],
  9917. THREE.ShaderChunk[ "specularmap_fragment" ],
  9918. THREE.ShaderChunk[ "lightmap_fragment" ],
  9919. THREE.ShaderChunk[ "color_fragment" ],
  9920. THREE.ShaderChunk[ "envmap_fragment" ],
  9921. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9922. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9923. THREE.ShaderChunk[ "fog_fragment" ],
  9924. "}"
  9925. ].join("\n")
  9926. },
  9927. 'lambert': {
  9928. uniforms: THREE.UniformsUtils.merge( [
  9929. THREE.UniformsLib[ "common" ],
  9930. THREE.UniformsLib[ "fog" ],
  9931. THREE.UniformsLib[ "lights" ],
  9932. THREE.UniformsLib[ "shadowmap" ],
  9933. {
  9934. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9935. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9936. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9937. }
  9938. ] ),
  9939. vertexShader: [
  9940. "#define LAMBERT",
  9941. "varying vec3 vLightFront;",
  9942. "#ifdef DOUBLE_SIDED",
  9943. "varying vec3 vLightBack;",
  9944. "#endif",
  9945. THREE.ShaderChunk[ "map_pars_vertex" ],
  9946. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9947. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9948. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9949. THREE.ShaderChunk[ "color_pars_vertex" ],
  9950. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9951. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9952. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9953. "void main() {",
  9954. THREE.ShaderChunk[ "map_vertex" ],
  9955. THREE.ShaderChunk[ "lightmap_vertex" ],
  9956. THREE.ShaderChunk[ "color_vertex" ],
  9957. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9958. THREE.ShaderChunk[ "skinbase_vertex" ],
  9959. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9960. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9961. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9962. THREE.ShaderChunk[ "skinning_vertex" ],
  9963. THREE.ShaderChunk[ "default_vertex" ],
  9964. THREE.ShaderChunk[ "worldpos_vertex" ],
  9965. THREE.ShaderChunk[ "envmap_vertex" ],
  9966. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9967. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9968. "}"
  9969. ].join("\n"),
  9970. fragmentShader: [
  9971. "uniform float opacity;",
  9972. "varying vec3 vLightFront;",
  9973. "#ifdef DOUBLE_SIDED",
  9974. "varying vec3 vLightBack;",
  9975. "#endif",
  9976. THREE.ShaderChunk[ "color_pars_fragment" ],
  9977. THREE.ShaderChunk[ "map_pars_fragment" ],
  9978. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9979. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9980. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9981. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9982. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9983. "void main() {",
  9984. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9985. THREE.ShaderChunk[ "map_fragment" ],
  9986. THREE.ShaderChunk[ "alphatest_fragment" ],
  9987. THREE.ShaderChunk[ "specularmap_fragment" ],
  9988. "#ifdef DOUBLE_SIDED",
  9989. //"float isFront = float( gl_FrontFacing );",
  9990. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9991. "if ( gl_FrontFacing )",
  9992. "gl_FragColor.xyz *= vLightFront;",
  9993. "else",
  9994. "gl_FragColor.xyz *= vLightBack;",
  9995. "#else",
  9996. "gl_FragColor.xyz *= vLightFront;",
  9997. "#endif",
  9998. THREE.ShaderChunk[ "lightmap_fragment" ],
  9999. THREE.ShaderChunk[ "color_fragment" ],
  10000. THREE.ShaderChunk[ "envmap_fragment" ],
  10001. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10002. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10003. THREE.ShaderChunk[ "fog_fragment" ],
  10004. "}"
  10005. ].join("\n")
  10006. },
  10007. 'phong': {
  10008. uniforms: THREE.UniformsUtils.merge( [
  10009. THREE.UniformsLib[ "common" ],
  10010. THREE.UniformsLib[ "bump" ],
  10011. THREE.UniformsLib[ "normalmap" ],
  10012. THREE.UniformsLib[ "fog" ],
  10013. THREE.UniformsLib[ "lights" ],
  10014. THREE.UniformsLib[ "shadowmap" ],
  10015. {
  10016. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10017. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10018. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10019. "shininess": { type: "f", value: 30 },
  10020. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10021. }
  10022. ] ),
  10023. vertexShader: [
  10024. "#define PHONG",
  10025. "varying vec3 vViewPosition;",
  10026. "varying vec3 vNormal;",
  10027. THREE.ShaderChunk[ "map_pars_vertex" ],
  10028. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10029. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10030. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10031. THREE.ShaderChunk[ "color_pars_vertex" ],
  10032. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10033. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10034. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10035. "void main() {",
  10036. THREE.ShaderChunk[ "map_vertex" ],
  10037. THREE.ShaderChunk[ "lightmap_vertex" ],
  10038. THREE.ShaderChunk[ "color_vertex" ],
  10039. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10040. THREE.ShaderChunk[ "skinbase_vertex" ],
  10041. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10042. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10043. "vNormal = normalize( transformedNormal );",
  10044. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10045. THREE.ShaderChunk[ "skinning_vertex" ],
  10046. THREE.ShaderChunk[ "default_vertex" ],
  10047. "vViewPosition = -mvPosition.xyz;",
  10048. THREE.ShaderChunk[ "worldpos_vertex" ],
  10049. THREE.ShaderChunk[ "envmap_vertex" ],
  10050. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10051. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10052. "}"
  10053. ].join("\n"),
  10054. fragmentShader: [
  10055. "uniform vec3 diffuse;",
  10056. "uniform float opacity;",
  10057. "uniform vec3 ambient;",
  10058. "uniform vec3 emissive;",
  10059. "uniform vec3 specular;",
  10060. "uniform float shininess;",
  10061. THREE.ShaderChunk[ "color_pars_fragment" ],
  10062. THREE.ShaderChunk[ "map_pars_fragment" ],
  10063. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10064. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10065. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10066. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10067. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10068. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10069. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10070. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10071. "void main() {",
  10072. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10073. THREE.ShaderChunk[ "map_fragment" ],
  10074. THREE.ShaderChunk[ "alphatest_fragment" ],
  10075. THREE.ShaderChunk[ "specularmap_fragment" ],
  10076. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10077. THREE.ShaderChunk[ "lightmap_fragment" ],
  10078. THREE.ShaderChunk[ "color_fragment" ],
  10079. THREE.ShaderChunk[ "envmap_fragment" ],
  10080. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10081. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10082. THREE.ShaderChunk[ "fog_fragment" ],
  10083. "}"
  10084. ].join("\n")
  10085. },
  10086. 'particle_basic': {
  10087. uniforms: THREE.UniformsUtils.merge( [
  10088. THREE.UniformsLib[ "particle" ],
  10089. THREE.UniformsLib[ "shadowmap" ]
  10090. ] ),
  10091. vertexShader: [
  10092. "uniform float size;",
  10093. "uniform float scale;",
  10094. THREE.ShaderChunk[ "color_pars_vertex" ],
  10095. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10096. "void main() {",
  10097. THREE.ShaderChunk[ "color_vertex" ],
  10098. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10099. "#ifdef USE_SIZEATTENUATION",
  10100. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10101. "#else",
  10102. "gl_PointSize = size;",
  10103. "#endif",
  10104. "gl_Position = projectionMatrix * mvPosition;",
  10105. THREE.ShaderChunk[ "worldpos_vertex" ],
  10106. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10107. "}"
  10108. ].join("\n"),
  10109. fragmentShader: [
  10110. "uniform vec3 psColor;",
  10111. "uniform float opacity;",
  10112. THREE.ShaderChunk[ "color_pars_fragment" ],
  10113. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10114. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10115. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10116. "void main() {",
  10117. "gl_FragColor = vec4( psColor, opacity );",
  10118. THREE.ShaderChunk[ "map_particle_fragment" ],
  10119. THREE.ShaderChunk[ "alphatest_fragment" ],
  10120. THREE.ShaderChunk[ "color_fragment" ],
  10121. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10122. THREE.ShaderChunk[ "fog_fragment" ],
  10123. "}"
  10124. ].join("\n")
  10125. },
  10126. 'dashed': {
  10127. uniforms: THREE.UniformsUtils.merge( [
  10128. THREE.UniformsLib[ "common" ],
  10129. THREE.UniformsLib[ "fog" ],
  10130. {
  10131. "scale": { type: "f", value: 1 },
  10132. "dashSize": { type: "f", value: 1 },
  10133. "totalSize": { type: "f", value: 2 }
  10134. }
  10135. ] ),
  10136. vertexShader: [
  10137. "uniform float scale;",
  10138. "attribute float lineDistance;",
  10139. "varying float vLineDistance;",
  10140. THREE.ShaderChunk[ "color_pars_vertex" ],
  10141. "void main() {",
  10142. THREE.ShaderChunk[ "color_vertex" ],
  10143. "vLineDistance = scale * lineDistance;",
  10144. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10145. "gl_Position = projectionMatrix * mvPosition;",
  10146. "}"
  10147. ].join("\n"),
  10148. fragmentShader: [
  10149. "uniform vec3 diffuse;",
  10150. "uniform float opacity;",
  10151. "uniform float dashSize;",
  10152. "uniform float totalSize;",
  10153. "varying float vLineDistance;",
  10154. THREE.ShaderChunk[ "color_pars_fragment" ],
  10155. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10156. "void main() {",
  10157. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10158. "discard;",
  10159. "}",
  10160. "gl_FragColor = vec4( diffuse, opacity );",
  10161. THREE.ShaderChunk[ "color_fragment" ],
  10162. THREE.ShaderChunk[ "fog_fragment" ],
  10163. "}"
  10164. ].join("\n")
  10165. },
  10166. // Depth encoding into RGBA texture
  10167. // based on SpiderGL shadow map example
  10168. // http://spidergl.org/example.php?id=6
  10169. // originally from
  10170. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10171. // see also here:
  10172. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10173. 'depthRGBA': {
  10174. uniforms: {},
  10175. vertexShader: [
  10176. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10177. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10178. "void main() {",
  10179. THREE.ShaderChunk[ "skinbase_vertex" ],
  10180. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10181. THREE.ShaderChunk[ "skinning_vertex" ],
  10182. THREE.ShaderChunk[ "default_vertex" ],
  10183. "}"
  10184. ].join("\n"),
  10185. fragmentShader: [
  10186. "vec4 pack_depth( const in float depth ) {",
  10187. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10188. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10189. "vec4 res = fract( depth * bit_shift );",
  10190. "res -= res.xxyz * bit_mask;",
  10191. "return res;",
  10192. "}",
  10193. "void main() {",
  10194. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10195. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10196. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10197. //"gl_FragData[ 0 ] = pack_depth( z );",
  10198. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10199. "}"
  10200. ].join("\n")
  10201. }
  10202. };
  10203. /**
  10204. * @author supereggbert / http://www.paulbrunt.co.uk/
  10205. * @author mrdoob / http://mrdoob.com/
  10206. * @author alteredq / http://alteredqualia.com/
  10207. * @author szimek / https://github.com/szimek/
  10208. */
  10209. THREE.WebGLRenderer = function ( parameters ) {
  10210. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10211. parameters = parameters || {};
  10212. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10213. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10214. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  10215. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10216. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10217. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10218. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10219. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  10220. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  10221. // public properties
  10222. this.domElement = _canvas;
  10223. this.context = null;
  10224. // clearing
  10225. this.autoClear = true;
  10226. this.autoClearColor = true;
  10227. this.autoClearDepth = true;
  10228. this.autoClearStencil = true;
  10229. // scene graph
  10230. this.sortObjects = true;
  10231. this.autoUpdateObjects = true;
  10232. this.autoUpdateScene = true;
  10233. // physically based shading
  10234. this.gammaInput = false;
  10235. this.gammaOutput = false;
  10236. this.physicallyBasedShading = false;
  10237. // shadow map
  10238. this.shadowMapEnabled = false;
  10239. this.shadowMapAutoUpdate = true;
  10240. this.shadowMapType = THREE.PCFShadowMap;
  10241. this.shadowMapCullFace = THREE.CullFaceFront;
  10242. this.shadowMapDebug = false;
  10243. this.shadowMapCascade = false;
  10244. // morphs
  10245. this.maxMorphTargets = 8;
  10246. this.maxMorphNormals = 4;
  10247. // flags
  10248. this.autoScaleCubemaps = true;
  10249. // custom render plugins
  10250. this.renderPluginsPre = [];
  10251. this.renderPluginsPost = [];
  10252. // info
  10253. this.info = {
  10254. memory: {
  10255. programs: 0,
  10256. geometries: 0,
  10257. textures: 0
  10258. },
  10259. render: {
  10260. calls: 0,
  10261. vertices: 0,
  10262. faces: 0,
  10263. points: 0
  10264. }
  10265. };
  10266. // internal properties
  10267. var _this = this,
  10268. _programs = [],
  10269. _programs_counter = 0,
  10270. // internal state cache
  10271. _currentProgram = null,
  10272. _currentFramebuffer = null,
  10273. _currentMaterialId = -1,
  10274. _currentGeometryGroupHash = null,
  10275. _currentCamera = null,
  10276. _geometryGroupCounter = 0,
  10277. _usedTextureUnits = 0,
  10278. // GL state cache
  10279. _oldDoubleSided = -1,
  10280. _oldFlipSided = -1,
  10281. _oldBlending = -1,
  10282. _oldBlendEquation = -1,
  10283. _oldBlendSrc = -1,
  10284. _oldBlendDst = -1,
  10285. _oldDepthTest = -1,
  10286. _oldDepthWrite = -1,
  10287. _oldPolygonOffset = null,
  10288. _oldPolygonOffsetFactor = null,
  10289. _oldPolygonOffsetUnits = null,
  10290. _oldLineWidth = null,
  10291. _viewportX = 0,
  10292. _viewportY = 0,
  10293. _viewportWidth = 0,
  10294. _viewportHeight = 0,
  10295. _currentWidth = 0,
  10296. _currentHeight = 0,
  10297. _enabledAttributes = {},
  10298. // frustum
  10299. _frustum = new THREE.Frustum(),
  10300. // camera matrices cache
  10301. _projScreenMatrix = new THREE.Matrix4(),
  10302. _projScreenMatrixPS = new THREE.Matrix4(),
  10303. _vector3 = new THREE.Vector3(),
  10304. // light arrays cache
  10305. _direction = new THREE.Vector3(),
  10306. _lightsNeedUpdate = true,
  10307. _lights = {
  10308. ambient: [ 0, 0, 0 ],
  10309. directional: { length: 0, colors: new Array(), positions: new Array() },
  10310. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  10311. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  10312. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  10313. };
  10314. // initialize
  10315. var _gl;
  10316. var _glExtensionTextureFloat;
  10317. var _glExtensionStandardDerivatives;
  10318. var _glExtensionTextureFilterAnisotropic;
  10319. var _glExtensionCompressedTextureS3TC;
  10320. initGL();
  10321. setDefaultGLState();
  10322. this.context = _gl;
  10323. // GPU capabilities
  10324. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10325. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10326. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10327. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10328. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10329. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  10330. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  10331. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  10332. //
  10333. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  10334. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  10335. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  10336. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  10337. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  10338. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  10339. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  10340. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  10341. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  10342. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  10343. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  10344. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  10345. // clamp precision to maximum available
  10346. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  10347. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  10348. if ( _precision === "highp" && ! highpAvailable ) {
  10349. if ( mediumpAvailable ) {
  10350. _precision = "mediump";
  10351. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  10352. } else {
  10353. _precision = "lowp";
  10354. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  10355. }
  10356. }
  10357. if ( _precision === "mediump" && ! mediumpAvailable ) {
  10358. _precision = "lowp";
  10359. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  10360. }
  10361. // API
  10362. this.getContext = function () {
  10363. return _gl;
  10364. };
  10365. this.supportsVertexTextures = function () {
  10366. return _supportsVertexTextures;
  10367. };
  10368. this.getMaxAnisotropy = function () {
  10369. return _maxAnisotropy;
  10370. };
  10371. this.setSize = function ( width, height ) {
  10372. _canvas.width = width;
  10373. _canvas.height = height;
  10374. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  10375. };
  10376. this.setViewport = function ( x, y, width, height ) {
  10377. _viewportX = x !== undefined ? x : 0;
  10378. _viewportY = y !== undefined ? y : 0;
  10379. _viewportWidth = width !== undefined ? width : _canvas.width;
  10380. _viewportHeight = height !== undefined ? height : _canvas.height;
  10381. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10382. };
  10383. this.setScissor = function ( x, y, width, height ) {
  10384. _gl.scissor( x, y, width, height );
  10385. };
  10386. this.enableScissorTest = function ( enable ) {
  10387. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  10388. };
  10389. // Clearing
  10390. this.setClearColorHex = function ( hex, alpha ) {
  10391. _clearColor.setHex( hex );
  10392. _clearAlpha = alpha;
  10393. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10394. };
  10395. this.setClearColor = function ( color, alpha ) {
  10396. _clearColor.copy( color );
  10397. _clearAlpha = alpha;
  10398. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10399. };
  10400. this.getClearColor = function () {
  10401. return _clearColor;
  10402. };
  10403. this.getClearAlpha = function () {
  10404. return _clearAlpha;
  10405. };
  10406. this.clear = function ( color, depth, stencil ) {
  10407. var bits = 0;
  10408. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  10409. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  10410. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  10411. _gl.clear( bits );
  10412. };
  10413. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  10414. this.setRenderTarget( renderTarget );
  10415. this.clear( color, depth, stencil );
  10416. };
  10417. // Plugins
  10418. this.addPostPlugin = function ( plugin ) {
  10419. plugin.init( this );
  10420. this.renderPluginsPost.push( plugin );
  10421. };
  10422. this.addPrePlugin = function ( plugin ) {
  10423. plugin.init( this );
  10424. this.renderPluginsPre.push( plugin );
  10425. };
  10426. // Rendering
  10427. this.updateShadowMap = function ( scene, camera ) {
  10428. _currentProgram = null;
  10429. _oldBlending = -1;
  10430. _oldDepthTest = -1;
  10431. _oldDepthWrite = -1;
  10432. _currentGeometryGroupHash = -1;
  10433. _currentMaterialId = -1;
  10434. _lightsNeedUpdate = true;
  10435. _oldDoubleSided = -1;
  10436. _oldFlipSided = -1;
  10437. this.shadowMapPlugin.update( scene, camera );
  10438. };
  10439. // Internal functions
  10440. // Buffer allocation
  10441. function createParticleBuffers ( geometry ) {
  10442. geometry.__webglVertexBuffer = _gl.createBuffer();
  10443. geometry.__webglColorBuffer = _gl.createBuffer();
  10444. _this.info.memory.geometries ++;
  10445. };
  10446. function createLineBuffers ( geometry ) {
  10447. geometry.__webglVertexBuffer = _gl.createBuffer();
  10448. geometry.__webglColorBuffer = _gl.createBuffer();
  10449. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  10450. _this.info.memory.geometries ++;
  10451. };
  10452. function createRibbonBuffers ( geometry ) {
  10453. geometry.__webglVertexBuffer = _gl.createBuffer();
  10454. geometry.__webglColorBuffer = _gl.createBuffer();
  10455. geometry.__webglNormalBuffer = _gl.createBuffer();
  10456. _this.info.memory.geometries ++;
  10457. };
  10458. function createMeshBuffers ( geometryGroup ) {
  10459. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  10460. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  10461. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  10462. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  10463. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  10464. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  10465. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  10466. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  10467. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  10468. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  10469. var m, ml;
  10470. if ( geometryGroup.numMorphTargets ) {
  10471. geometryGroup.__webglMorphTargetsBuffers = [];
  10472. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10473. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  10474. }
  10475. }
  10476. if ( geometryGroup.numMorphNormals ) {
  10477. geometryGroup.__webglMorphNormalsBuffers = [];
  10478. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10479. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  10480. }
  10481. }
  10482. _this.info.memory.geometries ++;
  10483. };
  10484. // Events
  10485. var onGeometryDispose = function ( event ) {
  10486. var geometry = event.target;
  10487. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10488. deallocateGeometry( geometry );
  10489. _this.info.memory.geometries --;
  10490. };
  10491. var onTextureDispose = function ( event ) {
  10492. var texture = event.target;
  10493. texture.removeEventListener( 'dispose', onTextureDispose );
  10494. deallocateTexture( texture );
  10495. _this.info.memory.textures --;
  10496. };
  10497. var onRenderTargetDispose = function ( event ) {
  10498. var renderTarget = event.target;
  10499. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10500. deallocateRenderTarget( renderTarget );
  10501. _this.info.memory.textures --;
  10502. };
  10503. var onMaterialDispose = function ( event ) {
  10504. var material = event.target;
  10505. material.removeEventListener( 'dispose', onMaterialDispose );
  10506. deallocateMaterial( material );
  10507. };
  10508. // Buffer deallocation
  10509. var deallocateGeometry = function ( geometry ) {
  10510. geometry.__webglInit = undefined;
  10511. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10512. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10513. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  10514. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  10515. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  10516. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  10517. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  10518. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  10519. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  10520. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  10521. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10522. // geometry groups
  10523. if ( geometry.geometryGroups !== undefined ) {
  10524. for ( var g in geometry.geometryGroups ) {
  10525. var geometryGroup = geometry.geometryGroups[ g ];
  10526. if ( geometryGroup.numMorphTargets !== undefined ) {
  10527. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10528. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10529. }
  10530. }
  10531. if ( geometryGroup.numMorphNormals !== undefined ) {
  10532. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10533. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10534. }
  10535. }
  10536. deleteCustomAttributesBuffers( geometryGroup );
  10537. }
  10538. }
  10539. deleteCustomAttributesBuffers( geometry );
  10540. };
  10541. var deallocateTexture = function ( texture ) {
  10542. if ( texture.image && texture.image.__webglTextureCube ) {
  10543. // cube texture
  10544. _gl.deleteTexture( texture.image.__webglTextureCube );
  10545. } else {
  10546. // 2D texture
  10547. if ( ! texture.__webglInit ) return;
  10548. texture.__webglInit = false;
  10549. _gl.deleteTexture( texture.__webglTexture );
  10550. }
  10551. };
  10552. var deallocateRenderTarget = function ( renderTarget ) {
  10553. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  10554. _gl.deleteTexture( renderTarget.__webglTexture );
  10555. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  10556. for ( var i = 0; i < 6; i ++ ) {
  10557. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  10558. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  10559. }
  10560. } else {
  10561. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  10562. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  10563. }
  10564. };
  10565. var deallocateMaterial = function ( material ) {
  10566. var program = material.program;
  10567. if ( program === undefined ) return;
  10568. material.program = undefined;
  10569. // only deallocate GL program if this was the last use of shared program
  10570. // assumed there is only single copy of any program in the _programs list
  10571. // (that's how it's constructed)
  10572. var i, il, programInfo;
  10573. var deleteProgram = false;
  10574. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10575. programInfo = _programs[ i ];
  10576. if ( programInfo.program === program ) {
  10577. programInfo.usedTimes --;
  10578. if ( programInfo.usedTimes === 0 ) {
  10579. deleteProgram = true;
  10580. }
  10581. break;
  10582. }
  10583. }
  10584. if ( deleteProgram === true ) {
  10585. // avoid using array.splice, this is costlier than creating new array from scratch
  10586. var newPrograms = [];
  10587. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10588. programInfo = _programs[ i ];
  10589. if ( programInfo.program !== program ) {
  10590. newPrograms.push( programInfo );
  10591. }
  10592. }
  10593. _programs = newPrograms;
  10594. _gl.deleteProgram( program );
  10595. _this.info.memory.programs --;
  10596. }
  10597. };
  10598. //
  10599. /*
  10600. function deleteParticleBuffers ( geometry ) {
  10601. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10602. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10603. deleteCustomAttributesBuffers( geometry );
  10604. _this.info.memory.geometries --;
  10605. };
  10606. function deleteLineBuffers ( geometry ) {
  10607. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10608. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10609. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10610. deleteCustomAttributesBuffers( geometry );
  10611. _this.info.memory.geometries --;
  10612. };
  10613. function deleteRibbonBuffers ( geometry ) {
  10614. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10615. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10616. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10617. deleteCustomAttributesBuffers( geometry );
  10618. _this.info.memory.geometries --;
  10619. };
  10620. function deleteMeshBuffers ( geometryGroup ) {
  10621. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  10622. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  10623. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  10624. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  10625. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  10626. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  10627. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  10628. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  10629. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  10630. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  10631. var m, ml;
  10632. if ( geometryGroup.numMorphTargets ) {
  10633. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10634. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10635. }
  10636. }
  10637. if ( geometryGroup.numMorphNormals ) {
  10638. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10639. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10640. }
  10641. }
  10642. deleteCustomAttributesBuffers( geometryGroup );
  10643. _this.info.memory.geometries --;
  10644. };
  10645. */
  10646. function deleteCustomAttributesBuffers( geometry ) {
  10647. if ( geometry.__webglCustomAttributesList ) {
  10648. for ( var id in geometry.__webglCustomAttributesList ) {
  10649. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  10650. }
  10651. }
  10652. };
  10653. // Buffer initialization
  10654. function initCustomAttributes ( geometry, object ) {
  10655. var nvertices = geometry.vertices.length;
  10656. var material = object.material;
  10657. if ( material.attributes ) {
  10658. if ( geometry.__webglCustomAttributesList === undefined ) {
  10659. geometry.__webglCustomAttributesList = [];
  10660. }
  10661. for ( var a in material.attributes ) {
  10662. var attribute = material.attributes[ a ];
  10663. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10664. attribute.__webglInitialized = true;
  10665. var size = 1; // "f" and "i"
  10666. if ( attribute.type === "v2" ) size = 2;
  10667. else if ( attribute.type === "v3" ) size = 3;
  10668. else if ( attribute.type === "v4" ) size = 4;
  10669. else if ( attribute.type === "c" ) size = 3;
  10670. attribute.size = size;
  10671. attribute.array = new Float32Array( nvertices * size );
  10672. attribute.buffer = _gl.createBuffer();
  10673. attribute.buffer.belongsToAttribute = a;
  10674. attribute.needsUpdate = true;
  10675. }
  10676. geometry.__webglCustomAttributesList.push( attribute );
  10677. }
  10678. }
  10679. };
  10680. function initParticleBuffers ( geometry, object ) {
  10681. var nvertices = geometry.vertices.length;
  10682. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10683. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10684. geometry.__sortArray = [];
  10685. geometry.__webglParticleCount = nvertices;
  10686. initCustomAttributes ( geometry, object );
  10687. };
  10688. function initLineBuffers ( geometry, object ) {
  10689. var nvertices = geometry.vertices.length;
  10690. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10691. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10692. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  10693. geometry.__webglLineCount = nvertices;
  10694. initCustomAttributes ( geometry, object );
  10695. };
  10696. function initRibbonBuffers ( geometry, object ) {
  10697. var nvertices = geometry.vertices.length;
  10698. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10699. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10700. geometry.__normalArray = new Float32Array( nvertices * 3 );
  10701. geometry.__webglVertexCount = nvertices;
  10702. initCustomAttributes ( geometry, object );
  10703. };
  10704. function initMeshBuffers ( geometryGroup, object ) {
  10705. var geometry = object.geometry,
  10706. faces3 = geometryGroup.faces3,
  10707. faces4 = geometryGroup.faces4,
  10708. nvertices = faces3.length * 3 + faces4.length * 4,
  10709. ntris = faces3.length * 1 + faces4.length * 2,
  10710. nlines = faces3.length * 3 + faces4.length * 4,
  10711. material = getBufferMaterial( object, geometryGroup ),
  10712. uvType = bufferGuessUVType( material ),
  10713. normalType = bufferGuessNormalType( material ),
  10714. vertexColorType = bufferGuessVertexColorType( material );
  10715. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  10716. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  10717. if ( normalType ) {
  10718. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  10719. }
  10720. if ( geometry.hasTangents ) {
  10721. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  10722. }
  10723. if ( vertexColorType ) {
  10724. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  10725. }
  10726. if ( uvType ) {
  10727. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  10728. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  10729. }
  10730. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  10731. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  10732. }
  10733. }
  10734. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  10735. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  10736. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  10737. }
  10738. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  10739. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  10740. var m, ml;
  10741. if ( geometryGroup.numMorphTargets ) {
  10742. geometryGroup.__morphTargetsArrays = [];
  10743. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10744. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  10745. }
  10746. }
  10747. if ( geometryGroup.numMorphNormals ) {
  10748. geometryGroup.__morphNormalsArrays = [];
  10749. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10750. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  10751. }
  10752. }
  10753. geometryGroup.__webglFaceCount = ntris * 3;
  10754. geometryGroup.__webglLineCount = nlines * 2;
  10755. // custom attributes
  10756. if ( material.attributes ) {
  10757. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  10758. geometryGroup.__webglCustomAttributesList = [];
  10759. }
  10760. for ( var a in material.attributes ) {
  10761. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  10762. // attribute buffers which are correctly indexed in the setMeshBuffers function
  10763. var originalAttribute = material.attributes[ a ];
  10764. var attribute = {};
  10765. for ( var property in originalAttribute ) {
  10766. attribute[ property ] = originalAttribute[ property ];
  10767. }
  10768. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10769. attribute.__webglInitialized = true;
  10770. var size = 1; // "f" and "i"
  10771. if( attribute.type === "v2" ) size = 2;
  10772. else if( attribute.type === "v3" ) size = 3;
  10773. else if( attribute.type === "v4" ) size = 4;
  10774. else if( attribute.type === "c" ) size = 3;
  10775. attribute.size = size;
  10776. attribute.array = new Float32Array( nvertices * size );
  10777. attribute.buffer = _gl.createBuffer();
  10778. attribute.buffer.belongsToAttribute = a;
  10779. originalAttribute.needsUpdate = true;
  10780. attribute.__original = originalAttribute;
  10781. }
  10782. geometryGroup.__webglCustomAttributesList.push( attribute );
  10783. }
  10784. }
  10785. geometryGroup.__inittedArrays = true;
  10786. };
  10787. function getBufferMaterial( object, geometryGroup ) {
  10788. return object.material instanceof THREE.MeshFaceMaterial
  10789. ? object.material.materials[ geometryGroup.materialIndex ]
  10790. : object.material;
  10791. };
  10792. function materialNeedsSmoothNormals ( material ) {
  10793. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  10794. };
  10795. function bufferGuessNormalType ( material ) {
  10796. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  10797. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  10798. return false;
  10799. }
  10800. if ( materialNeedsSmoothNormals( material ) ) {
  10801. return THREE.SmoothShading;
  10802. } else {
  10803. return THREE.FlatShading;
  10804. }
  10805. };
  10806. function bufferGuessVertexColorType ( material ) {
  10807. if ( material.vertexColors ) {
  10808. return material.vertexColors;
  10809. }
  10810. return false;
  10811. };
  10812. function bufferGuessUVType ( material ) {
  10813. // material must use some texture to require uvs
  10814. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  10815. return true;
  10816. }
  10817. return false;
  10818. };
  10819. //
  10820. function initDirectBuffers( geometry ) {
  10821. var a, attribute, type;
  10822. for ( a in geometry.attributes ) {
  10823. if ( a === "index" ) {
  10824. type = _gl.ELEMENT_ARRAY_BUFFER;
  10825. } else {
  10826. type = _gl.ARRAY_BUFFER;
  10827. }
  10828. attribute = geometry.attributes[ a ];
  10829. attribute.buffer = _gl.createBuffer();
  10830. _gl.bindBuffer( type, attribute.buffer );
  10831. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  10832. }
  10833. };
  10834. // Buffer setting
  10835. function setParticleBuffers ( geometry, hint, object ) {
  10836. var v, c, vertex, offset, index, color,
  10837. vertices = geometry.vertices,
  10838. vl = vertices.length,
  10839. colors = geometry.colors,
  10840. cl = colors.length,
  10841. vertexArray = geometry.__vertexArray,
  10842. colorArray = geometry.__colorArray,
  10843. sortArray = geometry.__sortArray,
  10844. dirtyVertices = geometry.verticesNeedUpdate,
  10845. dirtyElements = geometry.elementsNeedUpdate,
  10846. dirtyColors = geometry.colorsNeedUpdate,
  10847. customAttributes = geometry.__webglCustomAttributesList,
  10848. i, il,
  10849. a, ca, cal, value,
  10850. customAttribute;
  10851. if ( object.sortParticles ) {
  10852. _projScreenMatrixPS.copy( _projScreenMatrix );
  10853. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  10854. for ( v = 0; v < vl; v ++ ) {
  10855. vertex = vertices[ v ];
  10856. _vector3.copy( vertex );
  10857. _projScreenMatrixPS.multiplyVector3( _vector3 );
  10858. sortArray[ v ] = [ _vector3.z, v ];
  10859. }
  10860. sortArray.sort( numericalSort );
  10861. for ( v = 0; v < vl; v ++ ) {
  10862. vertex = vertices[ sortArray[v][1] ];
  10863. offset = v * 3;
  10864. vertexArray[ offset ] = vertex.x;
  10865. vertexArray[ offset + 1 ] = vertex.y;
  10866. vertexArray[ offset + 2 ] = vertex.z;
  10867. }
  10868. for ( c = 0; c < cl; c ++ ) {
  10869. offset = c * 3;
  10870. color = colors[ sortArray[c][1] ];
  10871. colorArray[ offset ] = color.r;
  10872. colorArray[ offset + 1 ] = color.g;
  10873. colorArray[ offset + 2 ] = color.b;
  10874. }
  10875. if ( customAttributes ) {
  10876. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10877. customAttribute = customAttributes[ i ];
  10878. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  10879. offset = 0;
  10880. cal = customAttribute.value.length;
  10881. if ( customAttribute.size === 1 ) {
  10882. for ( ca = 0; ca < cal; ca ++ ) {
  10883. index = sortArray[ ca ][ 1 ];
  10884. customAttribute.array[ ca ] = customAttribute.value[ index ];
  10885. }
  10886. } else if ( customAttribute.size === 2 ) {
  10887. for ( ca = 0; ca < cal; ca ++ ) {
  10888. index = sortArray[ ca ][ 1 ];
  10889. value = customAttribute.value[ index ];
  10890. customAttribute.array[ offset ] = value.x;
  10891. customAttribute.array[ offset + 1 ] = value.y;
  10892. offset += 2;
  10893. }
  10894. } else if ( customAttribute.size === 3 ) {
  10895. if ( customAttribute.type === "c" ) {
  10896. for ( ca = 0; ca < cal; ca ++ ) {
  10897. index = sortArray[ ca ][ 1 ];
  10898. value = customAttribute.value[ index ];
  10899. customAttribute.array[ offset ] = value.r;
  10900. customAttribute.array[ offset + 1 ] = value.g;
  10901. customAttribute.array[ offset + 2 ] = value.b;
  10902. offset += 3;
  10903. }
  10904. } else {
  10905. for ( ca = 0; ca < cal; ca ++ ) {
  10906. index = sortArray[ ca ][ 1 ];
  10907. value = customAttribute.value[ index ];
  10908. customAttribute.array[ offset ] = value.x;
  10909. customAttribute.array[ offset + 1 ] = value.y;
  10910. customAttribute.array[ offset + 2 ] = value.z;
  10911. offset += 3;
  10912. }
  10913. }
  10914. } else if ( customAttribute.size === 4 ) {
  10915. for ( ca = 0; ca < cal; ca ++ ) {
  10916. index = sortArray[ ca ][ 1 ];
  10917. value = customAttribute.value[ index ];
  10918. customAttribute.array[ offset ] = value.x;
  10919. customAttribute.array[ offset + 1 ] = value.y;
  10920. customAttribute.array[ offset + 2 ] = value.z;
  10921. customAttribute.array[ offset + 3 ] = value.w;
  10922. offset += 4;
  10923. }
  10924. }
  10925. }
  10926. }
  10927. } else {
  10928. if ( dirtyVertices ) {
  10929. for ( v = 0; v < vl; v ++ ) {
  10930. vertex = vertices[ v ];
  10931. offset = v * 3;
  10932. vertexArray[ offset ] = vertex.x;
  10933. vertexArray[ offset + 1 ] = vertex.y;
  10934. vertexArray[ offset + 2 ] = vertex.z;
  10935. }
  10936. }
  10937. if ( dirtyColors ) {
  10938. for ( c = 0; c < cl; c ++ ) {
  10939. color = colors[ c ];
  10940. offset = c * 3;
  10941. colorArray[ offset ] = color.r;
  10942. colorArray[ offset + 1 ] = color.g;
  10943. colorArray[ offset + 2 ] = color.b;
  10944. }
  10945. }
  10946. if ( customAttributes ) {
  10947. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10948. customAttribute = customAttributes[ i ];
  10949. if ( customAttribute.needsUpdate &&
  10950. ( customAttribute.boundTo === undefined ||
  10951. customAttribute.boundTo === "vertices") ) {
  10952. cal = customAttribute.value.length;
  10953. offset = 0;
  10954. if ( customAttribute.size === 1 ) {
  10955. for ( ca = 0; ca < cal; ca ++ ) {
  10956. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10957. }
  10958. } else if ( customAttribute.size === 2 ) {
  10959. for ( ca = 0; ca < cal; ca ++ ) {
  10960. value = customAttribute.value[ ca ];
  10961. customAttribute.array[ offset ] = value.x;
  10962. customAttribute.array[ offset + 1 ] = value.y;
  10963. offset += 2;
  10964. }
  10965. } else if ( customAttribute.size === 3 ) {
  10966. if ( customAttribute.type === "c" ) {
  10967. for ( ca = 0; ca < cal; ca ++ ) {
  10968. value = customAttribute.value[ ca ];
  10969. customAttribute.array[ offset ] = value.r;
  10970. customAttribute.array[ offset + 1 ] = value.g;
  10971. customAttribute.array[ offset + 2 ] = value.b;
  10972. offset += 3;
  10973. }
  10974. } else {
  10975. for ( ca = 0; ca < cal; ca ++ ) {
  10976. value = customAttribute.value[ ca ];
  10977. customAttribute.array[ offset ] = value.x;
  10978. customAttribute.array[ offset + 1 ] = value.y;
  10979. customAttribute.array[ offset + 2 ] = value.z;
  10980. offset += 3;
  10981. }
  10982. }
  10983. } else if ( customAttribute.size === 4 ) {
  10984. for ( ca = 0; ca < cal; ca ++ ) {
  10985. value = customAttribute.value[ ca ];
  10986. customAttribute.array[ offset ] = value.x;
  10987. customAttribute.array[ offset + 1 ] = value.y;
  10988. customAttribute.array[ offset + 2 ] = value.z;
  10989. customAttribute.array[ offset + 3 ] = value.w;
  10990. offset += 4;
  10991. }
  10992. }
  10993. }
  10994. }
  10995. }
  10996. }
  10997. if ( dirtyVertices || object.sortParticles ) {
  10998. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10999. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11000. }
  11001. if ( dirtyColors || object.sortParticles ) {
  11002. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11003. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11004. }
  11005. if ( customAttributes ) {
  11006. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11007. customAttribute = customAttributes[ i ];
  11008. if ( customAttribute.needsUpdate || object.sortParticles ) {
  11009. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11010. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11011. }
  11012. }
  11013. }
  11014. };
  11015. function setLineBuffers ( geometry, hint ) {
  11016. var v, c, d, vertex, offset, color,
  11017. vertices = geometry.vertices,
  11018. colors = geometry.colors,
  11019. lineDistances = geometry.lineDistances,
  11020. vl = vertices.length,
  11021. cl = colors.length,
  11022. dl = lineDistances.length,
  11023. vertexArray = geometry.__vertexArray,
  11024. colorArray = geometry.__colorArray,
  11025. lineDistanceArray = geometry.__lineDistanceArray,
  11026. dirtyVertices = geometry.verticesNeedUpdate,
  11027. dirtyColors = geometry.colorsNeedUpdate,
  11028. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  11029. customAttributes = geometry.__webglCustomAttributesList,
  11030. i, il,
  11031. a, ca, cal, value,
  11032. customAttribute;
  11033. if ( dirtyVertices ) {
  11034. for ( v = 0; v < vl; v ++ ) {
  11035. vertex = vertices[ v ];
  11036. offset = v * 3;
  11037. vertexArray[ offset ] = vertex.x;
  11038. vertexArray[ offset + 1 ] = vertex.y;
  11039. vertexArray[ offset + 2 ] = vertex.z;
  11040. }
  11041. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11042. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11043. }
  11044. if ( dirtyColors ) {
  11045. for ( c = 0; c < cl; c ++ ) {
  11046. color = colors[ c ];
  11047. offset = c * 3;
  11048. colorArray[ offset ] = color.r;
  11049. colorArray[ offset + 1 ] = color.g;
  11050. colorArray[ offset + 2 ] = color.b;
  11051. }
  11052. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11053. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11054. }
  11055. if ( dirtyLineDistances ) {
  11056. for ( d = 0; d < dl; d ++ ) {
  11057. lineDistanceArray[ d ] = lineDistances[ d ];
  11058. }
  11059. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  11060. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  11061. }
  11062. if ( customAttributes ) {
  11063. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11064. customAttribute = customAttributes[ i ];
  11065. if ( customAttribute.needsUpdate &&
  11066. ( customAttribute.boundTo === undefined ||
  11067. customAttribute.boundTo === "vertices" ) ) {
  11068. offset = 0;
  11069. cal = customAttribute.value.length;
  11070. if ( customAttribute.size === 1 ) {
  11071. for ( ca = 0; ca < cal; ca ++ ) {
  11072. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11073. }
  11074. } else if ( customAttribute.size === 2 ) {
  11075. for ( ca = 0; ca < cal; ca ++ ) {
  11076. value = customAttribute.value[ ca ];
  11077. customAttribute.array[ offset ] = value.x;
  11078. customAttribute.array[ offset + 1 ] = value.y;
  11079. offset += 2;
  11080. }
  11081. } else if ( customAttribute.size === 3 ) {
  11082. if ( customAttribute.type === "c" ) {
  11083. for ( ca = 0; ca < cal; ca ++ ) {
  11084. value = customAttribute.value[ ca ];
  11085. customAttribute.array[ offset ] = value.r;
  11086. customAttribute.array[ offset + 1 ] = value.g;
  11087. customAttribute.array[ offset + 2 ] = value.b;
  11088. offset += 3;
  11089. }
  11090. } else {
  11091. for ( ca = 0; ca < cal; ca ++ ) {
  11092. value = customAttribute.value[ ca ];
  11093. customAttribute.array[ offset ] = value.x;
  11094. customAttribute.array[ offset + 1 ] = value.y;
  11095. customAttribute.array[ offset + 2 ] = value.z;
  11096. offset += 3;
  11097. }
  11098. }
  11099. } else if ( customAttribute.size === 4 ) {
  11100. for ( ca = 0; ca < cal; ca ++ ) {
  11101. value = customAttribute.value[ ca ];
  11102. customAttribute.array[ offset ] = value.x;
  11103. customAttribute.array[ offset + 1 ] = value.y;
  11104. customAttribute.array[ offset + 2 ] = value.z;
  11105. customAttribute.array[ offset + 3 ] = value.w;
  11106. offset += 4;
  11107. }
  11108. }
  11109. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11110. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11111. }
  11112. }
  11113. }
  11114. };
  11115. function setRibbonBuffers ( geometry, hint ) {
  11116. var v, c, n, vertex, offset, color, normal,
  11117. i, il, ca, cal, customAttribute, value,
  11118. vertices = geometry.vertices,
  11119. colors = geometry.colors,
  11120. normals = geometry.normals,
  11121. vl = vertices.length,
  11122. cl = colors.length,
  11123. nl = normals.length,
  11124. vertexArray = geometry.__vertexArray,
  11125. colorArray = geometry.__colorArray,
  11126. normalArray = geometry.__normalArray,
  11127. dirtyVertices = geometry.verticesNeedUpdate,
  11128. dirtyColors = geometry.colorsNeedUpdate,
  11129. dirtyNormals = geometry.normalsNeedUpdate,
  11130. customAttributes = geometry.__webglCustomAttributesList;
  11131. if ( dirtyVertices ) {
  11132. for ( v = 0; v < vl; v ++ ) {
  11133. vertex = vertices[ v ];
  11134. offset = v * 3;
  11135. vertexArray[ offset ] = vertex.x;
  11136. vertexArray[ offset + 1 ] = vertex.y;
  11137. vertexArray[ offset + 2 ] = vertex.z;
  11138. }
  11139. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11140. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11141. }
  11142. if ( dirtyColors ) {
  11143. for ( c = 0; c < cl; c ++ ) {
  11144. color = colors[ c ];
  11145. offset = c * 3;
  11146. colorArray[ offset ] = color.r;
  11147. colorArray[ offset + 1 ] = color.g;
  11148. colorArray[ offset + 2 ] = color.b;
  11149. }
  11150. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11151. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11152. }
  11153. if ( dirtyNormals ) {
  11154. for ( n = 0; n < nl; n ++ ) {
  11155. normal = normals[ n ];
  11156. offset = n * 3;
  11157. normalArray[ offset ] = normal.x;
  11158. normalArray[ offset + 1 ] = normal.y;
  11159. normalArray[ offset + 2 ] = normal.z;
  11160. }
  11161. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  11162. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11163. }
  11164. if ( customAttributes ) {
  11165. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11166. customAttribute = customAttributes[ i ];
  11167. if ( customAttribute.needsUpdate &&
  11168. ( customAttribute.boundTo === undefined ||
  11169. customAttribute.boundTo === "vertices" ) ) {
  11170. offset = 0;
  11171. cal = customAttribute.value.length;
  11172. if ( customAttribute.size === 1 ) {
  11173. for ( ca = 0; ca < cal; ca ++ ) {
  11174. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11175. }
  11176. } else if ( customAttribute.size === 2 ) {
  11177. for ( ca = 0; ca < cal; ca ++ ) {
  11178. value = customAttribute.value[ ca ];
  11179. customAttribute.array[ offset ] = value.x;
  11180. customAttribute.array[ offset + 1 ] = value.y;
  11181. offset += 2;
  11182. }
  11183. } else if ( customAttribute.size === 3 ) {
  11184. if ( customAttribute.type === "c" ) {
  11185. for ( ca = 0; ca < cal; ca ++ ) {
  11186. value = customAttribute.value[ ca ];
  11187. customAttribute.array[ offset ] = value.r;
  11188. customAttribute.array[ offset + 1 ] = value.g;
  11189. customAttribute.array[ offset + 2 ] = value.b;
  11190. offset += 3;
  11191. }
  11192. } else {
  11193. for ( ca = 0; ca < cal; ca ++ ) {
  11194. value = customAttribute.value[ ca ];
  11195. customAttribute.array[ offset ] = value.x;
  11196. customAttribute.array[ offset + 1 ] = value.y;
  11197. customAttribute.array[ offset + 2 ] = value.z;
  11198. offset += 3;
  11199. }
  11200. }
  11201. } else if ( customAttribute.size === 4 ) {
  11202. for ( ca = 0; ca < cal; ca ++ ) {
  11203. value = customAttribute.value[ ca ];
  11204. customAttribute.array[ offset ] = value.x;
  11205. customAttribute.array[ offset + 1 ] = value.y;
  11206. customAttribute.array[ offset + 2 ] = value.z;
  11207. customAttribute.array[ offset + 3 ] = value.w;
  11208. offset += 4;
  11209. }
  11210. }
  11211. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11212. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11213. }
  11214. }
  11215. }
  11216. };
  11217. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  11218. if ( ! geometryGroup.__inittedArrays ) {
  11219. return;
  11220. }
  11221. var normalType = bufferGuessNormalType( material ),
  11222. vertexColorType = bufferGuessVertexColorType( material ),
  11223. uvType = bufferGuessUVType( material ),
  11224. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  11225. var f, fl, fi, face,
  11226. vertexNormals, faceNormal, normal,
  11227. vertexColors, faceColor,
  11228. vertexTangents,
  11229. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  11230. c1, c2, c3, c4,
  11231. sw1, sw2, sw3, sw4,
  11232. si1, si2, si3, si4,
  11233. sa1, sa2, sa3, sa4,
  11234. sb1, sb2, sb3, sb4,
  11235. m, ml, i, il,
  11236. vn, uvi, uv2i,
  11237. vk, vkl, vka,
  11238. nka, chf, faceVertexNormals,
  11239. a,
  11240. vertexIndex = 0,
  11241. offset = 0,
  11242. offset_uv = 0,
  11243. offset_uv2 = 0,
  11244. offset_face = 0,
  11245. offset_normal = 0,
  11246. offset_tangent = 0,
  11247. offset_line = 0,
  11248. offset_color = 0,
  11249. offset_skin = 0,
  11250. offset_morphTarget = 0,
  11251. offset_custom = 0,
  11252. offset_customSrc = 0,
  11253. value,
  11254. vertexArray = geometryGroup.__vertexArray,
  11255. uvArray = geometryGroup.__uvArray,
  11256. uv2Array = geometryGroup.__uv2Array,
  11257. normalArray = geometryGroup.__normalArray,
  11258. tangentArray = geometryGroup.__tangentArray,
  11259. colorArray = geometryGroup.__colorArray,
  11260. skinIndexArray = geometryGroup.__skinIndexArray,
  11261. skinWeightArray = geometryGroup.__skinWeightArray,
  11262. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  11263. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  11264. customAttributes = geometryGroup.__webglCustomAttributesList,
  11265. customAttribute,
  11266. faceArray = geometryGroup.__faceArray,
  11267. lineArray = geometryGroup.__lineArray,
  11268. geometry = object.geometry, // this is shared for all chunks
  11269. dirtyVertices = geometry.verticesNeedUpdate,
  11270. dirtyElements = geometry.elementsNeedUpdate,
  11271. dirtyUvs = geometry.uvsNeedUpdate,
  11272. dirtyNormals = geometry.normalsNeedUpdate,
  11273. dirtyTangents = geometry.tangentsNeedUpdate,
  11274. dirtyColors = geometry.colorsNeedUpdate,
  11275. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  11276. vertices = geometry.vertices,
  11277. chunk_faces3 = geometryGroup.faces3,
  11278. chunk_faces4 = geometryGroup.faces4,
  11279. obj_faces = geometry.faces,
  11280. obj_uvs = geometry.faceVertexUvs[ 0 ],
  11281. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  11282. obj_colors = geometry.colors,
  11283. obj_skinIndices = geometry.skinIndices,
  11284. obj_skinWeights = geometry.skinWeights,
  11285. morphTargets = geometry.morphTargets,
  11286. morphNormals = geometry.morphNormals;
  11287. if ( dirtyVertices ) {
  11288. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11289. face = obj_faces[ chunk_faces3[ f ] ];
  11290. v1 = vertices[ face.a ];
  11291. v2 = vertices[ face.b ];
  11292. v3 = vertices[ face.c ];
  11293. vertexArray[ offset ] = v1.x;
  11294. vertexArray[ offset + 1 ] = v1.y;
  11295. vertexArray[ offset + 2 ] = v1.z;
  11296. vertexArray[ offset + 3 ] = v2.x;
  11297. vertexArray[ offset + 4 ] = v2.y;
  11298. vertexArray[ offset + 5 ] = v2.z;
  11299. vertexArray[ offset + 6 ] = v3.x;
  11300. vertexArray[ offset + 7 ] = v3.y;
  11301. vertexArray[ offset + 8 ] = v3.z;
  11302. offset += 9;
  11303. }
  11304. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11305. face = obj_faces[ chunk_faces4[ f ] ];
  11306. v1 = vertices[ face.a ];
  11307. v2 = vertices[ face.b ];
  11308. v3 = vertices[ face.c ];
  11309. v4 = vertices[ face.d ];
  11310. vertexArray[ offset ] = v1.x;
  11311. vertexArray[ offset + 1 ] = v1.y;
  11312. vertexArray[ offset + 2 ] = v1.z;
  11313. vertexArray[ offset + 3 ] = v2.x;
  11314. vertexArray[ offset + 4 ] = v2.y;
  11315. vertexArray[ offset + 5 ] = v2.z;
  11316. vertexArray[ offset + 6 ] = v3.x;
  11317. vertexArray[ offset + 7 ] = v3.y;
  11318. vertexArray[ offset + 8 ] = v3.z;
  11319. vertexArray[ offset + 9 ] = v4.x;
  11320. vertexArray[ offset + 10 ] = v4.y;
  11321. vertexArray[ offset + 11 ] = v4.z;
  11322. offset += 12;
  11323. }
  11324. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11325. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11326. }
  11327. if ( dirtyMorphTargets ) {
  11328. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  11329. offset_morphTarget = 0;
  11330. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11331. chf = chunk_faces3[ f ];
  11332. face = obj_faces[ chf ];
  11333. // morph positions
  11334. v1 = morphTargets[ vk ].vertices[ face.a ];
  11335. v2 = morphTargets[ vk ].vertices[ face.b ];
  11336. v3 = morphTargets[ vk ].vertices[ face.c ];
  11337. vka = morphTargetsArrays[ vk ];
  11338. vka[ offset_morphTarget ] = v1.x;
  11339. vka[ offset_morphTarget + 1 ] = v1.y;
  11340. vka[ offset_morphTarget + 2 ] = v1.z;
  11341. vka[ offset_morphTarget + 3 ] = v2.x;
  11342. vka[ offset_morphTarget + 4 ] = v2.y;
  11343. vka[ offset_morphTarget + 5 ] = v2.z;
  11344. vka[ offset_morphTarget + 6 ] = v3.x;
  11345. vka[ offset_morphTarget + 7 ] = v3.y;
  11346. vka[ offset_morphTarget + 8 ] = v3.z;
  11347. // morph normals
  11348. if ( material.morphNormals ) {
  11349. if ( needsSmoothNormals ) {
  11350. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11351. n1 = faceVertexNormals.a;
  11352. n2 = faceVertexNormals.b;
  11353. n3 = faceVertexNormals.c;
  11354. } else {
  11355. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11356. n2 = n1;
  11357. n3 = n1;
  11358. }
  11359. nka = morphNormalsArrays[ vk ];
  11360. nka[ offset_morphTarget ] = n1.x;
  11361. nka[ offset_morphTarget + 1 ] = n1.y;
  11362. nka[ offset_morphTarget + 2 ] = n1.z;
  11363. nka[ offset_morphTarget + 3 ] = n2.x;
  11364. nka[ offset_morphTarget + 4 ] = n2.y;
  11365. nka[ offset_morphTarget + 5 ] = n2.z;
  11366. nka[ offset_morphTarget + 6 ] = n3.x;
  11367. nka[ offset_morphTarget + 7 ] = n3.y;
  11368. nka[ offset_morphTarget + 8 ] = n3.z;
  11369. }
  11370. //
  11371. offset_morphTarget += 9;
  11372. }
  11373. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11374. chf = chunk_faces4[ f ];
  11375. face = obj_faces[ chf ];
  11376. // morph positions
  11377. v1 = morphTargets[ vk ].vertices[ face.a ];
  11378. v2 = morphTargets[ vk ].vertices[ face.b ];
  11379. v3 = morphTargets[ vk ].vertices[ face.c ];
  11380. v4 = morphTargets[ vk ].vertices[ face.d ];
  11381. vka = morphTargetsArrays[ vk ];
  11382. vka[ offset_morphTarget ] = v1.x;
  11383. vka[ offset_morphTarget + 1 ] = v1.y;
  11384. vka[ offset_morphTarget + 2 ] = v1.z;
  11385. vka[ offset_morphTarget + 3 ] = v2.x;
  11386. vka[ offset_morphTarget + 4 ] = v2.y;
  11387. vka[ offset_morphTarget + 5 ] = v2.z;
  11388. vka[ offset_morphTarget + 6 ] = v3.x;
  11389. vka[ offset_morphTarget + 7 ] = v3.y;
  11390. vka[ offset_morphTarget + 8 ] = v3.z;
  11391. vka[ offset_morphTarget + 9 ] = v4.x;
  11392. vka[ offset_morphTarget + 10 ] = v4.y;
  11393. vka[ offset_morphTarget + 11 ] = v4.z;
  11394. // morph normals
  11395. if ( material.morphNormals ) {
  11396. if ( needsSmoothNormals ) {
  11397. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11398. n1 = faceVertexNormals.a;
  11399. n2 = faceVertexNormals.b;
  11400. n3 = faceVertexNormals.c;
  11401. n4 = faceVertexNormals.d;
  11402. } else {
  11403. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11404. n2 = n1;
  11405. n3 = n1;
  11406. n4 = n1;
  11407. }
  11408. nka = morphNormalsArrays[ vk ];
  11409. nka[ offset_morphTarget ] = n1.x;
  11410. nka[ offset_morphTarget + 1 ] = n1.y;
  11411. nka[ offset_morphTarget + 2 ] = n1.z;
  11412. nka[ offset_morphTarget + 3 ] = n2.x;
  11413. nka[ offset_morphTarget + 4 ] = n2.y;
  11414. nka[ offset_morphTarget + 5 ] = n2.z;
  11415. nka[ offset_morphTarget + 6 ] = n3.x;
  11416. nka[ offset_morphTarget + 7 ] = n3.y;
  11417. nka[ offset_morphTarget + 8 ] = n3.z;
  11418. nka[ offset_morphTarget + 9 ] = n4.x;
  11419. nka[ offset_morphTarget + 10 ] = n4.y;
  11420. nka[ offset_morphTarget + 11 ] = n4.z;
  11421. }
  11422. //
  11423. offset_morphTarget += 12;
  11424. }
  11425. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  11426. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  11427. if ( material.morphNormals ) {
  11428. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  11429. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  11430. }
  11431. }
  11432. }
  11433. if ( obj_skinWeights.length ) {
  11434. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11435. face = obj_faces[ chunk_faces3[ f ] ];
  11436. // weights
  11437. sw1 = obj_skinWeights[ face.a ];
  11438. sw2 = obj_skinWeights[ face.b ];
  11439. sw3 = obj_skinWeights[ face.c ];
  11440. skinWeightArray[ offset_skin ] = sw1.x;
  11441. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11442. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11443. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11444. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11445. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11446. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11447. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11448. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11449. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11450. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11451. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11452. // indices
  11453. si1 = obj_skinIndices[ face.a ];
  11454. si2 = obj_skinIndices[ face.b ];
  11455. si3 = obj_skinIndices[ face.c ];
  11456. skinIndexArray[ offset_skin ] = si1.x;
  11457. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11458. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11459. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11460. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11461. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11462. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11463. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11464. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11465. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11466. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11467. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11468. offset_skin += 12;
  11469. }
  11470. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11471. face = obj_faces[ chunk_faces4[ f ] ];
  11472. // weights
  11473. sw1 = obj_skinWeights[ face.a ];
  11474. sw2 = obj_skinWeights[ face.b ];
  11475. sw3 = obj_skinWeights[ face.c ];
  11476. sw4 = obj_skinWeights[ face.d ];
  11477. skinWeightArray[ offset_skin ] = sw1.x;
  11478. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11479. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11480. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11481. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11482. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11483. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11484. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11485. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11486. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11487. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11488. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11489. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  11490. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  11491. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  11492. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  11493. // indices
  11494. si1 = obj_skinIndices[ face.a ];
  11495. si2 = obj_skinIndices[ face.b ];
  11496. si3 = obj_skinIndices[ face.c ];
  11497. si4 = obj_skinIndices[ face.d ];
  11498. skinIndexArray[ offset_skin ] = si1.x;
  11499. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11500. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11501. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11502. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11503. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11504. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11505. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11506. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11507. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11508. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11509. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11510. skinIndexArray[ offset_skin + 12 ] = si4.x;
  11511. skinIndexArray[ offset_skin + 13 ] = si4.y;
  11512. skinIndexArray[ offset_skin + 14 ] = si4.z;
  11513. skinIndexArray[ offset_skin + 15 ] = si4.w;
  11514. offset_skin += 16;
  11515. }
  11516. if ( offset_skin > 0 ) {
  11517. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11518. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  11519. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11520. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  11521. }
  11522. }
  11523. if ( dirtyColors && vertexColorType ) {
  11524. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11525. face = obj_faces[ chunk_faces3[ f ] ];
  11526. vertexColors = face.vertexColors;
  11527. faceColor = face.color;
  11528. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  11529. c1 = vertexColors[ 0 ];
  11530. c2 = vertexColors[ 1 ];
  11531. c3 = vertexColors[ 2 ];
  11532. } else {
  11533. c1 = faceColor;
  11534. c2 = faceColor;
  11535. c3 = faceColor;
  11536. }
  11537. colorArray[ offset_color ] = c1.r;
  11538. colorArray[ offset_color + 1 ] = c1.g;
  11539. colorArray[ offset_color + 2 ] = c1.b;
  11540. colorArray[ offset_color + 3 ] = c2.r;
  11541. colorArray[ offset_color + 4 ] = c2.g;
  11542. colorArray[ offset_color + 5 ] = c2.b;
  11543. colorArray[ offset_color + 6 ] = c3.r;
  11544. colorArray[ offset_color + 7 ] = c3.g;
  11545. colorArray[ offset_color + 8 ] = c3.b;
  11546. offset_color += 9;
  11547. }
  11548. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11549. face = obj_faces[ chunk_faces4[ f ] ];
  11550. vertexColors = face.vertexColors;
  11551. faceColor = face.color;
  11552. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  11553. c1 = vertexColors[ 0 ];
  11554. c2 = vertexColors[ 1 ];
  11555. c3 = vertexColors[ 2 ];
  11556. c4 = vertexColors[ 3 ];
  11557. } else {
  11558. c1 = faceColor;
  11559. c2 = faceColor;
  11560. c3 = faceColor;
  11561. c4 = faceColor;
  11562. }
  11563. colorArray[ offset_color ] = c1.r;
  11564. colorArray[ offset_color + 1 ] = c1.g;
  11565. colorArray[ offset_color + 2 ] = c1.b;
  11566. colorArray[ offset_color + 3 ] = c2.r;
  11567. colorArray[ offset_color + 4 ] = c2.g;
  11568. colorArray[ offset_color + 5 ] = c2.b;
  11569. colorArray[ offset_color + 6 ] = c3.r;
  11570. colorArray[ offset_color + 7 ] = c3.g;
  11571. colorArray[ offset_color + 8 ] = c3.b;
  11572. colorArray[ offset_color + 9 ] = c4.r;
  11573. colorArray[ offset_color + 10 ] = c4.g;
  11574. colorArray[ offset_color + 11 ] = c4.b;
  11575. offset_color += 12;
  11576. }
  11577. if ( offset_color > 0 ) {
  11578. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11579. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11580. }
  11581. }
  11582. if ( dirtyTangents && geometry.hasTangents ) {
  11583. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11584. face = obj_faces[ chunk_faces3[ f ] ];
  11585. vertexTangents = face.vertexTangents;
  11586. t1 = vertexTangents[ 0 ];
  11587. t2 = vertexTangents[ 1 ];
  11588. t3 = vertexTangents[ 2 ];
  11589. tangentArray[ offset_tangent ] = t1.x;
  11590. tangentArray[ offset_tangent + 1 ] = t1.y;
  11591. tangentArray[ offset_tangent + 2 ] = t1.z;
  11592. tangentArray[ offset_tangent + 3 ] = t1.w;
  11593. tangentArray[ offset_tangent + 4 ] = t2.x;
  11594. tangentArray[ offset_tangent + 5 ] = t2.y;
  11595. tangentArray[ offset_tangent + 6 ] = t2.z;
  11596. tangentArray[ offset_tangent + 7 ] = t2.w;
  11597. tangentArray[ offset_tangent + 8 ] = t3.x;
  11598. tangentArray[ offset_tangent + 9 ] = t3.y;
  11599. tangentArray[ offset_tangent + 10 ] = t3.z;
  11600. tangentArray[ offset_tangent + 11 ] = t3.w;
  11601. offset_tangent += 12;
  11602. }
  11603. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11604. face = obj_faces[ chunk_faces4[ f ] ];
  11605. vertexTangents = face.vertexTangents;
  11606. t1 = vertexTangents[ 0 ];
  11607. t2 = vertexTangents[ 1 ];
  11608. t3 = vertexTangents[ 2 ];
  11609. t4 = vertexTangents[ 3 ];
  11610. tangentArray[ offset_tangent ] = t1.x;
  11611. tangentArray[ offset_tangent + 1 ] = t1.y;
  11612. tangentArray[ offset_tangent + 2 ] = t1.z;
  11613. tangentArray[ offset_tangent + 3 ] = t1.w;
  11614. tangentArray[ offset_tangent + 4 ] = t2.x;
  11615. tangentArray[ offset_tangent + 5 ] = t2.y;
  11616. tangentArray[ offset_tangent + 6 ] = t2.z;
  11617. tangentArray[ offset_tangent + 7 ] = t2.w;
  11618. tangentArray[ offset_tangent + 8 ] = t3.x;
  11619. tangentArray[ offset_tangent + 9 ] = t3.y;
  11620. tangentArray[ offset_tangent + 10 ] = t3.z;
  11621. tangentArray[ offset_tangent + 11 ] = t3.w;
  11622. tangentArray[ offset_tangent + 12 ] = t4.x;
  11623. tangentArray[ offset_tangent + 13 ] = t4.y;
  11624. tangentArray[ offset_tangent + 14 ] = t4.z;
  11625. tangentArray[ offset_tangent + 15 ] = t4.w;
  11626. offset_tangent += 16;
  11627. }
  11628. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11629. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  11630. }
  11631. if ( dirtyNormals && normalType ) {
  11632. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11633. face = obj_faces[ chunk_faces3[ f ] ];
  11634. vertexNormals = face.vertexNormals;
  11635. faceNormal = face.normal;
  11636. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  11637. for ( i = 0; i < 3; i ++ ) {
  11638. vn = vertexNormals[ i ];
  11639. normalArray[ offset_normal ] = vn.x;
  11640. normalArray[ offset_normal + 1 ] = vn.y;
  11641. normalArray[ offset_normal + 2 ] = vn.z;
  11642. offset_normal += 3;
  11643. }
  11644. } else {
  11645. for ( i = 0; i < 3; i ++ ) {
  11646. normalArray[ offset_normal ] = faceNormal.x;
  11647. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11648. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11649. offset_normal += 3;
  11650. }
  11651. }
  11652. }
  11653. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11654. face = obj_faces[ chunk_faces4[ f ] ];
  11655. vertexNormals = face.vertexNormals;
  11656. faceNormal = face.normal;
  11657. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  11658. for ( i = 0; i < 4; i ++ ) {
  11659. vn = vertexNormals[ i ];
  11660. normalArray[ offset_normal ] = vn.x;
  11661. normalArray[ offset_normal + 1 ] = vn.y;
  11662. normalArray[ offset_normal + 2 ] = vn.z;
  11663. offset_normal += 3;
  11664. }
  11665. } else {
  11666. for ( i = 0; i < 4; i ++ ) {
  11667. normalArray[ offset_normal ] = faceNormal.x;
  11668. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11669. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11670. offset_normal += 3;
  11671. }
  11672. }
  11673. }
  11674. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11675. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11676. }
  11677. if ( dirtyUvs && obj_uvs && uvType ) {
  11678. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11679. fi = chunk_faces3[ f ];
  11680. uv = obj_uvs[ fi ];
  11681. if ( uv === undefined ) continue;
  11682. for ( i = 0; i < 3; i ++ ) {
  11683. uvi = uv[ i ];
  11684. uvArray[ offset_uv ] = uvi.x;
  11685. uvArray[ offset_uv + 1 ] = uvi.y;
  11686. offset_uv += 2;
  11687. }
  11688. }
  11689. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11690. fi = chunk_faces4[ f ];
  11691. uv = obj_uvs[ fi ];
  11692. if ( uv === undefined ) continue;
  11693. for ( i = 0; i < 4; i ++ ) {
  11694. uvi = uv[ i ];
  11695. uvArray[ offset_uv ] = uvi.x;
  11696. uvArray[ offset_uv + 1 ] = uvi.y;
  11697. offset_uv += 2;
  11698. }
  11699. }
  11700. if ( offset_uv > 0 ) {
  11701. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11702. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  11703. }
  11704. }
  11705. if ( dirtyUvs && obj_uvs2 && uvType ) {
  11706. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11707. fi = chunk_faces3[ f ];
  11708. uv2 = obj_uvs2[ fi ];
  11709. if ( uv2 === undefined ) continue;
  11710. for ( i = 0; i < 3; i ++ ) {
  11711. uv2i = uv2[ i ];
  11712. uv2Array[ offset_uv2 ] = uv2i.x;
  11713. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11714. offset_uv2 += 2;
  11715. }
  11716. }
  11717. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11718. fi = chunk_faces4[ f ];
  11719. uv2 = obj_uvs2[ fi ];
  11720. if ( uv2 === undefined ) continue;
  11721. for ( i = 0; i < 4; i ++ ) {
  11722. uv2i = uv2[ i ];
  11723. uv2Array[ offset_uv2 ] = uv2i.x;
  11724. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11725. offset_uv2 += 2;
  11726. }
  11727. }
  11728. if ( offset_uv2 > 0 ) {
  11729. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11730. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  11731. }
  11732. }
  11733. if ( dirtyElements ) {
  11734. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11735. faceArray[ offset_face ] = vertexIndex;
  11736. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11737. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  11738. offset_face += 3;
  11739. lineArray[ offset_line ] = vertexIndex;
  11740. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11741. lineArray[ offset_line + 2 ] = vertexIndex;
  11742. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  11743. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11744. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11745. offset_line += 6;
  11746. vertexIndex += 3;
  11747. }
  11748. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11749. faceArray[ offset_face ] = vertexIndex;
  11750. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11751. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  11752. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  11753. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  11754. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  11755. offset_face += 6;
  11756. lineArray[ offset_line ] = vertexIndex;
  11757. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11758. lineArray[ offset_line + 2 ] = vertexIndex;
  11759. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  11760. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11761. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11762. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  11763. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  11764. offset_line += 8;
  11765. vertexIndex += 4;
  11766. }
  11767. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11768. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  11769. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11770. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  11771. }
  11772. if ( customAttributes ) {
  11773. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11774. customAttribute = customAttributes[ i ];
  11775. if ( ! customAttribute.__original.needsUpdate ) continue;
  11776. offset_custom = 0;
  11777. offset_customSrc = 0;
  11778. if ( customAttribute.size === 1 ) {
  11779. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11780. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11781. face = obj_faces[ chunk_faces3[ f ] ];
  11782. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11783. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11784. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11785. offset_custom += 3;
  11786. }
  11787. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11788. face = obj_faces[ chunk_faces4[ f ] ];
  11789. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11790. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11791. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11792. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  11793. offset_custom += 4;
  11794. }
  11795. } else if ( customAttribute.boundTo === "faces" ) {
  11796. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11797. value = customAttribute.value[ chunk_faces3[ f ] ];
  11798. customAttribute.array[ offset_custom ] = value;
  11799. customAttribute.array[ offset_custom + 1 ] = value;
  11800. customAttribute.array[ offset_custom + 2 ] = value;
  11801. offset_custom += 3;
  11802. }
  11803. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11804. value = customAttribute.value[ chunk_faces4[ f ] ];
  11805. customAttribute.array[ offset_custom ] = value;
  11806. customAttribute.array[ offset_custom + 1 ] = value;
  11807. customAttribute.array[ offset_custom + 2 ] = value;
  11808. customAttribute.array[ offset_custom + 3 ] = value;
  11809. offset_custom += 4;
  11810. }
  11811. }
  11812. } else if ( customAttribute.size === 2 ) {
  11813. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11814. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11815. face = obj_faces[ chunk_faces3[ f ] ];
  11816. v1 = customAttribute.value[ face.a ];
  11817. v2 = customAttribute.value[ face.b ];
  11818. v3 = customAttribute.value[ face.c ];
  11819. customAttribute.array[ offset_custom ] = v1.x;
  11820. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11821. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11822. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11823. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11824. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11825. offset_custom += 6;
  11826. }
  11827. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11828. face = obj_faces[ chunk_faces4[ f ] ];
  11829. v1 = customAttribute.value[ face.a ];
  11830. v2 = customAttribute.value[ face.b ];
  11831. v3 = customAttribute.value[ face.c ];
  11832. v4 = customAttribute.value[ face.d ];
  11833. customAttribute.array[ offset_custom ] = v1.x;
  11834. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11835. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11836. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11837. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11838. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11839. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11840. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11841. offset_custom += 8;
  11842. }
  11843. } else if ( customAttribute.boundTo === "faces" ) {
  11844. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11845. value = customAttribute.value[ chunk_faces3[ f ] ];
  11846. v1 = value;
  11847. v2 = value;
  11848. v3 = value;
  11849. customAttribute.array[ offset_custom ] = v1.x;
  11850. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11851. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11852. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11853. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11854. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11855. offset_custom += 6;
  11856. }
  11857. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11858. value = customAttribute.value[ chunk_faces4[ f ] ];
  11859. v1 = value;
  11860. v2 = value;
  11861. v3 = value;
  11862. v4 = value;
  11863. customAttribute.array[ offset_custom ] = v1.x;
  11864. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11865. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11866. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11867. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11868. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11869. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11870. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11871. offset_custom += 8;
  11872. }
  11873. }
  11874. } else if ( customAttribute.size === 3 ) {
  11875. var pp;
  11876. if ( customAttribute.type === "c" ) {
  11877. pp = [ "r", "g", "b" ];
  11878. } else {
  11879. pp = [ "x", "y", "z" ];
  11880. }
  11881. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11882. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11883. face = obj_faces[ chunk_faces3[ f ] ];
  11884. v1 = customAttribute.value[ face.a ];
  11885. v2 = customAttribute.value[ face.b ];
  11886. v3 = customAttribute.value[ face.c ];
  11887. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11888. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11889. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11890. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11891. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11892. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11893. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11894. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11895. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11896. offset_custom += 9;
  11897. }
  11898. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11899. face = obj_faces[ chunk_faces4[ f ] ];
  11900. v1 = customAttribute.value[ face.a ];
  11901. v2 = customAttribute.value[ face.b ];
  11902. v3 = customAttribute.value[ face.c ];
  11903. v4 = customAttribute.value[ face.d ];
  11904. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11905. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11906. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11907. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11908. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11909. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11910. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11911. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11912. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11913. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11914. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11915. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11916. offset_custom += 12;
  11917. }
  11918. } else if ( customAttribute.boundTo === "faces" ) {
  11919. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11920. value = customAttribute.value[ chunk_faces3[ f ] ];
  11921. v1 = value;
  11922. v2 = value;
  11923. v3 = value;
  11924. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11925. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11926. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11927. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11928. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11929. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11930. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11931. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11932. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11933. offset_custom += 9;
  11934. }
  11935. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11936. value = customAttribute.value[ chunk_faces4[ f ] ];
  11937. v1 = value;
  11938. v2 = value;
  11939. v3 = value;
  11940. v4 = value;
  11941. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11942. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11943. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11944. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11945. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11946. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11947. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11948. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11949. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11950. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11951. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11952. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11953. offset_custom += 12;
  11954. }
  11955. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11956. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11957. value = customAttribute.value[ chunk_faces3[ f ] ];
  11958. v1 = value[ 0 ];
  11959. v2 = value[ 1 ];
  11960. v3 = value[ 2 ];
  11961. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11962. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11963. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11964. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11965. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11966. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11967. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11968. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11969. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11970. offset_custom += 9;
  11971. }
  11972. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11973. value = customAttribute.value[ chunk_faces4[ f ] ];
  11974. v1 = value[ 0 ];
  11975. v2 = value[ 1 ];
  11976. v3 = value[ 2 ];
  11977. v4 = value[ 3 ];
  11978. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11979. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11980. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11981. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11982. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11983. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11984. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11985. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11986. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11987. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11988. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11989. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11990. offset_custom += 12;
  11991. }
  11992. }
  11993. } else if ( customAttribute.size === 4 ) {
  11994. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11995. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11996. face = obj_faces[ chunk_faces3[ f ] ];
  11997. v1 = customAttribute.value[ face.a ];
  11998. v2 = customAttribute.value[ face.b ];
  11999. v3 = customAttribute.value[ face.c ];
  12000. customAttribute.array[ offset_custom ] = v1.x;
  12001. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12002. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12003. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12004. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12005. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12006. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12007. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12008. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12009. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12010. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12011. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12012. offset_custom += 12;
  12013. }
  12014. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12015. face = obj_faces[ chunk_faces4[ f ] ];
  12016. v1 = customAttribute.value[ face.a ];
  12017. v2 = customAttribute.value[ face.b ];
  12018. v3 = customAttribute.value[ face.c ];
  12019. v4 = customAttribute.value[ face.d ];
  12020. customAttribute.array[ offset_custom ] = v1.x;
  12021. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12022. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12023. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12024. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12025. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12026. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12027. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12028. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12029. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12030. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12031. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12032. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12033. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12034. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12035. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12036. offset_custom += 16;
  12037. }
  12038. } else if ( customAttribute.boundTo === "faces" ) {
  12039. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12040. value = customAttribute.value[ chunk_faces3[ f ] ];
  12041. v1 = value;
  12042. v2 = value;
  12043. v3 = value;
  12044. customAttribute.array[ offset_custom ] = v1.x;
  12045. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12046. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12047. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12048. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12049. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12050. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12051. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12052. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12053. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12054. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12055. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12056. offset_custom += 12;
  12057. }
  12058. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12059. value = customAttribute.value[ chunk_faces4[ f ] ];
  12060. v1 = value;
  12061. v2 = value;
  12062. v3 = value;
  12063. v4 = value;
  12064. customAttribute.array[ offset_custom ] = v1.x;
  12065. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12066. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12067. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12068. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12069. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12070. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12071. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12072. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12073. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12074. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12075. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12076. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12077. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12078. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12079. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12080. offset_custom += 16;
  12081. }
  12082. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12083. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12084. value = customAttribute.value[ chunk_faces3[ f ] ];
  12085. v1 = value[ 0 ];
  12086. v2 = value[ 1 ];
  12087. v3 = value[ 2 ];
  12088. customAttribute.array[ offset_custom ] = v1.x;
  12089. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12090. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12091. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12092. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12093. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12094. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12095. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12096. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12097. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12098. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12099. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12100. offset_custom += 12;
  12101. }
  12102. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12103. value = customAttribute.value[ chunk_faces4[ f ] ];
  12104. v1 = value[ 0 ];
  12105. v2 = value[ 1 ];
  12106. v3 = value[ 2 ];
  12107. v4 = value[ 3 ];
  12108. customAttribute.array[ offset_custom ] = v1.x;
  12109. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12110. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12111. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12112. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12113. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12114. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12115. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12116. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12117. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12118. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12119. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12120. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12121. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12122. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12123. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12124. offset_custom += 16;
  12125. }
  12126. }
  12127. }
  12128. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12129. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12130. }
  12131. }
  12132. if ( dispose ) {
  12133. delete geometryGroup.__inittedArrays;
  12134. delete geometryGroup.__colorArray;
  12135. delete geometryGroup.__normalArray;
  12136. delete geometryGroup.__tangentArray;
  12137. delete geometryGroup.__uvArray;
  12138. delete geometryGroup.__uv2Array;
  12139. delete geometryGroup.__faceArray;
  12140. delete geometryGroup.__vertexArray;
  12141. delete geometryGroup.__lineArray;
  12142. delete geometryGroup.__skinIndexArray;
  12143. delete geometryGroup.__skinWeightArray;
  12144. }
  12145. };
  12146. function setDirectBuffers ( geometry, hint, dispose ) {
  12147. var attributes = geometry.attributes;
  12148. var index = attributes[ "index" ];
  12149. var position = attributes[ "position" ];
  12150. var normal = attributes[ "normal" ];
  12151. var uv = attributes[ "uv" ];
  12152. var color = attributes[ "color" ];
  12153. var tangent = attributes[ "tangent" ];
  12154. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  12155. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12156. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  12157. }
  12158. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  12159. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12160. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  12161. }
  12162. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  12163. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12164. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  12165. }
  12166. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  12167. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12168. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  12169. }
  12170. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  12171. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12172. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  12173. }
  12174. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  12175. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12176. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  12177. }
  12178. if ( dispose ) {
  12179. for ( var i in geometry.attributes ) {
  12180. delete geometry.attributes[ i ].array;
  12181. }
  12182. }
  12183. };
  12184. // Buffer rendering
  12185. this.renderBufferImmediate = function ( object, program, material ) {
  12186. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12187. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12188. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12189. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12190. if ( object.hasPositions ) {
  12191. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12192. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12193. _gl.enableVertexAttribArray( program.attributes.position );
  12194. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12195. }
  12196. if ( object.hasNormals ) {
  12197. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12198. if ( material.shading === THREE.FlatShading ) {
  12199. var nx, ny, nz,
  12200. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12201. normalArray,
  12202. i, il = object.count * 3;
  12203. for( i = 0; i < il; i += 9 ) {
  12204. normalArray = object.normalArray;
  12205. nax = normalArray[ i ];
  12206. nay = normalArray[ i + 1 ];
  12207. naz = normalArray[ i + 2 ];
  12208. nbx = normalArray[ i + 3 ];
  12209. nby = normalArray[ i + 4 ];
  12210. nbz = normalArray[ i + 5 ];
  12211. ncx = normalArray[ i + 6 ];
  12212. ncy = normalArray[ i + 7 ];
  12213. ncz = normalArray[ i + 8 ];
  12214. nx = ( nax + nbx + ncx ) / 3;
  12215. ny = ( nay + nby + ncy ) / 3;
  12216. nz = ( naz + nbz + ncz ) / 3;
  12217. normalArray[ i ] = nx;
  12218. normalArray[ i + 1 ] = ny;
  12219. normalArray[ i + 2 ] = nz;
  12220. normalArray[ i + 3 ] = nx;
  12221. normalArray[ i + 4 ] = ny;
  12222. normalArray[ i + 5 ] = nz;
  12223. normalArray[ i + 6 ] = nx;
  12224. normalArray[ i + 7 ] = ny;
  12225. normalArray[ i + 8 ] = nz;
  12226. }
  12227. }
  12228. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12229. _gl.enableVertexAttribArray( program.attributes.normal );
  12230. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12231. }
  12232. if ( object.hasUvs && material.map ) {
  12233. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  12234. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12235. _gl.enableVertexAttribArray( program.attributes.uv );
  12236. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12237. }
  12238. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  12239. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  12240. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12241. _gl.enableVertexAttribArray( program.attributes.color );
  12242. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12243. }
  12244. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12245. object.count = 0;
  12246. };
  12247. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  12248. if ( material.visible === false ) return;
  12249. var program, attributes, linewidth, primitives, a, attribute;
  12250. program = setProgram( camera, lights, fog, material, object );
  12251. attributes = program.attributes;
  12252. var updateBuffers = false,
  12253. wireframeBit = material.wireframe ? 1 : 0,
  12254. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12255. if ( geometryHash !== _currentGeometryGroupHash ) {
  12256. _currentGeometryGroupHash = geometryHash;
  12257. updateBuffers = true;
  12258. }
  12259. if ( updateBuffers ) {
  12260. disableAttributes();
  12261. }
  12262. // render mesh
  12263. if ( object instanceof THREE.Mesh ) {
  12264. var index = geometry.attributes[ "index" ];
  12265. // indexed triangles
  12266. if ( index ) {
  12267. var offsets = geometry.offsets;
  12268. // if there is more than 1 chunk
  12269. // must set attribute pointers to use new offsets for each chunk
  12270. // even if geometry and materials didn't change
  12271. if ( offsets.length > 1 ) updateBuffers = true;
  12272. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12273. var startIndex = offsets[ i ].index;
  12274. if ( updateBuffers ) {
  12275. // vertices
  12276. var position = geometry.attributes[ "position" ];
  12277. var positionSize = position.itemSize;
  12278. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12279. enableAttribute( attributes.position );
  12280. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  12281. // normals
  12282. var normal = geometry.attributes[ "normal" ];
  12283. if ( attributes.normal >= 0 && normal ) {
  12284. var normalSize = normal.itemSize;
  12285. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12286. enableAttribute( attributes.normal );
  12287. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  12288. }
  12289. // uvs
  12290. var uv = geometry.attributes[ "uv" ];
  12291. if ( attributes.uv >= 0 && uv ) {
  12292. var uvSize = uv.itemSize;
  12293. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12294. enableAttribute( attributes.uv );
  12295. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  12296. }
  12297. // colors
  12298. var color = geometry.attributes[ "color" ];
  12299. if ( attributes.color >= 0 && color ) {
  12300. var colorSize = color.itemSize;
  12301. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12302. enableAttribute( attributes.color );
  12303. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  12304. }
  12305. // tangents
  12306. var tangent = geometry.attributes[ "tangent" ];
  12307. if ( attributes.tangent >= 0 && tangent ) {
  12308. var tangentSize = tangent.itemSize;
  12309. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12310. enableAttribute( attributes.tangent );
  12311. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  12312. }
  12313. // indices
  12314. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12315. }
  12316. // render indexed triangles
  12317. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  12318. _this.info.render.calls ++;
  12319. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12320. _this.info.render.faces += offsets[ i ].count / 3;
  12321. }
  12322. // non-indexed triangles
  12323. } else {
  12324. if ( updateBuffers ) {
  12325. // vertices
  12326. var position = geometry.attributes[ "position" ];
  12327. var positionSize = position.itemSize;
  12328. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12329. enableAttribute( attributes.position );
  12330. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12331. // normals
  12332. var normal = geometry.attributes[ "normal" ];
  12333. if ( attributes.normal >= 0 && normal ) {
  12334. var normalSize = normal.itemSize;
  12335. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12336. enableAttribute( attributes.normal );
  12337. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, 0 );
  12338. }
  12339. // uvs
  12340. var uv = geometry.attributes[ "uv" ];
  12341. if ( attributes.uv >= 0 && uv ) {
  12342. var uvSize = uv.itemSize;
  12343. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12344. enableAttribute( attributes.uv );
  12345. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, 0 );
  12346. }
  12347. // colors
  12348. var color = geometry.attributes[ "color" ];
  12349. if ( attributes.color >= 0 && color ) {
  12350. var colorSize = color.itemSize;
  12351. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12352. enableAttribute( attributes.color );
  12353. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12354. }
  12355. // tangents
  12356. var tangent = geometry.attributes[ "tangent" ];
  12357. if ( attributes.tangent >= 0 && tangent ) {
  12358. var tangentSize = tangent.itemSize;
  12359. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12360. enableAttribute( attributes.tangent );
  12361. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0 );
  12362. }
  12363. }
  12364. // render non-indexed triangles
  12365. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  12366. _this.info.render.calls ++;
  12367. _this.info.render.vertices += position.numItems / 3;
  12368. _this.info.render.faces += position.numItems / 3 / 3;
  12369. }
  12370. // render particles
  12371. } else if ( object instanceof THREE.ParticleSystem ) {
  12372. if ( updateBuffers ) {
  12373. // vertices
  12374. var position = geometry.attributes[ "position" ];
  12375. var positionSize = position.itemSize;
  12376. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12377. enableAttribute( attributes.position );
  12378. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12379. // colors
  12380. var color = geometry.attributes[ "color" ];
  12381. if ( attributes.color >= 0 && color ) {
  12382. var colorSize = color.itemSize;
  12383. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12384. enableAttribute( attributes.color );
  12385. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12386. }
  12387. // render particles
  12388. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  12389. _this.info.render.calls ++;
  12390. _this.info.render.points += position.numItems / 3;
  12391. }
  12392. }
  12393. };
  12394. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  12395. if ( material.visible === false ) return;
  12396. var program, attributes, linewidth, primitives, a, attribute, i, il;
  12397. program = setProgram( camera, lights, fog, material, object );
  12398. attributes = program.attributes;
  12399. var updateBuffers = false,
  12400. wireframeBit = material.wireframe ? 1 : 0,
  12401. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12402. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  12403. _currentGeometryGroupHash = geometryGroupHash;
  12404. updateBuffers = true;
  12405. }
  12406. if ( updateBuffers ) {
  12407. disableAttributes();
  12408. }
  12409. // vertices
  12410. if ( !material.morphTargets && attributes.position >= 0 ) {
  12411. if ( updateBuffers ) {
  12412. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12413. enableAttribute( attributes.position );
  12414. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12415. }
  12416. } else {
  12417. if ( object.morphTargetBase ) {
  12418. setupMorphTargets( material, geometryGroup, object );
  12419. }
  12420. }
  12421. if ( updateBuffers ) {
  12422. // custom attributes
  12423. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  12424. if ( geometryGroup.__webglCustomAttributesList ) {
  12425. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  12426. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  12427. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  12428. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  12429. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  12430. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  12431. }
  12432. }
  12433. }
  12434. // colors
  12435. if ( attributes.color >= 0 ) {
  12436. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12437. enableAttribute( attributes.color );
  12438. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12439. }
  12440. // normals
  12441. if ( attributes.normal >= 0 ) {
  12442. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12443. enableAttribute( attributes.normal );
  12444. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12445. }
  12446. // tangents
  12447. if ( attributes.tangent >= 0 ) {
  12448. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12449. enableAttribute( attributes.tangent );
  12450. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  12451. }
  12452. // uvs
  12453. if ( attributes.uv >= 0 ) {
  12454. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12455. enableAttribute( attributes.uv );
  12456. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12457. }
  12458. if ( attributes.uv2 >= 0 ) {
  12459. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12460. enableAttribute( attributes.uv2 );
  12461. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  12462. }
  12463. if ( material.skinning &&
  12464. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12465. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12466. enableAttribute( attributes.skinIndex );
  12467. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  12468. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12469. enableAttribute( attributes.skinWeight );
  12470. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  12471. }
  12472. // line distances
  12473. if ( attributes.lineDistance >= 0 ) {
  12474. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  12475. enableAttribute( attributes.lineDistance );
  12476. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  12477. }
  12478. }
  12479. // render mesh
  12480. if ( object instanceof THREE.Mesh ) {
  12481. // wireframe
  12482. if ( material.wireframe ) {
  12483. setLineWidth( material.wireframeLinewidth );
  12484. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12485. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  12486. // triangles
  12487. } else {
  12488. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12489. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  12490. }
  12491. _this.info.render.calls ++;
  12492. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  12493. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  12494. // render lines
  12495. } else if ( object instanceof THREE.Line ) {
  12496. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12497. setLineWidth( material.linewidth );
  12498. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  12499. _this.info.render.calls ++;
  12500. // render particles
  12501. } else if ( object instanceof THREE.ParticleSystem ) {
  12502. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  12503. _this.info.render.calls ++;
  12504. _this.info.render.points += geometryGroup.__webglParticleCount;
  12505. // render ribbon
  12506. } else if ( object instanceof THREE.Ribbon ) {
  12507. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  12508. _this.info.render.calls ++;
  12509. }
  12510. };
  12511. function enableAttribute( attribute ) {
  12512. if ( ! _enabledAttributes[ attribute ] ) {
  12513. _gl.enableVertexAttribArray( attribute );
  12514. _enabledAttributes[ attribute ] = true;
  12515. }
  12516. };
  12517. function disableAttributes() {
  12518. for ( var attribute in _enabledAttributes ) {
  12519. if ( _enabledAttributes[ attribute ] ) {
  12520. _gl.disableVertexAttribArray( attribute );
  12521. _enabledAttributes[ attribute ] = false;
  12522. }
  12523. }
  12524. };
  12525. function setupMorphTargets ( material, geometryGroup, object ) {
  12526. // set base
  12527. var attributes = material.program.attributes;
  12528. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  12529. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  12530. enableAttribute( attributes.position );
  12531. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12532. } else if ( attributes.position >= 0 ) {
  12533. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12534. enableAttribute( attributes.position );
  12535. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12536. }
  12537. if ( object.morphTargetForcedOrder.length ) {
  12538. // set forced order
  12539. var m = 0;
  12540. var order = object.morphTargetForcedOrder;
  12541. var influences = object.morphTargetInfluences;
  12542. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  12543. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12544. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  12545. enableAttribute( attributes[ "morphTarget" + m ] );
  12546. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12547. }
  12548. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12549. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  12550. enableAttribute( attributes[ "morphNormal" + m ] );
  12551. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12552. }
  12553. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  12554. m ++;
  12555. }
  12556. } else {
  12557. // find the most influencing
  12558. var influence, activeInfluenceIndices = [];
  12559. var influences = object.morphTargetInfluences;
  12560. var i, il = influences.length;
  12561. for ( i = 0; i < il; i ++ ) {
  12562. influence = influences[ i ];
  12563. if ( influence > 0 ) {
  12564. activeInfluenceIndices.push( [ influence, i ] );
  12565. }
  12566. }
  12567. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  12568. activeInfluenceIndices.sort( numericalSort );
  12569. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  12570. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  12571. activeInfluenceIndices.sort( numericalSort );
  12572. } else if ( activeInfluenceIndices.length === 0 ) {
  12573. activeInfluenceIndices.push( [ 0, 0 ] );
  12574. };
  12575. var influenceIndex, m = 0;
  12576. while ( m < material.numSupportedMorphTargets ) {
  12577. if ( activeInfluenceIndices[ m ] ) {
  12578. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  12579. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12580. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  12581. enableAttribute( attributes[ "morphTarget" + m ] );
  12582. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12583. }
  12584. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12585. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  12586. enableAttribute( attributes[ "morphNormal" + m ] );
  12587. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12588. }
  12589. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  12590. } else {
  12591. /*
  12592. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12593. if ( material.morphNormals ) {
  12594. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12595. }
  12596. */
  12597. object.__webglMorphTargetInfluences[ m ] = 0;
  12598. }
  12599. m ++;
  12600. }
  12601. }
  12602. // load updated influences uniform
  12603. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  12604. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  12605. }
  12606. };
  12607. // Sorting
  12608. function painterSortStable ( a, b ) {
  12609. if ( a.z !== b.z ) {
  12610. return b.z - a.z;
  12611. } else {
  12612. return b.id - a.id;
  12613. }
  12614. };
  12615. function numericalSort ( a, b ) {
  12616. return b[ 0 ] - a[ 0 ];
  12617. };
  12618. // Rendering
  12619. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12620. if ( camera instanceof THREE.Camera === false ) {
  12621. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12622. return;
  12623. }
  12624. var i, il,
  12625. webglObject, object,
  12626. renderList,
  12627. lights = scene.__lights,
  12628. fog = scene.fog;
  12629. // reset caching for this frame
  12630. _currentMaterialId = -1;
  12631. _lightsNeedUpdate = true;
  12632. // update scene graph
  12633. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  12634. // update camera matrices and frustum
  12635. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  12636. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12637. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  12638. _frustum.setFromMatrix( _projScreenMatrix );
  12639. // update WebGL objects
  12640. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  12641. // custom render plugins (pre pass)
  12642. renderPlugins( this.renderPluginsPre, scene, camera );
  12643. //
  12644. _this.info.render.calls = 0;
  12645. _this.info.render.vertices = 0;
  12646. _this.info.render.faces = 0;
  12647. _this.info.render.points = 0;
  12648. this.setRenderTarget( renderTarget );
  12649. if ( this.autoClear || forceClear ) {
  12650. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12651. }
  12652. // set matrices for regular objects (frustum culled)
  12653. renderList = scene.__webglObjects;
  12654. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12655. webglObject = renderList[ i ];
  12656. object = webglObject.object;
  12657. webglObject.render = false;
  12658. if ( object.visible ) {
  12659. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  12660. setupMatrices( object, camera );
  12661. unrollBufferMaterial( webglObject );
  12662. webglObject.render = true;
  12663. if ( this.sortObjects === true ) {
  12664. if ( object.renderDepth !== null ) {
  12665. webglObject.z = object.renderDepth;
  12666. } else {
  12667. _vector3.copy( object.matrixWorld.getPosition() );
  12668. _projScreenMatrix.multiplyVector3( _vector3 );
  12669. webglObject.z = _vector3.z;
  12670. }
  12671. webglObject.id = object.id;
  12672. }
  12673. }
  12674. }
  12675. }
  12676. if ( this.sortObjects ) {
  12677. renderList.sort( painterSortStable );
  12678. }
  12679. // set matrices for immediate objects
  12680. renderList = scene.__webglObjectsImmediate;
  12681. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12682. webglObject = renderList[ i ];
  12683. object = webglObject.object;
  12684. if ( object.visible ) {
  12685. setupMatrices( object, camera );
  12686. unrollImmediateBufferMaterial( webglObject );
  12687. }
  12688. }
  12689. if ( scene.overrideMaterial ) {
  12690. var material = scene.overrideMaterial;
  12691. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12692. this.setDepthTest( material.depthTest );
  12693. this.setDepthWrite( material.depthWrite );
  12694. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12695. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  12696. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  12697. } else {
  12698. var material = null;
  12699. // opaque pass (front-to-back order)
  12700. this.setBlending( THREE.NoBlending );
  12701. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  12702. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  12703. // transparent pass (back-to-front order)
  12704. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  12705. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  12706. }
  12707. // custom render plugins (post pass)
  12708. renderPlugins( this.renderPluginsPost, scene, camera );
  12709. // Generate mipmap if we're using any kind of mipmap filtering
  12710. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  12711. updateRenderTargetMipmap( renderTarget );
  12712. }
  12713. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12714. this.setDepthTest( true );
  12715. this.setDepthWrite( true );
  12716. // _gl.finish();
  12717. };
  12718. function renderPlugins( plugins, scene, camera ) {
  12719. if ( ! plugins.length ) return;
  12720. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  12721. // reset state for plugin (to start from clean slate)
  12722. _currentProgram = null;
  12723. _currentCamera = null;
  12724. _oldBlending = -1;
  12725. _oldDepthTest = -1;
  12726. _oldDepthWrite = -1;
  12727. _oldDoubleSided = -1;
  12728. _oldFlipSided = -1;
  12729. _currentGeometryGroupHash = -1;
  12730. _currentMaterialId = -1;
  12731. _lightsNeedUpdate = true;
  12732. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  12733. // reset state after plugin (anything could have changed)
  12734. _currentProgram = null;
  12735. _currentCamera = null;
  12736. _oldBlending = -1;
  12737. _oldDepthTest = -1;
  12738. _oldDepthWrite = -1;
  12739. _oldDoubleSided = -1;
  12740. _oldFlipSided = -1;
  12741. _currentGeometryGroupHash = -1;
  12742. _currentMaterialId = -1;
  12743. _lightsNeedUpdate = true;
  12744. }
  12745. };
  12746. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12747. var webglObject, object, buffer, material, start, end, delta;
  12748. if ( reverse ) {
  12749. start = renderList.length - 1;
  12750. end = -1;
  12751. delta = -1;
  12752. } else {
  12753. start = 0;
  12754. end = renderList.length;
  12755. delta = 1;
  12756. }
  12757. for ( var i = start; i !== end; i += delta ) {
  12758. webglObject = renderList[ i ];
  12759. if ( webglObject.render ) {
  12760. object = webglObject.object;
  12761. buffer = webglObject.buffer;
  12762. if ( overrideMaterial ) {
  12763. material = overrideMaterial;
  12764. } else {
  12765. material = webglObject[ materialType ];
  12766. if ( ! material ) continue;
  12767. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12768. _this.setDepthTest( material.depthTest );
  12769. _this.setDepthWrite( material.depthWrite );
  12770. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12771. }
  12772. _this.setMaterialFaces( material );
  12773. if ( buffer instanceof THREE.BufferGeometry ) {
  12774. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  12775. } else {
  12776. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  12777. }
  12778. }
  12779. }
  12780. };
  12781. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12782. var webglObject, object, material, program;
  12783. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  12784. webglObject = renderList[ i ];
  12785. object = webglObject.object;
  12786. if ( object.visible ) {
  12787. if ( overrideMaterial ) {
  12788. material = overrideMaterial;
  12789. } else {
  12790. material = webglObject[ materialType ];
  12791. if ( ! material ) continue;
  12792. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12793. _this.setDepthTest( material.depthTest );
  12794. _this.setDepthWrite( material.depthWrite );
  12795. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12796. }
  12797. _this.renderImmediateObject( camera, lights, fog, material, object );
  12798. }
  12799. }
  12800. };
  12801. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  12802. var program = setProgram( camera, lights, fog, material, object );
  12803. _currentGeometryGroupHash = -1;
  12804. _this.setMaterialFaces( material );
  12805. if ( object.immediateRenderCallback ) {
  12806. object.immediateRenderCallback( program, _gl, _frustum );
  12807. } else {
  12808. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  12809. }
  12810. };
  12811. function unrollImmediateBufferMaterial ( globject ) {
  12812. var object = globject.object,
  12813. material = object.material;
  12814. if ( material.transparent ) {
  12815. globject.transparent = material;
  12816. globject.opaque = null;
  12817. } else {
  12818. globject.opaque = material;
  12819. globject.transparent = null;
  12820. }
  12821. };
  12822. function unrollBufferMaterial ( globject ) {
  12823. var object = globject.object,
  12824. buffer = globject.buffer,
  12825. material, materialIndex, meshMaterial;
  12826. meshMaterial = object.material;
  12827. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  12828. materialIndex = buffer.materialIndex;
  12829. material = meshMaterial.materials[ materialIndex ];
  12830. if ( material.transparent ) {
  12831. globject.transparent = material;
  12832. globject.opaque = null;
  12833. } else {
  12834. globject.opaque = material;
  12835. globject.transparent = null;
  12836. }
  12837. } else {
  12838. material = meshMaterial;
  12839. if ( material ) {
  12840. if ( material.transparent ) {
  12841. globject.transparent = material;
  12842. globject.opaque = null;
  12843. } else {
  12844. globject.opaque = material;
  12845. globject.transparent = null;
  12846. }
  12847. }
  12848. }
  12849. };
  12850. // Geometry splitting
  12851. function sortFacesByMaterial ( geometry, material ) {
  12852. var f, fl, face, materialIndex, vertices,
  12853. groupHash, hash_map = {};
  12854. var numMorphTargets = geometry.morphTargets.length;
  12855. var numMorphNormals = geometry.morphNormals.length;
  12856. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  12857. geometry.geometryGroups = {};
  12858. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  12859. face = geometry.faces[ f ];
  12860. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  12861. if ( hash_map[ materialIndex ] === undefined ) {
  12862. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  12863. }
  12864. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12865. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12866. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12867. }
  12868. vertices = face instanceof THREE.Face3 ? 3 : 4;
  12869. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  12870. hash_map[ materialIndex ].counter += 1;
  12871. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12872. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12873. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12874. }
  12875. }
  12876. if ( face instanceof THREE.Face3 ) {
  12877. geometry.geometryGroups[ groupHash ].faces3.push( f );
  12878. } else {
  12879. geometry.geometryGroups[ groupHash ].faces4.push( f );
  12880. }
  12881. geometry.geometryGroups[ groupHash ].vertices += vertices;
  12882. }
  12883. geometry.geometryGroupsList = [];
  12884. for ( var g in geometry.geometryGroups ) {
  12885. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  12886. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  12887. }
  12888. };
  12889. // Objects refresh
  12890. this.initWebGLObjects = function ( scene ) {
  12891. if ( !scene.__webglObjects ) {
  12892. scene.__webglObjects = [];
  12893. scene.__webglObjectsImmediate = [];
  12894. scene.__webglSprites = [];
  12895. scene.__webglFlares = [];
  12896. }
  12897. while ( scene.__objectsAdded.length ) {
  12898. addObject( scene.__objectsAdded[ 0 ], scene );
  12899. scene.__objectsAdded.splice( 0, 1 );
  12900. }
  12901. while ( scene.__objectsRemoved.length ) {
  12902. removeObject( scene.__objectsRemoved[ 0 ], scene );
  12903. scene.__objectsRemoved.splice( 0, 1 );
  12904. }
  12905. // update must be called after objects adding / removal
  12906. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  12907. updateObject( scene.__webglObjects[ o ].object );
  12908. }
  12909. };
  12910. // Objects adding
  12911. function addObject ( object, scene ) {
  12912. var g, geometry, material, geometryGroup;
  12913. if ( ! object.__webglInit ) {
  12914. object.__webglInit = true;
  12915. object._modelViewMatrix = new THREE.Matrix4();
  12916. object._normalMatrix = new THREE.Matrix3();
  12917. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  12918. object.geometry.__webglInit = true;
  12919. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  12920. }
  12921. if ( object instanceof THREE.Mesh ) {
  12922. geometry = object.geometry;
  12923. material = object.material;
  12924. if ( geometry instanceof THREE.Geometry ) {
  12925. if ( geometry.geometryGroups === undefined ) {
  12926. sortFacesByMaterial( geometry, material );
  12927. }
  12928. // create separate VBOs per geometry chunk
  12929. for ( g in geometry.geometryGroups ) {
  12930. geometryGroup = geometry.geometryGroups[ g ];
  12931. // initialise VBO on the first access
  12932. if ( ! geometryGroup.__webglVertexBuffer ) {
  12933. createMeshBuffers( geometryGroup );
  12934. initMeshBuffers( geometryGroup, object );
  12935. geometry.verticesNeedUpdate = true;
  12936. geometry.morphTargetsNeedUpdate = true;
  12937. geometry.elementsNeedUpdate = true;
  12938. geometry.uvsNeedUpdate = true;
  12939. geometry.normalsNeedUpdate = true;
  12940. geometry.tangentsNeedUpdate = true;
  12941. geometry.colorsNeedUpdate = true;
  12942. }
  12943. }
  12944. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12945. initDirectBuffers( geometry );
  12946. }
  12947. } else if ( object instanceof THREE.Ribbon ) {
  12948. geometry = object.geometry;
  12949. if ( ! geometry.__webglVertexBuffer ) {
  12950. createRibbonBuffers( geometry );
  12951. initRibbonBuffers( geometry, object );
  12952. geometry.verticesNeedUpdate = true;
  12953. geometry.colorsNeedUpdate = true;
  12954. geometry.normalsNeedUpdate = true;
  12955. }
  12956. } else if ( object instanceof THREE.Line ) {
  12957. geometry = object.geometry;
  12958. if ( ! geometry.__webglVertexBuffer ) {
  12959. createLineBuffers( geometry );
  12960. initLineBuffers( geometry, object );
  12961. geometry.verticesNeedUpdate = true;
  12962. geometry.colorsNeedUpdate = true;
  12963. geometry.lineDistancesNeedUpdate = true;
  12964. }
  12965. } else if ( object instanceof THREE.ParticleSystem ) {
  12966. geometry = object.geometry;
  12967. if ( ! geometry.__webglVertexBuffer ) {
  12968. if ( geometry instanceof THREE.Geometry ) {
  12969. createParticleBuffers( geometry );
  12970. initParticleBuffers( geometry, object );
  12971. geometry.verticesNeedUpdate = true;
  12972. geometry.colorsNeedUpdate = true;
  12973. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12974. initDirectBuffers( geometry );
  12975. }
  12976. }
  12977. }
  12978. }
  12979. if ( ! object.__webglActive ) {
  12980. if ( object instanceof THREE.Mesh ) {
  12981. geometry = object.geometry;
  12982. if ( geometry instanceof THREE.BufferGeometry ) {
  12983. addBuffer( scene.__webglObjects, geometry, object );
  12984. } else {
  12985. for ( g in geometry.geometryGroups ) {
  12986. geometryGroup = geometry.geometryGroups[ g ];
  12987. addBuffer( scene.__webglObjects, geometryGroup, object );
  12988. }
  12989. }
  12990. } else if ( object instanceof THREE.Ribbon ||
  12991. object instanceof THREE.Line ||
  12992. object instanceof THREE.ParticleSystem ) {
  12993. geometry = object.geometry;
  12994. addBuffer( scene.__webglObjects, geometry, object );
  12995. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12996. addBufferImmediate( scene.__webglObjectsImmediate, object );
  12997. } else if ( object instanceof THREE.Sprite ) {
  12998. scene.__webglSprites.push( object );
  12999. } else if ( object instanceof THREE.LensFlare ) {
  13000. scene.__webglFlares.push( object );
  13001. }
  13002. object.__webglActive = true;
  13003. }
  13004. };
  13005. function addBuffer ( objlist, buffer, object ) {
  13006. objlist.push(
  13007. {
  13008. buffer: buffer,
  13009. object: object,
  13010. opaque: null,
  13011. transparent: null
  13012. }
  13013. );
  13014. };
  13015. function addBufferImmediate ( objlist, object ) {
  13016. objlist.push(
  13017. {
  13018. object: object,
  13019. opaque: null,
  13020. transparent: null
  13021. }
  13022. );
  13023. };
  13024. // Objects updates
  13025. function updateObject ( object ) {
  13026. var geometry = object.geometry,
  13027. geometryGroup, customAttributesDirty, material;
  13028. if ( object instanceof THREE.Mesh ) {
  13029. if ( geometry instanceof THREE.BufferGeometry ) {
  13030. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  13031. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13032. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  13033. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13034. }
  13035. geometry.verticesNeedUpdate = false;
  13036. geometry.elementsNeedUpdate = false;
  13037. geometry.uvsNeedUpdate = false;
  13038. geometry.normalsNeedUpdate = false;
  13039. geometry.colorsNeedUpdate = false;
  13040. geometry.tangentsNeedUpdate = false;
  13041. } else {
  13042. // check all geometry groups
  13043. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13044. geometryGroup = geometry.geometryGroupsList[ i ];
  13045. material = getBufferMaterial( object, geometryGroup );
  13046. if ( geometry.buffersNeedUpdate ) {
  13047. initMeshBuffers( geometryGroup, object );
  13048. }
  13049. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13050. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13051. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13052. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13053. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13054. }
  13055. }
  13056. geometry.verticesNeedUpdate = false;
  13057. geometry.morphTargetsNeedUpdate = false;
  13058. geometry.elementsNeedUpdate = false;
  13059. geometry.uvsNeedUpdate = false;
  13060. geometry.normalsNeedUpdate = false;
  13061. geometry.colorsNeedUpdate = false;
  13062. geometry.tangentsNeedUpdate = false;
  13063. geometry.buffersNeedUpdate = false;
  13064. material.attributes && clearCustomAttributes( material );
  13065. }
  13066. } else if ( object instanceof THREE.Ribbon ) {
  13067. material = getBufferMaterial( object, geometry );
  13068. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13069. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  13070. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  13071. }
  13072. geometry.verticesNeedUpdate = false;
  13073. geometry.colorsNeedUpdate = false;
  13074. geometry.normalsNeedUpdate = false;
  13075. material.attributes && clearCustomAttributes( material );
  13076. } else if ( object instanceof THREE.Line ) {
  13077. material = getBufferMaterial( object, geometry );
  13078. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13079. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13080. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13081. }
  13082. geometry.verticesNeedUpdate = false;
  13083. geometry.colorsNeedUpdate = false;
  13084. geometry.lineDistancesNeedUpdate = false;
  13085. material.attributes && clearCustomAttributes( material );
  13086. } else if ( object instanceof THREE.ParticleSystem ) {
  13087. if ( geometry instanceof THREE.BufferGeometry ) {
  13088. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  13089. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13090. }
  13091. geometry.verticesNeedUpdate = false;
  13092. geometry.colorsNeedUpdate = false;
  13093. } else {
  13094. material = getBufferMaterial( object, geometry );
  13095. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13096. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13097. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13098. }
  13099. geometry.verticesNeedUpdate = false;
  13100. geometry.colorsNeedUpdate = false;
  13101. material.attributes && clearCustomAttributes( material );
  13102. }
  13103. }
  13104. };
  13105. // Objects updates - custom attributes check
  13106. function areCustomAttributesDirty ( material ) {
  13107. for ( var a in material.attributes ) {
  13108. if ( material.attributes[ a ].needsUpdate ) return true;
  13109. }
  13110. return false;
  13111. };
  13112. function clearCustomAttributes ( material ) {
  13113. for ( var a in material.attributes ) {
  13114. material.attributes[ a ].needsUpdate = false;
  13115. }
  13116. };
  13117. // Objects removal
  13118. function removeObject ( object, scene ) {
  13119. if ( object instanceof THREE.Mesh ||
  13120. object instanceof THREE.ParticleSystem ||
  13121. object instanceof THREE.Ribbon ||
  13122. object instanceof THREE.Line ) {
  13123. removeInstances( scene.__webglObjects, object );
  13124. } else if ( object instanceof THREE.Sprite ) {
  13125. removeInstancesDirect( scene.__webglSprites, object );
  13126. } else if ( object instanceof THREE.LensFlare ) {
  13127. removeInstancesDirect( scene.__webglFlares, object );
  13128. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13129. removeInstances( scene.__webglObjectsImmediate, object );
  13130. }
  13131. object.__webglActive = false;
  13132. };
  13133. function removeInstances ( objlist, object ) {
  13134. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13135. if ( objlist[ o ].object === object ) {
  13136. objlist.splice( o, 1 );
  13137. }
  13138. }
  13139. };
  13140. function removeInstancesDirect ( objlist, object ) {
  13141. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13142. if ( objlist[ o ] === object ) {
  13143. objlist.splice( o, 1 );
  13144. }
  13145. }
  13146. };
  13147. // Materials
  13148. this.initMaterial = function ( material, lights, fog, object ) {
  13149. material.addEventListener( 'dispose', onMaterialDispose );
  13150. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13151. if ( material instanceof THREE.MeshDepthMaterial ) {
  13152. shaderID = 'depth';
  13153. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13154. shaderID = 'normal';
  13155. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13156. shaderID = 'basic';
  13157. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13158. shaderID = 'lambert';
  13159. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13160. shaderID = 'phong';
  13161. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13162. shaderID = 'basic';
  13163. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13164. shaderID = 'dashed';
  13165. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13166. shaderID = 'particle_basic';
  13167. }
  13168. if ( shaderID ) {
  13169. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13170. }
  13171. // heuristics to create shader parameters according to lights in the scene
  13172. // (not to blow over maxLights budget)
  13173. maxLightCount = allocateLights( lights );
  13174. maxShadows = allocateShadows( lights );
  13175. maxBones = allocateBones( object );
  13176. parameters = {
  13177. map: !!material.map,
  13178. envMap: !!material.envMap,
  13179. lightMap: !!material.lightMap,
  13180. bumpMap: !!material.bumpMap,
  13181. normalMap: !!material.normalMap,
  13182. specularMap: !!material.specularMap,
  13183. vertexColors: material.vertexColors,
  13184. fog: fog,
  13185. useFog: material.fog,
  13186. fogExp: fog instanceof THREE.FogExp2,
  13187. sizeAttenuation: material.sizeAttenuation,
  13188. skinning: material.skinning,
  13189. maxBones: maxBones,
  13190. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13191. boneTextureWidth: object && object.boneTextureWidth,
  13192. boneTextureHeight: object && object.boneTextureHeight,
  13193. morphTargets: material.morphTargets,
  13194. morphNormals: material.morphNormals,
  13195. maxMorphTargets: this.maxMorphTargets,
  13196. maxMorphNormals: this.maxMorphNormals,
  13197. maxDirLights: maxLightCount.directional,
  13198. maxPointLights: maxLightCount.point,
  13199. maxSpotLights: maxLightCount.spot,
  13200. maxHemiLights: maxLightCount.hemi,
  13201. maxShadows: maxShadows,
  13202. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13203. shadowMapType: this.shadowMapType,
  13204. shadowMapDebug: this.shadowMapDebug,
  13205. shadowMapCascade: this.shadowMapCascade,
  13206. alphaTest: material.alphaTest,
  13207. metal: material.metal,
  13208. perPixel: material.perPixel,
  13209. wrapAround: material.wrapAround,
  13210. doubleSided: material.side === THREE.DoubleSide,
  13211. flipSided: material.side === THREE.BackSide
  13212. };
  13213. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  13214. var attributes = material.program.attributes;
  13215. if ( material.morphTargets ) {
  13216. material.numSupportedMorphTargets = 0;
  13217. var id, base = "morphTarget";
  13218. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13219. id = base + i;
  13220. if ( attributes[ id ] >= 0 ) {
  13221. material.numSupportedMorphTargets ++;
  13222. }
  13223. }
  13224. }
  13225. if ( material.morphNormals ) {
  13226. material.numSupportedMorphNormals = 0;
  13227. var id, base = "morphNormal";
  13228. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13229. id = base + i;
  13230. if ( attributes[ id ] >= 0 ) {
  13231. material.numSupportedMorphNormals ++;
  13232. }
  13233. }
  13234. }
  13235. material.uniformsList = [];
  13236. for ( u in material.uniforms ) {
  13237. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13238. }
  13239. };
  13240. function setMaterialShaders( material, shaders ) {
  13241. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  13242. material.vertexShader = shaders.vertexShader;
  13243. material.fragmentShader = shaders.fragmentShader;
  13244. };
  13245. function setProgram( camera, lights, fog, material, object ) {
  13246. _usedTextureUnits = 0;
  13247. if ( material.needsUpdate ) {
  13248. if ( material.program ) deallocateMaterial( material );
  13249. _this.initMaterial( material, lights, fog, object );
  13250. material.needsUpdate = false;
  13251. }
  13252. if ( material.morphTargets ) {
  13253. if ( ! object.__webglMorphTargetInfluences ) {
  13254. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13255. }
  13256. }
  13257. var refreshMaterial = false;
  13258. var program = material.program,
  13259. p_uniforms = program.uniforms,
  13260. m_uniforms = material.uniforms;
  13261. if ( program !== _currentProgram ) {
  13262. _gl.useProgram( program );
  13263. _currentProgram = program;
  13264. refreshMaterial = true;
  13265. }
  13266. if ( material.id !== _currentMaterialId ) {
  13267. _currentMaterialId = material.id;
  13268. refreshMaterial = true;
  13269. }
  13270. if ( refreshMaterial || camera !== _currentCamera ) {
  13271. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13272. if ( camera !== _currentCamera ) _currentCamera = camera;
  13273. }
  13274. // skinning uniforms must be set even if material didn't change
  13275. // auto-setting of texture unit for bone texture must go before other textures
  13276. // not sure why, but otherwise weird things happen
  13277. if ( material.skinning ) {
  13278. if ( _supportsBoneTextures && object.useVertexTexture ) {
  13279. if ( p_uniforms.boneTexture !== null ) {
  13280. var textureUnit = getTextureUnit();
  13281. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13282. _this.setTexture( object.boneTexture, textureUnit );
  13283. }
  13284. } else {
  13285. if ( p_uniforms.boneGlobalMatrices !== null ) {
  13286. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  13287. }
  13288. }
  13289. }
  13290. if ( refreshMaterial ) {
  13291. // refresh uniforms common to several materials
  13292. if ( fog && material.fog ) {
  13293. refreshUniformsFog( m_uniforms, fog );
  13294. }
  13295. if ( material instanceof THREE.MeshPhongMaterial ||
  13296. material instanceof THREE.MeshLambertMaterial ||
  13297. material.lights ) {
  13298. if ( _lightsNeedUpdate ) {
  13299. setupLights( program, lights );
  13300. _lightsNeedUpdate = false;
  13301. }
  13302. refreshUniformsLights( m_uniforms, _lights );
  13303. }
  13304. if ( material instanceof THREE.MeshBasicMaterial ||
  13305. material instanceof THREE.MeshLambertMaterial ||
  13306. material instanceof THREE.MeshPhongMaterial ) {
  13307. refreshUniformsCommon( m_uniforms, material );
  13308. }
  13309. // refresh single material specific uniforms
  13310. if ( material instanceof THREE.LineBasicMaterial ) {
  13311. refreshUniformsLine( m_uniforms, material );
  13312. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13313. refreshUniformsLine( m_uniforms, material );
  13314. refreshUniformsDash( m_uniforms, material );
  13315. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13316. refreshUniformsParticle( m_uniforms, material );
  13317. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13318. refreshUniformsPhong( m_uniforms, material );
  13319. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13320. refreshUniformsLambert( m_uniforms, material );
  13321. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13322. m_uniforms.mNear.value = camera.near;
  13323. m_uniforms.mFar.value = camera.far;
  13324. m_uniforms.opacity.value = material.opacity;
  13325. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13326. m_uniforms.opacity.value = material.opacity;
  13327. }
  13328. if ( object.receiveShadow && ! material._shadowPass ) {
  13329. refreshUniformsShadow( m_uniforms, lights );
  13330. }
  13331. // load common uniforms
  13332. loadUniformsGeneric( program, material.uniformsList );
  13333. // load material specific uniforms
  13334. // (shader material also gets them for the sake of genericity)
  13335. if ( material instanceof THREE.ShaderMaterial ||
  13336. material instanceof THREE.MeshPhongMaterial ||
  13337. material.envMap ) {
  13338. if ( p_uniforms.cameraPosition !== null ) {
  13339. var position = camera.matrixWorld.getPosition();
  13340. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  13341. }
  13342. }
  13343. if ( material instanceof THREE.MeshPhongMaterial ||
  13344. material instanceof THREE.MeshLambertMaterial ||
  13345. material instanceof THREE.ShaderMaterial ||
  13346. material.skinning ) {
  13347. if ( p_uniforms.viewMatrix !== null ) {
  13348. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13349. }
  13350. }
  13351. }
  13352. loadUniformsMatrices( p_uniforms, object );
  13353. if ( p_uniforms.modelMatrix !== null ) {
  13354. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13355. }
  13356. return program;
  13357. };
  13358. // Uniforms (refresh uniforms objects)
  13359. function refreshUniformsCommon ( uniforms, material ) {
  13360. uniforms.opacity.value = material.opacity;
  13361. if ( _this.gammaInput ) {
  13362. uniforms.diffuse.value.copyGammaToLinear( material.color );
  13363. } else {
  13364. uniforms.diffuse.value = material.color;
  13365. }
  13366. uniforms.map.value = material.map;
  13367. uniforms.lightMap.value = material.lightMap;
  13368. uniforms.specularMap.value = material.specularMap;
  13369. if ( material.bumpMap ) {
  13370. uniforms.bumpMap.value = material.bumpMap;
  13371. uniforms.bumpScale.value = material.bumpScale;
  13372. }
  13373. if ( material.normalMap ) {
  13374. uniforms.normalMap.value = material.normalMap;
  13375. uniforms.normalScale.value.copy( material.normalScale );
  13376. }
  13377. // uv repeat and offset setting priorities
  13378. // 1. color map
  13379. // 2. specular map
  13380. // 3. normal map
  13381. // 4. bump map
  13382. var uvScaleMap;
  13383. if ( material.map ) {
  13384. uvScaleMap = material.map;
  13385. } else if ( material.specularMap ) {
  13386. uvScaleMap = material.specularMap;
  13387. } else if ( material.normalMap ) {
  13388. uvScaleMap = material.normalMap;
  13389. } else if ( material.bumpMap ) {
  13390. uvScaleMap = material.bumpMap;
  13391. }
  13392. if ( uvScaleMap !== undefined ) {
  13393. var offset = uvScaleMap.offset;
  13394. var repeat = uvScaleMap.repeat;
  13395. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13396. }
  13397. uniforms.envMap.value = material.envMap;
  13398. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  13399. if ( _this.gammaInput ) {
  13400. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  13401. uniforms.reflectivity.value = material.reflectivity;
  13402. } else {
  13403. uniforms.reflectivity.value = material.reflectivity;
  13404. }
  13405. uniforms.refractionRatio.value = material.refractionRatio;
  13406. uniforms.combine.value = material.combine;
  13407. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  13408. };
  13409. function refreshUniformsLine ( uniforms, material ) {
  13410. uniforms.diffuse.value = material.color;
  13411. uniforms.opacity.value = material.opacity;
  13412. };
  13413. function refreshUniformsDash ( uniforms, material ) {
  13414. uniforms.dashSize.value = material.dashSize;
  13415. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13416. uniforms.scale.value = material.scale;
  13417. };
  13418. function refreshUniformsParticle ( uniforms, material ) {
  13419. uniforms.psColor.value = material.color;
  13420. uniforms.opacity.value = material.opacity;
  13421. uniforms.size.value = material.size;
  13422. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  13423. uniforms.map.value = material.map;
  13424. };
  13425. function refreshUniformsFog ( uniforms, fog ) {
  13426. uniforms.fogColor.value = fog.color;
  13427. if ( fog instanceof THREE.Fog ) {
  13428. uniforms.fogNear.value = fog.near;
  13429. uniforms.fogFar.value = fog.far;
  13430. } else if ( fog instanceof THREE.FogExp2 ) {
  13431. uniforms.fogDensity.value = fog.density;
  13432. }
  13433. };
  13434. function refreshUniformsPhong ( uniforms, material ) {
  13435. uniforms.shininess.value = material.shininess;
  13436. if ( _this.gammaInput ) {
  13437. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13438. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13439. uniforms.specular.value.copyGammaToLinear( material.specular );
  13440. } else {
  13441. uniforms.ambient.value = material.ambient;
  13442. uniforms.emissive.value = material.emissive;
  13443. uniforms.specular.value = material.specular;
  13444. }
  13445. if ( material.wrapAround ) {
  13446. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13447. }
  13448. };
  13449. function refreshUniformsLambert ( uniforms, material ) {
  13450. if ( _this.gammaInput ) {
  13451. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13452. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13453. } else {
  13454. uniforms.ambient.value = material.ambient;
  13455. uniforms.emissive.value = material.emissive;
  13456. }
  13457. if ( material.wrapAround ) {
  13458. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13459. }
  13460. };
  13461. function refreshUniformsLights ( uniforms, lights ) {
  13462. uniforms.ambientLightColor.value = lights.ambient;
  13463. uniforms.directionalLightColor.value = lights.directional.colors;
  13464. uniforms.directionalLightDirection.value = lights.directional.positions;
  13465. uniforms.pointLightColor.value = lights.point.colors;
  13466. uniforms.pointLightPosition.value = lights.point.positions;
  13467. uniforms.pointLightDistance.value = lights.point.distances;
  13468. uniforms.spotLightColor.value = lights.spot.colors;
  13469. uniforms.spotLightPosition.value = lights.spot.positions;
  13470. uniforms.spotLightDistance.value = lights.spot.distances;
  13471. uniforms.spotLightDirection.value = lights.spot.directions;
  13472. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  13473. uniforms.spotLightExponent.value = lights.spot.exponents;
  13474. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  13475. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  13476. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  13477. };
  13478. function refreshUniformsShadow ( uniforms, lights ) {
  13479. if ( uniforms.shadowMatrix ) {
  13480. var j = 0;
  13481. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  13482. var light = lights[ i ];
  13483. if ( ! light.castShadow ) continue;
  13484. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  13485. uniforms.shadowMap.value[ j ] = light.shadowMap;
  13486. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  13487. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  13488. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  13489. uniforms.shadowBias.value[ j ] = light.shadowBias;
  13490. j ++;
  13491. }
  13492. }
  13493. }
  13494. };
  13495. // Uniforms (load to GPU)
  13496. function loadUniformsMatrices ( uniforms, object ) {
  13497. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  13498. if ( uniforms.normalMatrix ) {
  13499. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  13500. }
  13501. };
  13502. function getTextureUnit() {
  13503. var textureUnit = _usedTextureUnits;
  13504. if ( textureUnit >= _maxTextures ) {
  13505. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  13506. }
  13507. _usedTextureUnits += 1;
  13508. return textureUnit;
  13509. };
  13510. function loadUniformsGeneric ( program, uniforms ) {
  13511. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  13512. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  13513. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  13514. if ( !location ) continue;
  13515. uniform = uniforms[ j ][ 0 ];
  13516. type = uniform.type;
  13517. value = uniform.value;
  13518. if ( type === "i" ) { // single integer
  13519. _gl.uniform1i( location, value );
  13520. } else if ( type === "f" ) { // single float
  13521. _gl.uniform1f( location, value );
  13522. } else if ( type === "v2" ) { // single THREE.Vector2
  13523. _gl.uniform2f( location, value.x, value.y );
  13524. } else if ( type === "v3" ) { // single THREE.Vector3
  13525. _gl.uniform3f( location, value.x, value.y, value.z );
  13526. } else if ( type === "v4" ) { // single THREE.Vector4
  13527. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  13528. } else if ( type === "c" ) { // single THREE.Color
  13529. _gl.uniform3f( location, value.r, value.g, value.b );
  13530. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  13531. _gl.uniform1iv( location, value );
  13532. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  13533. _gl.uniform3iv( location, value );
  13534. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  13535. _gl.uniform1fv( location, value );
  13536. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  13537. _gl.uniform3fv( location, value );
  13538. } else if ( type === "v2v" ) { // array of THREE.Vector2
  13539. if ( uniform._array === undefined ) {
  13540. uniform._array = new Float32Array( 2 * value.length );
  13541. }
  13542. for ( i = 0, il = value.length; i < il; i ++ ) {
  13543. offset = i * 2;
  13544. uniform._array[ offset ] = value[ i ].x;
  13545. uniform._array[ offset + 1 ] = value[ i ].y;
  13546. }
  13547. _gl.uniform2fv( location, uniform._array );
  13548. } else if ( type === "v3v" ) { // array of THREE.Vector3
  13549. if ( uniform._array === undefined ) {
  13550. uniform._array = new Float32Array( 3 * value.length );
  13551. }
  13552. for ( i = 0, il = value.length; i < il; i ++ ) {
  13553. offset = i * 3;
  13554. uniform._array[ offset ] = value[ i ].x;
  13555. uniform._array[ offset + 1 ] = value[ i ].y;
  13556. uniform._array[ offset + 2 ] = value[ i ].z;
  13557. }
  13558. _gl.uniform3fv( location, uniform._array );
  13559. } else if ( type === "v4v" ) { // array of THREE.Vector4
  13560. if ( uniform._array === undefined ) {
  13561. uniform._array = new Float32Array( 4 * value.length );
  13562. }
  13563. for ( i = 0, il = value.length; i < il; i ++ ) {
  13564. offset = i * 4;
  13565. uniform._array[ offset ] = value[ i ].x;
  13566. uniform._array[ offset + 1 ] = value[ i ].y;
  13567. uniform._array[ offset + 2 ] = value[ i ].z;
  13568. uniform._array[ offset + 3 ] = value[ i ].w;
  13569. }
  13570. _gl.uniform4fv( location, uniform._array );
  13571. } else if ( type === "m4") { // single THREE.Matrix4
  13572. if ( uniform._array === undefined ) {
  13573. uniform._array = new Float32Array( 16 );
  13574. }
  13575. value.flattenToArray( uniform._array );
  13576. _gl.uniformMatrix4fv( location, false, uniform._array );
  13577. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  13578. if ( uniform._array === undefined ) {
  13579. uniform._array = new Float32Array( 16 * value.length );
  13580. }
  13581. for ( i = 0, il = value.length; i < il; i ++ ) {
  13582. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  13583. }
  13584. _gl.uniformMatrix4fv( location, false, uniform._array );
  13585. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  13586. texture = value;
  13587. textureUnit = getTextureUnit();
  13588. _gl.uniform1i( location, textureUnit );
  13589. if ( !texture ) continue;
  13590. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  13591. setCubeTexture( texture, textureUnit );
  13592. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  13593. setCubeTextureDynamic( texture, textureUnit );
  13594. } else {
  13595. _this.setTexture( texture, textureUnit );
  13596. }
  13597. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  13598. if ( uniform._array === undefined ) {
  13599. uniform._array = [];
  13600. }
  13601. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13602. uniform._array[ i ] = getTextureUnit();
  13603. }
  13604. _gl.uniform1iv( location, uniform._array );
  13605. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13606. texture = uniform.value[ i ];
  13607. textureUnit = uniform._array[ i ];
  13608. if ( !texture ) continue;
  13609. _this.setTexture( texture, textureUnit );
  13610. }
  13611. }
  13612. }
  13613. };
  13614. function setupMatrices ( object, camera ) {
  13615. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  13616. object._normalMatrix.getInverse( object._modelViewMatrix );
  13617. object._normalMatrix.transpose();
  13618. };
  13619. //
  13620. function setColorGamma( array, offset, color, intensitySq ) {
  13621. array[ offset ] = color.r * color.r * intensitySq;
  13622. array[ offset + 1 ] = color.g * color.g * intensitySq;
  13623. array[ offset + 2 ] = color.b * color.b * intensitySq;
  13624. };
  13625. function setColorLinear( array, offset, color, intensity ) {
  13626. array[ offset ] = color.r * intensity;
  13627. array[ offset + 1 ] = color.g * intensity;
  13628. array[ offset + 2 ] = color.b * intensity;
  13629. };
  13630. function setupLights ( program, lights ) {
  13631. var l, ll, light, n,
  13632. r = 0, g = 0, b = 0,
  13633. color, skyColor, groundColor,
  13634. intensity, intensitySq,
  13635. position,
  13636. distance,
  13637. zlights = _lights,
  13638. dirColors = zlights.directional.colors,
  13639. dirPositions = zlights.directional.positions,
  13640. pointColors = zlights.point.colors,
  13641. pointPositions = zlights.point.positions,
  13642. pointDistances = zlights.point.distances,
  13643. spotColors = zlights.spot.colors,
  13644. spotPositions = zlights.spot.positions,
  13645. spotDistances = zlights.spot.distances,
  13646. spotDirections = zlights.spot.directions,
  13647. spotAnglesCos = zlights.spot.anglesCos,
  13648. spotExponents = zlights.spot.exponents,
  13649. hemiSkyColors = zlights.hemi.skyColors,
  13650. hemiGroundColors = zlights.hemi.groundColors,
  13651. hemiPositions = zlights.hemi.positions,
  13652. dirLength = 0,
  13653. pointLength = 0,
  13654. spotLength = 0,
  13655. hemiLength = 0,
  13656. dirCount = 0,
  13657. pointCount = 0,
  13658. spotCount = 0,
  13659. hemiCount = 0,
  13660. dirOffset = 0,
  13661. pointOffset = 0,
  13662. spotOffset = 0,
  13663. hemiOffset = 0;
  13664. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13665. light = lights[ l ];
  13666. if ( light.onlyShadow ) continue;
  13667. color = light.color;
  13668. intensity = light.intensity;
  13669. distance = light.distance;
  13670. if ( light instanceof THREE.AmbientLight ) {
  13671. if ( ! light.visible ) continue;
  13672. if ( _this.gammaInput ) {
  13673. r += color.r * color.r;
  13674. g += color.g * color.g;
  13675. b += color.b * color.b;
  13676. } else {
  13677. r += color.r;
  13678. g += color.g;
  13679. b += color.b;
  13680. }
  13681. } else if ( light instanceof THREE.DirectionalLight ) {
  13682. dirCount += 1;
  13683. if ( ! light.visible ) continue;
  13684. _direction.copy( light.matrixWorld.getPosition() );
  13685. _direction.subSelf( light.target.matrixWorld.getPosition() );
  13686. _direction.normalize();
  13687. // skip lights with undefined direction
  13688. // these create troubles in OpenGL (making pixel black)
  13689. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  13690. dirOffset = dirLength * 3;
  13691. dirPositions[ dirOffset ] = _direction.x;
  13692. dirPositions[ dirOffset + 1 ] = _direction.y;
  13693. dirPositions[ dirOffset + 2 ] = _direction.z;
  13694. if ( _this.gammaInput ) {
  13695. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  13696. } else {
  13697. setColorLinear( dirColors, dirOffset, color, intensity );
  13698. }
  13699. dirLength += 1;
  13700. } else if ( light instanceof THREE.PointLight ) {
  13701. pointCount += 1;
  13702. if ( ! light.visible ) continue;
  13703. pointOffset = pointLength * 3;
  13704. if ( _this.gammaInput ) {
  13705. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  13706. } else {
  13707. setColorLinear( pointColors, pointOffset, color, intensity );
  13708. }
  13709. position = light.matrixWorld.getPosition();
  13710. pointPositions[ pointOffset ] = position.x;
  13711. pointPositions[ pointOffset + 1 ] = position.y;
  13712. pointPositions[ pointOffset + 2 ] = position.z;
  13713. pointDistances[ pointLength ] = distance;
  13714. pointLength += 1;
  13715. } else if ( light instanceof THREE.SpotLight ) {
  13716. spotCount += 1;
  13717. if ( ! light.visible ) continue;
  13718. spotOffset = spotLength * 3;
  13719. if ( _this.gammaInput ) {
  13720. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  13721. } else {
  13722. setColorLinear( spotColors, spotOffset, color, intensity );
  13723. }
  13724. position = light.matrixWorld.getPosition();
  13725. spotPositions[ spotOffset ] = position.x;
  13726. spotPositions[ spotOffset + 1 ] = position.y;
  13727. spotPositions[ spotOffset + 2 ] = position.z;
  13728. spotDistances[ spotLength ] = distance;
  13729. _direction.copy( position );
  13730. _direction.subSelf( light.target.matrixWorld.getPosition() );
  13731. _direction.normalize();
  13732. spotDirections[ spotOffset ] = _direction.x;
  13733. spotDirections[ spotOffset + 1 ] = _direction.y;
  13734. spotDirections[ spotOffset + 2 ] = _direction.z;
  13735. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  13736. spotExponents[ spotLength ] = light.exponent;
  13737. spotLength += 1;
  13738. } else if ( light instanceof THREE.HemisphereLight ) {
  13739. hemiCount += 1;
  13740. if ( ! light.visible ) continue;
  13741. _direction.copy( light.matrixWorld.getPosition() );
  13742. _direction.normalize();
  13743. // skip lights with undefined direction
  13744. // these create troubles in OpenGL (making pixel black)
  13745. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  13746. hemiOffset = hemiLength * 3;
  13747. hemiPositions[ hemiOffset ] = _direction.x;
  13748. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  13749. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  13750. skyColor = light.color;
  13751. groundColor = light.groundColor;
  13752. if ( _this.gammaInput ) {
  13753. intensitySq = intensity * intensity;
  13754. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  13755. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  13756. } else {
  13757. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  13758. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  13759. }
  13760. hemiLength += 1;
  13761. }
  13762. }
  13763. // null eventual remains from removed lights
  13764. // (this is to avoid if in shader)
  13765. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  13766. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  13767. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  13768. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  13769. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  13770. zlights.directional.length = dirLength;
  13771. zlights.point.length = pointLength;
  13772. zlights.spot.length = spotLength;
  13773. zlights.hemi.length = hemiLength;
  13774. zlights.ambient[ 0 ] = r;
  13775. zlights.ambient[ 1 ] = g;
  13776. zlights.ambient[ 2 ] = b;
  13777. };
  13778. // GL state setting
  13779. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13780. if ( cullFace === THREE.CullFaceNone ) {
  13781. _gl.disable( _gl.CULL_FACE );
  13782. } else {
  13783. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  13784. _gl.frontFace( _gl.CW );
  13785. } else {
  13786. _gl.frontFace( _gl.CCW );
  13787. }
  13788. if ( cullFace === THREE.CullFaceBack ) {
  13789. _gl.cullFace( _gl.BACK );
  13790. } else if ( cullFace === THREE.CullFaceFront ) {
  13791. _gl.cullFace( _gl.FRONT );
  13792. } else {
  13793. _gl.cullFace( _gl.FRONT_AND_BACK );
  13794. }
  13795. _gl.enable( _gl.CULL_FACE );
  13796. }
  13797. };
  13798. this.setMaterialFaces = function ( material ) {
  13799. var doubleSided = material.side === THREE.DoubleSide;
  13800. var flipSided = material.side === THREE.BackSide;
  13801. if ( _oldDoubleSided !== doubleSided ) {
  13802. if ( doubleSided ) {
  13803. _gl.disable( _gl.CULL_FACE );
  13804. } else {
  13805. _gl.enable( _gl.CULL_FACE );
  13806. }
  13807. _oldDoubleSided = doubleSided;
  13808. }
  13809. if ( _oldFlipSided !== flipSided ) {
  13810. if ( flipSided ) {
  13811. _gl.frontFace( _gl.CW );
  13812. } else {
  13813. _gl.frontFace( _gl.CCW );
  13814. }
  13815. _oldFlipSided = flipSided;
  13816. }
  13817. };
  13818. this.setDepthTest = function ( depthTest ) {
  13819. if ( _oldDepthTest !== depthTest ) {
  13820. if ( depthTest ) {
  13821. _gl.enable( _gl.DEPTH_TEST );
  13822. } else {
  13823. _gl.disable( _gl.DEPTH_TEST );
  13824. }
  13825. _oldDepthTest = depthTest;
  13826. }
  13827. };
  13828. this.setDepthWrite = function ( depthWrite ) {
  13829. if ( _oldDepthWrite !== depthWrite ) {
  13830. _gl.depthMask( depthWrite );
  13831. _oldDepthWrite = depthWrite;
  13832. }
  13833. };
  13834. function setLineWidth ( width ) {
  13835. if ( width !== _oldLineWidth ) {
  13836. _gl.lineWidth( width );
  13837. _oldLineWidth = width;
  13838. }
  13839. };
  13840. function setPolygonOffset ( polygonoffset, factor, units ) {
  13841. if ( _oldPolygonOffset !== polygonoffset ) {
  13842. if ( polygonoffset ) {
  13843. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  13844. } else {
  13845. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  13846. }
  13847. _oldPolygonOffset = polygonoffset;
  13848. }
  13849. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  13850. _gl.polygonOffset( factor, units );
  13851. _oldPolygonOffsetFactor = factor;
  13852. _oldPolygonOffsetUnits = units;
  13853. }
  13854. };
  13855. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  13856. if ( blending !== _oldBlending ) {
  13857. if ( blending === THREE.NoBlending ) {
  13858. _gl.disable( _gl.BLEND );
  13859. } else if ( blending === THREE.AdditiveBlending ) {
  13860. _gl.enable( _gl.BLEND );
  13861. _gl.blendEquation( _gl.FUNC_ADD );
  13862. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  13863. } else if ( blending === THREE.SubtractiveBlending ) {
  13864. // TODO: Find blendFuncSeparate() combination
  13865. _gl.enable( _gl.BLEND );
  13866. _gl.blendEquation( _gl.FUNC_ADD );
  13867. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  13868. } else if ( blending === THREE.MultiplyBlending ) {
  13869. // TODO: Find blendFuncSeparate() combination
  13870. _gl.enable( _gl.BLEND );
  13871. _gl.blendEquation( _gl.FUNC_ADD );
  13872. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  13873. } else if ( blending === THREE.CustomBlending ) {
  13874. _gl.enable( _gl.BLEND );
  13875. } else {
  13876. _gl.enable( _gl.BLEND );
  13877. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  13878. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  13879. }
  13880. _oldBlending = blending;
  13881. }
  13882. if ( blending === THREE.CustomBlending ) {
  13883. if ( blendEquation !== _oldBlendEquation ) {
  13884. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  13885. _oldBlendEquation = blendEquation;
  13886. }
  13887. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  13888. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  13889. _oldBlendSrc = blendSrc;
  13890. _oldBlendDst = blendDst;
  13891. }
  13892. } else {
  13893. _oldBlendEquation = null;
  13894. _oldBlendSrc = null;
  13895. _oldBlendDst = null;
  13896. }
  13897. };
  13898. // Defines
  13899. function generateDefines ( defines ) {
  13900. var value, chunk, chunks = [];
  13901. for ( var d in defines ) {
  13902. value = defines[ d ];
  13903. if ( value === false ) continue;
  13904. chunk = "#define " + d + " " + value;
  13905. chunks.push( chunk );
  13906. }
  13907. return chunks.join( "\n" );
  13908. };
  13909. // Shaders
  13910. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  13911. var p, pl, d, program, code;
  13912. var chunks = [];
  13913. // Generate code
  13914. if ( shaderID ) {
  13915. chunks.push( shaderID );
  13916. } else {
  13917. chunks.push( fragmentShader );
  13918. chunks.push( vertexShader );
  13919. }
  13920. for ( d in defines ) {
  13921. chunks.push( d );
  13922. chunks.push( defines[ d ] );
  13923. }
  13924. for ( p in parameters ) {
  13925. chunks.push( p );
  13926. chunks.push( parameters[ p ] );
  13927. }
  13928. code = chunks.join();
  13929. // Check if code has been already compiled
  13930. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  13931. var programInfo = _programs[ p ];
  13932. if ( programInfo.code === code ) {
  13933. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  13934. programInfo.usedTimes ++;
  13935. return programInfo.program;
  13936. }
  13937. }
  13938. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  13939. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  13940. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  13941. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  13942. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  13943. }
  13944. //console.log( "building new program " );
  13945. //
  13946. var customDefines = generateDefines( defines );
  13947. //
  13948. program = _gl.createProgram();
  13949. var prefix_vertex = [
  13950. "precision " + _precision + " float;",
  13951. customDefines,
  13952. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  13953. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13954. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13955. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13956. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13957. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13958. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13959. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13960. "#define MAX_SHADOWS " + parameters.maxShadows,
  13961. "#define MAX_BONES " + parameters.maxBones,
  13962. parameters.map ? "#define USE_MAP" : "",
  13963. parameters.envMap ? "#define USE_ENVMAP" : "",
  13964. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13965. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13966. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13967. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13968. parameters.vertexColors ? "#define USE_COLOR" : "",
  13969. parameters.skinning ? "#define USE_SKINNING" : "",
  13970. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  13971. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  13972. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  13973. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  13974. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  13975. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13976. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13977. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13978. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13979. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13980. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  13981. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13982. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13983. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  13984. "uniform mat4 modelMatrix;",
  13985. "uniform mat4 modelViewMatrix;",
  13986. "uniform mat4 projectionMatrix;",
  13987. "uniform mat4 viewMatrix;",
  13988. "uniform mat3 normalMatrix;",
  13989. "uniform vec3 cameraPosition;",
  13990. "attribute vec3 position;",
  13991. "attribute vec3 normal;",
  13992. "attribute vec2 uv;",
  13993. "attribute vec2 uv2;",
  13994. "#ifdef USE_COLOR",
  13995. "attribute vec3 color;",
  13996. "#endif",
  13997. "#ifdef USE_MORPHTARGETS",
  13998. "attribute vec3 morphTarget0;",
  13999. "attribute vec3 morphTarget1;",
  14000. "attribute vec3 morphTarget2;",
  14001. "attribute vec3 morphTarget3;",
  14002. "#ifdef USE_MORPHNORMALS",
  14003. "attribute vec3 morphNormal0;",
  14004. "attribute vec3 morphNormal1;",
  14005. "attribute vec3 morphNormal2;",
  14006. "attribute vec3 morphNormal3;",
  14007. "#else",
  14008. "attribute vec3 morphTarget4;",
  14009. "attribute vec3 morphTarget5;",
  14010. "attribute vec3 morphTarget6;",
  14011. "attribute vec3 morphTarget7;",
  14012. "#endif",
  14013. "#endif",
  14014. "#ifdef USE_SKINNING",
  14015. "attribute vec4 skinIndex;",
  14016. "attribute vec4 skinWeight;",
  14017. "#endif",
  14018. ""
  14019. ].join("\n");
  14020. var prefix_fragment = [
  14021. "precision " + _precision + " float;",
  14022. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14023. customDefines,
  14024. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14025. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14026. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14027. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14028. "#define MAX_SHADOWS " + parameters.maxShadows,
  14029. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14030. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14031. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14032. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14033. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14034. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14035. parameters.map ? "#define USE_MAP" : "",
  14036. parameters.envMap ? "#define USE_ENVMAP" : "",
  14037. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14038. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14039. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14040. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14041. parameters.vertexColors ? "#define USE_COLOR" : "",
  14042. parameters.metal ? "#define METAL" : "",
  14043. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14044. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14045. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14046. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14047. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14048. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14049. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14050. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14051. "uniform mat4 viewMatrix;",
  14052. "uniform vec3 cameraPosition;",
  14053. ""
  14054. ].join("\n");
  14055. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14056. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14057. _gl.attachShader( program, glVertexShader );
  14058. _gl.attachShader( program, glFragmentShader );
  14059. _gl.linkProgram( program );
  14060. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14061. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14062. }
  14063. // clean up
  14064. _gl.deleteShader( glFragmentShader );
  14065. _gl.deleteShader( glVertexShader );
  14066. //console.log( prefix_fragment + fragmentShader );
  14067. //console.log( prefix_vertex + vertexShader );
  14068. program.uniforms = {};
  14069. program.attributes = {};
  14070. var identifiers, u, a, i;
  14071. // cache uniform locations
  14072. identifiers = [
  14073. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14074. 'morphTargetInfluences'
  14075. ];
  14076. if ( parameters.useVertexTexture ) {
  14077. identifiers.push( 'boneTexture' );
  14078. } else {
  14079. identifiers.push( 'boneGlobalMatrices' );
  14080. }
  14081. for ( u in uniforms ) {
  14082. identifiers.push( u );
  14083. }
  14084. cacheUniformLocations( program, identifiers );
  14085. // cache attributes locations
  14086. identifiers = [
  14087. "position", "normal", "uv", "uv2", "tangent", "color",
  14088. "skinIndex", "skinWeight", "lineDistance"
  14089. ];
  14090. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14091. identifiers.push( "morphTarget" + i );
  14092. }
  14093. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14094. identifiers.push( "morphNormal" + i );
  14095. }
  14096. for ( a in attributes ) {
  14097. identifiers.push( a );
  14098. }
  14099. cacheAttributeLocations( program, identifiers );
  14100. program.id = _programs_counter ++;
  14101. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14102. _this.info.memory.programs = _programs.length;
  14103. return program;
  14104. };
  14105. // Shader parameters cache
  14106. function cacheUniformLocations ( program, identifiers ) {
  14107. var i, l, id;
  14108. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14109. id = identifiers[ i ];
  14110. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14111. }
  14112. };
  14113. function cacheAttributeLocations ( program, identifiers ) {
  14114. var i, l, id;
  14115. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14116. id = identifiers[ i ];
  14117. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14118. }
  14119. };
  14120. function addLineNumbers ( string ) {
  14121. var chunks = string.split( "\n" );
  14122. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14123. // Chrome reports shader errors on lines
  14124. // starting counting from 1
  14125. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14126. }
  14127. return chunks.join( "\n" );
  14128. };
  14129. function getShader ( type, string ) {
  14130. var shader;
  14131. if ( type === "fragment" ) {
  14132. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14133. } else if ( type === "vertex" ) {
  14134. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14135. }
  14136. _gl.shaderSource( shader, string );
  14137. _gl.compileShader( shader );
  14138. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14139. console.error( _gl.getShaderInfoLog( shader ) );
  14140. console.error( addLineNumbers( string ) );
  14141. return null;
  14142. }
  14143. return shader;
  14144. };
  14145. // Textures
  14146. function isPowerOfTwo ( value ) {
  14147. return ( value & ( value - 1 ) ) === 0;
  14148. };
  14149. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14150. if ( isImagePowerOfTwo ) {
  14151. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14152. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14153. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14154. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14155. } else {
  14156. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14157. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14158. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14159. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14160. }
  14161. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14162. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14163. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14164. texture.__oldAnisotropy = texture.anisotropy;
  14165. }
  14166. }
  14167. };
  14168. this.setTexture = function ( texture, slot ) {
  14169. if ( texture.needsUpdate ) {
  14170. if ( ! texture.__webglInit ) {
  14171. texture.__webglInit = true;
  14172. texture.addEventListener( 'dispose', onTextureDispose );
  14173. texture.__webglTexture = _gl.createTexture();
  14174. _this.info.memory.textures ++;
  14175. }
  14176. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14177. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14178. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14179. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14180. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14181. var image = texture.image,
  14182. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14183. glFormat = paramThreeToGL( texture.format ),
  14184. glType = paramThreeToGL( texture.type );
  14185. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14186. var mipmap, mipmaps = texture.mipmaps;
  14187. if ( texture instanceof THREE.DataTexture ) {
  14188. // use manually created mipmaps if available
  14189. // if there are no manual mipmaps
  14190. // set 0 level mipmap and then use GL to generate other mipmap levels
  14191. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14192. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14193. mipmap = mipmaps[ i ];
  14194. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14195. }
  14196. texture.generateMipmaps = false;
  14197. } else {
  14198. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14199. }
  14200. } else if ( texture instanceof THREE.CompressedTexture ) {
  14201. // compressed textures can only use manually created mipmaps
  14202. // WebGL can't generate mipmaps for DDS textures
  14203. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14204. mipmap = mipmaps[ i ];
  14205. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14206. }
  14207. } else { // regular Texture (image, video, canvas)
  14208. // use manually created mipmaps if available
  14209. // if there are no manual mipmaps
  14210. // set 0 level mipmap and then use GL to generate other mipmap levels
  14211. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14212. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14213. mipmap = mipmaps[ i ];
  14214. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14215. }
  14216. texture.generateMipmaps = false;
  14217. } else {
  14218. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14219. }
  14220. }
  14221. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14222. texture.needsUpdate = false;
  14223. if ( texture.onUpdate ) texture.onUpdate();
  14224. } else {
  14225. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14226. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14227. }
  14228. };
  14229. function clampToMaxSize ( image, maxSize ) {
  14230. if ( image.width <= maxSize && image.height <= maxSize ) {
  14231. return image;
  14232. }
  14233. // Warning: Scaling through the canvas will only work with images that use
  14234. // premultiplied alpha.
  14235. var maxDimension = Math.max( image.width, image.height );
  14236. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  14237. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  14238. var canvas = document.createElement( 'canvas' );
  14239. canvas.width = newWidth;
  14240. canvas.height = newHeight;
  14241. var ctx = canvas.getContext( "2d" );
  14242. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  14243. return canvas;
  14244. }
  14245. function setCubeTexture ( texture, slot ) {
  14246. if ( texture.image.length === 6 ) {
  14247. if ( texture.needsUpdate ) {
  14248. if ( ! texture.image.__webglTextureCube ) {
  14249. texture.image.__webglTextureCube = _gl.createTexture();
  14250. _this.info.memory.textures ++;
  14251. }
  14252. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14253. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14254. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14255. var isCompressed = texture instanceof THREE.CompressedTexture;
  14256. var cubeImage = [];
  14257. for ( var i = 0; i < 6; i ++ ) {
  14258. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  14259. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14260. } else {
  14261. cubeImage[ i ] = texture.image[ i ];
  14262. }
  14263. }
  14264. var image = cubeImage[ 0 ],
  14265. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14266. glFormat = paramThreeToGL( texture.format ),
  14267. glType = paramThreeToGL( texture.type );
  14268. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14269. for ( var i = 0; i < 6; i ++ ) {
  14270. if ( isCompressed ) {
  14271. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14272. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14273. mipmap = mipmaps[ j ];
  14274. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14275. }
  14276. } else {
  14277. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14278. }
  14279. }
  14280. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  14281. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14282. }
  14283. texture.needsUpdate = false;
  14284. if ( texture.onUpdate ) texture.onUpdate();
  14285. } else {
  14286. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14287. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14288. }
  14289. }
  14290. };
  14291. function setCubeTextureDynamic ( texture, slot ) {
  14292. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14293. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  14294. };
  14295. // Render targets
  14296. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  14297. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14298. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  14299. };
  14300. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  14301. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14302. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14303. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14304. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14305. /* For some reason this is not working. Defaulting to RGBA4.
  14306. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14307. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14308. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14309. */
  14310. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14311. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14312. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14313. } else {
  14314. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14315. }
  14316. };
  14317. this.setRenderTarget = function ( renderTarget ) {
  14318. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14319. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  14320. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14321. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14322. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14323. renderTarget.__webglTexture = _gl.createTexture();
  14324. _this.info.memory.textures ++;
  14325. // Setup texture, create render and frame buffers
  14326. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  14327. glFormat = paramThreeToGL( renderTarget.format ),
  14328. glType = paramThreeToGL( renderTarget.type );
  14329. if ( isCube ) {
  14330. renderTarget.__webglFramebuffer = [];
  14331. renderTarget.__webglRenderbuffer = [];
  14332. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14333. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  14334. for ( var i = 0; i < 6; i ++ ) {
  14335. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14336. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14337. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14338. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14339. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  14340. }
  14341. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14342. } else {
  14343. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  14344. if ( renderTarget.shareDepthFrom ) {
  14345. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  14346. } else {
  14347. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  14348. }
  14349. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14350. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  14351. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14352. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14353. if ( renderTarget.shareDepthFrom ) {
  14354. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14355. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14356. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14357. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14358. }
  14359. } else {
  14360. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  14361. }
  14362. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14363. }
  14364. // Release everything
  14365. if ( isCube ) {
  14366. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14367. } else {
  14368. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14369. }
  14370. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14371. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14372. }
  14373. var framebuffer, width, height, vx, vy;
  14374. if ( renderTarget ) {
  14375. if ( isCube ) {
  14376. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  14377. } else {
  14378. framebuffer = renderTarget.__webglFramebuffer;
  14379. }
  14380. width = renderTarget.width;
  14381. height = renderTarget.height;
  14382. vx = 0;
  14383. vy = 0;
  14384. } else {
  14385. framebuffer = null;
  14386. width = _viewportWidth;
  14387. height = _viewportHeight;
  14388. vx = _viewportX;
  14389. vy = _viewportY;
  14390. }
  14391. if ( framebuffer !== _currentFramebuffer ) {
  14392. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14393. _gl.viewport( vx, vy, width, height );
  14394. _currentFramebuffer = framebuffer;
  14395. }
  14396. _currentWidth = width;
  14397. _currentHeight = height;
  14398. };
  14399. function updateRenderTargetMipmap ( renderTarget ) {
  14400. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14401. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14402. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14403. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14404. } else {
  14405. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14406. _gl.generateMipmap( _gl.TEXTURE_2D );
  14407. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14408. }
  14409. };
  14410. // Fallback filters for non-power-of-2 textures
  14411. function filterFallback ( f ) {
  14412. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  14413. return _gl.NEAREST;
  14414. }
  14415. return _gl.LINEAR;
  14416. };
  14417. // Map three.js constants to WebGL constants
  14418. function paramThreeToGL ( p ) {
  14419. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  14420. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  14421. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  14422. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  14423. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  14424. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  14425. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  14426. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  14427. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  14428. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  14429. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  14430. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  14431. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  14432. if ( p === THREE.ByteType ) return _gl.BYTE;
  14433. if ( p === THREE.ShortType ) return _gl.SHORT;
  14434. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  14435. if ( p === THREE.IntType ) return _gl.INT;
  14436. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  14437. if ( p === THREE.FloatType ) return _gl.FLOAT;
  14438. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  14439. if ( p === THREE.RGBFormat ) return _gl.RGB;
  14440. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  14441. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  14442. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  14443. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  14444. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  14445. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  14446. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  14447. if ( p === THREE.OneFactor ) return _gl.ONE;
  14448. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  14449. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  14450. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  14451. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  14452. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  14453. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  14454. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  14455. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  14456. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  14457. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  14458. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14459. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14460. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14461. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14462. }
  14463. return 0;
  14464. };
  14465. // Allocations
  14466. function allocateBones ( object ) {
  14467. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  14468. return 1024;
  14469. } else {
  14470. // default for when object is not specified
  14471. // ( for example when prebuilding shader
  14472. // to be used with multiple objects )
  14473. //
  14474. // - leave some extra space for other uniforms
  14475. // - limit here is ANGLE's 254 max uniform vectors
  14476. // (up to 54 should be safe)
  14477. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  14478. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14479. var maxBones = nVertexMatrices;
  14480. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  14481. maxBones = Math.min( object.bones.length, maxBones );
  14482. if ( maxBones < object.bones.length ) {
  14483. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  14484. }
  14485. }
  14486. return maxBones;
  14487. }
  14488. };
  14489. function allocateLights ( lights ) {
  14490. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  14491. dirLights = pointLights = spotLights = hemiLights = 0;
  14492. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14493. light = lights[ l ];
  14494. if ( light.onlyShadow ) continue;
  14495. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  14496. if ( light instanceof THREE.PointLight ) pointLights ++;
  14497. if ( light instanceof THREE.SpotLight ) spotLights ++;
  14498. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  14499. }
  14500. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  14501. };
  14502. function allocateShadows ( lights ) {
  14503. var l, ll, light, maxShadows = 0;
  14504. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  14505. light = lights[ l ];
  14506. if ( ! light.castShadow ) continue;
  14507. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  14508. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  14509. }
  14510. return maxShadows;
  14511. };
  14512. // Initialization
  14513. function initGL () {
  14514. try {
  14515. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  14516. throw 'Error creating WebGL context.';
  14517. }
  14518. } catch ( error ) {
  14519. console.error( error );
  14520. }
  14521. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  14522. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  14523. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  14524. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  14525. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  14526. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  14527. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  14528. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  14529. if ( ! _glExtensionTextureFloat ) {
  14530. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  14531. }
  14532. if ( ! _glExtensionStandardDerivatives ) {
  14533. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  14534. }
  14535. if ( ! _glExtensionTextureFilterAnisotropic ) {
  14536. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  14537. }
  14538. if ( ! _glExtensionCompressedTextureS3TC ) {
  14539. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  14540. }
  14541. };
  14542. function setDefaultGLState () {
  14543. _gl.clearColor( 0, 0, 0, 1 );
  14544. _gl.clearDepth( 1 );
  14545. _gl.clearStencil( 0 );
  14546. _gl.enable( _gl.DEPTH_TEST );
  14547. _gl.depthFunc( _gl.LEQUAL );
  14548. _gl.frontFace( _gl.CCW );
  14549. _gl.cullFace( _gl.BACK );
  14550. _gl.enable( _gl.CULL_FACE );
  14551. _gl.enable( _gl.BLEND );
  14552. _gl.blendEquation( _gl.FUNC_ADD );
  14553. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  14554. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14555. };
  14556. // default plugins (order is important)
  14557. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  14558. this.addPrePlugin( this.shadowMapPlugin );
  14559. this.addPostPlugin( new THREE.SpritePlugin() );
  14560. this.addPostPlugin( new THREE.LensFlarePlugin() );
  14561. };
  14562. /**
  14563. * @author szimek / https://github.com/szimek/
  14564. * @author alteredq / http://alteredqualia.com/
  14565. */
  14566. THREE.WebGLRenderTarget = function ( width, height, options ) {
  14567. THREE.EventDispatcher.call( this );
  14568. this.width = width;
  14569. this.height = height;
  14570. options = options || {};
  14571. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  14572. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  14573. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  14574. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  14575. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  14576. this.offset = new THREE.Vector2( 0, 0 );
  14577. this.repeat = new THREE.Vector2( 1, 1 );
  14578. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  14579. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  14580. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  14581. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  14582. this.generateMipmaps = true;
  14583. this.shareDepthFrom = null;
  14584. };
  14585. THREE.WebGLRenderTarget.prototype.clone = function() {
  14586. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  14587. tmp.wrapS = this.wrapS;
  14588. tmp.wrapT = this.wrapT;
  14589. tmp.magFilter = this.magFilter;
  14590. tmp.minFilter = this.minFilter;
  14591. tmp.anisotropy = this.anisotropy;
  14592. tmp.offset.copy( this.offset );
  14593. tmp.repeat.copy( this.repeat );
  14594. tmp.format = this.format;
  14595. tmp.type = this.type;
  14596. tmp.depthBuffer = this.depthBuffer;
  14597. tmp.stencilBuffer = this.stencilBuffer;
  14598. tmp.generateMipmaps = this.generateMipmaps;
  14599. tmp.shareDepthFrom = this.shareDepthFrom;
  14600. return tmp;
  14601. };
  14602. THREE.WebGLRenderTarget.prototype.dispose = function () {
  14603. this.dispatchEvent( { type: 'dispose' } );
  14604. };
  14605. /**
  14606. * @author alteredq / http://alteredqualia.com
  14607. */
  14608. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  14609. THREE.WebGLRenderTarget.call( this, width, height, options );
  14610. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  14611. };
  14612. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  14613. /**
  14614. * @author mrdoob / http://mrdoob.com/
  14615. */
  14616. THREE.RenderableVertex = function () {
  14617. this.positionWorld = new THREE.Vector3();
  14618. this.positionScreen = new THREE.Vector4();
  14619. this.visible = true;
  14620. };
  14621. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  14622. this.positionWorld.copy( vertex.positionWorld );
  14623. this.positionScreen.copy( vertex.positionScreen );
  14624. }
  14625. /**
  14626. * @author mrdoob / http://mrdoob.com/
  14627. */
  14628. THREE.RenderableFace3 = function () {
  14629. this.v1 = new THREE.RenderableVertex();
  14630. this.v2 = new THREE.RenderableVertex();
  14631. this.v3 = new THREE.RenderableVertex();
  14632. this.centroidWorld = new THREE.Vector3();
  14633. this.centroidScreen = new THREE.Vector3();
  14634. this.normalWorld = new THREE.Vector3();
  14635. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14636. this.vertexNormalsLength = 0;
  14637. this.color = null;
  14638. this.material = null;
  14639. this.uvs = [[]];
  14640. this.z = null;
  14641. };
  14642. /**
  14643. * @author mrdoob / http://mrdoob.com/
  14644. */
  14645. THREE.RenderableFace4 = function () {
  14646. this.v1 = new THREE.RenderableVertex();
  14647. this.v2 = new THREE.RenderableVertex();
  14648. this.v3 = new THREE.RenderableVertex();
  14649. this.v4 = new THREE.RenderableVertex();
  14650. this.centroidWorld = new THREE.Vector3();
  14651. this.centroidScreen = new THREE.Vector3();
  14652. this.normalWorld = new THREE.Vector3();
  14653. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14654. this.vertexNormalsLength = 0;
  14655. this.color = null;
  14656. this.material = null;
  14657. this.uvs = [[]];
  14658. this.z = null;
  14659. };
  14660. /**
  14661. * @author mrdoob / http://mrdoob.com/
  14662. */
  14663. THREE.RenderableObject = function () {
  14664. this.object = null;
  14665. this.z = null;
  14666. };
  14667. /**
  14668. * @author mrdoob / http://mrdoob.com/
  14669. */
  14670. THREE.RenderableParticle = function () {
  14671. this.object = null;
  14672. this.x = null;
  14673. this.y = null;
  14674. this.z = null;
  14675. this.rotation = null;
  14676. this.scale = new THREE.Vector2();
  14677. this.material = null;
  14678. };
  14679. /**
  14680. * @author mrdoob / http://mrdoob.com/
  14681. */
  14682. THREE.RenderableLine = function () {
  14683. this.z = null;
  14684. this.v1 = new THREE.RenderableVertex();
  14685. this.v2 = new THREE.RenderableVertex();
  14686. this.material = null;
  14687. };
  14688. /**
  14689. * @author alteredq / http://alteredqualia.com/
  14690. */
  14691. THREE.ColorUtils = {
  14692. adjustHSV : function ( color, h, s, v ) {
  14693. var hsv = THREE.ColorUtils.__hsv;
  14694. color.getHSV( hsv );
  14695. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  14696. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  14697. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  14698. color.setHSV( hsv.h, hsv.s, hsv.v );
  14699. }
  14700. };
  14701. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  14702. * @author mrdoob / http://mrdoob.com/
  14703. * @author alteredq / http://alteredqualia.com/
  14704. */
  14705. THREE.GeometryUtils = {
  14706. // Merge two geometries or geometry and geometry from object (using object's transform)
  14707. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  14708. var matrix, matrixRotation,
  14709. vertexOffset = geometry1.vertices.length,
  14710. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  14711. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  14712. vertices1 = geometry1.vertices,
  14713. vertices2 = geometry2.vertices,
  14714. faces1 = geometry1.faces,
  14715. faces2 = geometry2.faces,
  14716. uvs1 = geometry1.faceVertexUvs[ 0 ],
  14717. uvs2 = geometry2.faceVertexUvs[ 0 ];
  14718. if ( object2 instanceof THREE.Mesh ) {
  14719. object2.matrixAutoUpdate && object2.updateMatrix();
  14720. matrix = object2.matrix;
  14721. matrixRotation = new THREE.Matrix4();
  14722. matrixRotation.extractRotation( matrix, object2.scale );
  14723. }
  14724. // vertices
  14725. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  14726. var vertex = vertices2[ i ];
  14727. var vertexCopy = vertex.clone();
  14728. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  14729. vertices1.push( vertexCopy );
  14730. }
  14731. // faces
  14732. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  14733. var face = faces2[ i ], faceCopy, normal, color,
  14734. faceVertexNormals = face.vertexNormals,
  14735. faceVertexColors = face.vertexColors;
  14736. if ( face instanceof THREE.Face3 ) {
  14737. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  14738. } else if ( face instanceof THREE.Face4 ) {
  14739. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  14740. }
  14741. faceCopy.normal.copy( face.normal );
  14742. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  14743. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  14744. normal = faceVertexNormals[ j ].clone();
  14745. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  14746. faceCopy.vertexNormals.push( normal );
  14747. }
  14748. faceCopy.color.copy( face.color );
  14749. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  14750. color = faceVertexColors[ j ];
  14751. faceCopy.vertexColors.push( color.clone() );
  14752. }
  14753. faceCopy.materialIndex = face.materialIndex;
  14754. faceCopy.centroid.copy( face.centroid );
  14755. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  14756. faces1.push( faceCopy );
  14757. }
  14758. // uvs
  14759. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  14760. var uv = uvs2[ i ], uvCopy = [];
  14761. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  14762. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  14763. }
  14764. uvs1.push( uvCopy );
  14765. }
  14766. },
  14767. removeMaterials: function ( geometry, materialIndexArray ) {
  14768. var materialIndexMap = {};
  14769. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  14770. materialIndexMap[ materialIndexArray[i] ] = true;
  14771. }
  14772. var face, newFaces = [];
  14773. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14774. face = geometry.faces[ i ];
  14775. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  14776. }
  14777. geometry.faces = newFaces;
  14778. },
  14779. // Get random point in triangle (via barycentric coordinates)
  14780. // (uniform distribution)
  14781. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  14782. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  14783. var a, b, c,
  14784. point = new THREE.Vector3(),
  14785. tmp = THREE.GeometryUtils.__v1;
  14786. a = THREE.GeometryUtils.random();
  14787. b = THREE.GeometryUtils.random();
  14788. if ( ( a + b ) > 1 ) {
  14789. a = 1 - a;
  14790. b = 1 - b;
  14791. }
  14792. c = 1 - a - b;
  14793. point.copy( vectorA );
  14794. point.multiplyScalar( a );
  14795. tmp.copy( vectorB );
  14796. tmp.multiplyScalar( b );
  14797. point.addSelf( tmp );
  14798. tmp.copy( vectorC );
  14799. tmp.multiplyScalar( c );
  14800. point.addSelf( tmp );
  14801. return point;
  14802. },
  14803. // Get random point in face (triangle / quad)
  14804. // (uniform distribution)
  14805. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  14806. var vA, vB, vC, vD;
  14807. if ( face instanceof THREE.Face3 ) {
  14808. vA = geometry.vertices[ face.a ];
  14809. vB = geometry.vertices[ face.b ];
  14810. vC = geometry.vertices[ face.c ];
  14811. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  14812. } else if ( face instanceof THREE.Face4 ) {
  14813. vA = geometry.vertices[ face.a ];
  14814. vB = geometry.vertices[ face.b ];
  14815. vC = geometry.vertices[ face.c ];
  14816. vD = geometry.vertices[ face.d ];
  14817. var area1, area2;
  14818. if ( useCachedAreas ) {
  14819. if ( face._area1 && face._area2 ) {
  14820. area1 = face._area1;
  14821. area2 = face._area2;
  14822. } else {
  14823. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14824. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14825. face._area1 = area1;
  14826. face._area2 = area2;
  14827. }
  14828. } else {
  14829. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  14830. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14831. }
  14832. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  14833. if ( r < area1 ) {
  14834. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  14835. } else {
  14836. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  14837. }
  14838. }
  14839. },
  14840. // Get uniformly distributed random points in mesh
  14841. // - create array with cumulative sums of face areas
  14842. // - pick random number from 0 to total area
  14843. // - find corresponding place in area array by binary search
  14844. // - get random point in face
  14845. randomPointsInGeometry: function ( geometry, n ) {
  14846. var face, i,
  14847. faces = geometry.faces,
  14848. vertices = geometry.vertices,
  14849. il = faces.length,
  14850. totalArea = 0,
  14851. cumulativeAreas = [],
  14852. vA, vB, vC, vD;
  14853. // precompute face areas
  14854. for ( i = 0; i < il; i ++ ) {
  14855. face = faces[ i ];
  14856. if ( face instanceof THREE.Face3 ) {
  14857. vA = vertices[ face.a ];
  14858. vB = vertices[ face.b ];
  14859. vC = vertices[ face.c ];
  14860. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  14861. } else if ( face instanceof THREE.Face4 ) {
  14862. vA = vertices[ face.a ];
  14863. vB = vertices[ face.b ];
  14864. vC = vertices[ face.c ];
  14865. vD = vertices[ face.d ];
  14866. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14867. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14868. face._area = face._area1 + face._area2;
  14869. }
  14870. totalArea += face._area;
  14871. cumulativeAreas[ i ] = totalArea;
  14872. }
  14873. // binary search cumulative areas array
  14874. function binarySearchIndices( value ) {
  14875. function binarySearch( start, end ) {
  14876. // return closest larger index
  14877. // if exact number is not found
  14878. if ( end < start )
  14879. return start;
  14880. var mid = start + Math.floor( ( end - start ) / 2 );
  14881. if ( cumulativeAreas[ mid ] > value ) {
  14882. return binarySearch( start, mid - 1 );
  14883. } else if ( cumulativeAreas[ mid ] < value ) {
  14884. return binarySearch( mid + 1, end );
  14885. } else {
  14886. return mid;
  14887. }
  14888. }
  14889. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  14890. return result;
  14891. }
  14892. // pick random face weighted by face area
  14893. var r, index,
  14894. result = [];
  14895. var stats = {};
  14896. for ( i = 0; i < n; i ++ ) {
  14897. r = THREE.GeometryUtils.random() * totalArea;
  14898. index = binarySearchIndices( r );
  14899. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  14900. if ( ! stats[ index ] ) {
  14901. stats[ index ] = 1;
  14902. } else {
  14903. stats[ index ] += 1;
  14904. }
  14905. }
  14906. return result;
  14907. },
  14908. // Get triangle area (half of parallelogram)
  14909. // http://mathworld.wolfram.com/TriangleArea.html
  14910. triangleArea: function ( vectorA, vectorB, vectorC ) {
  14911. var tmp1 = THREE.GeometryUtils.__v1,
  14912. tmp2 = THREE.GeometryUtils.__v2;
  14913. tmp1.sub( vectorB, vectorA );
  14914. tmp2.sub( vectorC, vectorA );
  14915. tmp1.crossSelf( tmp2 );
  14916. return 0.5 * tmp1.length();
  14917. },
  14918. // Center geometry so that 0,0,0 is in center of bounding box
  14919. center: function ( geometry ) {
  14920. geometry.computeBoundingBox();
  14921. var bb = geometry.boundingBox;
  14922. var offset = new THREE.Vector3();
  14923. offset.add( bb.min, bb.max );
  14924. offset.multiplyScalar( -0.5 );
  14925. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset ) );
  14926. geometry.computeBoundingBox();
  14927. return offset;
  14928. },
  14929. // Normalize UVs to be from <0,1>
  14930. // (for now just the first set of UVs)
  14931. normalizeUVs: function ( geometry ) {
  14932. var uvSet = geometry.faceVertexUvs[ 0 ];
  14933. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  14934. var uvs = uvSet[ i ];
  14935. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  14936. // texture repeat
  14937. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  14938. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  14939. }
  14940. }
  14941. },
  14942. triangulateQuads: function ( geometry ) {
  14943. var i, il, j, jl;
  14944. var faces = [];
  14945. var faceUvs = [];
  14946. var faceVertexUvs = [];
  14947. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  14948. faceUvs[ i ] = [];
  14949. }
  14950. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14951. faceVertexUvs[ i ] = [];
  14952. }
  14953. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14954. var face = geometry.faces[ i ];
  14955. if ( face instanceof THREE.Face4 ) {
  14956. var a = face.a;
  14957. var b = face.b;
  14958. var c = face.c;
  14959. var d = face.d;
  14960. var triA = new THREE.Face3();
  14961. var triB = new THREE.Face3();
  14962. triA.color.copy( face.color );
  14963. triB.color.copy( face.color );
  14964. triA.materialIndex = face.materialIndex;
  14965. triB.materialIndex = face.materialIndex;
  14966. triA.a = a;
  14967. triA.b = b;
  14968. triA.c = d;
  14969. triB.a = b;
  14970. triB.b = c;
  14971. triB.c = d;
  14972. if ( face.vertexColors.length === 4 ) {
  14973. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  14974. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  14975. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14976. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  14977. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  14978. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14979. }
  14980. faces.push( triA, triB );
  14981. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14982. if ( geometry.faceVertexUvs[ j ].length ) {
  14983. var uvs = geometry.faceVertexUvs[ j ][ i ];
  14984. var uvA = uvs[ 0 ];
  14985. var uvB = uvs[ 1 ];
  14986. var uvC = uvs[ 2 ];
  14987. var uvD = uvs[ 3 ];
  14988. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  14989. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  14990. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14991. }
  14992. }
  14993. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14994. if ( geometry.faceUvs[ j ].length ) {
  14995. var faceUv = geometry.faceUvs[ j ][ i ];
  14996. faceUvs[ j ].push( faceUv, faceUv );
  14997. }
  14998. }
  14999. } else {
  15000. faces.push( face );
  15001. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15002. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  15003. }
  15004. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15005. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15006. }
  15007. }
  15008. }
  15009. geometry.faces = faces;
  15010. geometry.faceUvs = faceUvs;
  15011. geometry.faceVertexUvs = faceVertexUvs;
  15012. geometry.computeCentroids();
  15013. geometry.computeFaceNormals();
  15014. geometry.computeVertexNormals();
  15015. if ( geometry.hasTangents ) geometry.computeTangents();
  15016. },
  15017. // Make all faces use unique vertices
  15018. // so that each face can be separated from others
  15019. explode: function( geometry ) {
  15020. var vertices = [];
  15021. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15022. var n = vertices.length;
  15023. var face = geometry.faces[ i ];
  15024. if ( face instanceof THREE.Face4 ) {
  15025. var a = face.a;
  15026. var b = face.b;
  15027. var c = face.c;
  15028. var d = face.d;
  15029. var va = geometry.vertices[ a ];
  15030. var vb = geometry.vertices[ b ];
  15031. var vc = geometry.vertices[ c ];
  15032. var vd = geometry.vertices[ d ];
  15033. vertices.push( va.clone() );
  15034. vertices.push( vb.clone() );
  15035. vertices.push( vc.clone() );
  15036. vertices.push( vd.clone() );
  15037. face.a = n;
  15038. face.b = n + 1;
  15039. face.c = n + 2;
  15040. face.d = n + 3;
  15041. } else {
  15042. var a = face.a;
  15043. var b = face.b;
  15044. var c = face.c;
  15045. var va = geometry.vertices[ a ];
  15046. var vb = geometry.vertices[ b ];
  15047. var vc = geometry.vertices[ c ];
  15048. vertices.push( va.clone() );
  15049. vertices.push( vb.clone() );
  15050. vertices.push( vc.clone() );
  15051. face.a = n;
  15052. face.b = n + 1;
  15053. face.c = n + 2;
  15054. }
  15055. }
  15056. geometry.vertices = vertices;
  15057. delete geometry.__tmpVertices;
  15058. },
  15059. // Break faces with edges longer than maxEdgeLength
  15060. // - not recursive
  15061. tessellate: function ( geometry, maxEdgeLength ) {
  15062. var i, il, face,
  15063. a, b, c, d,
  15064. va, vb, vc, vd,
  15065. dab, dbc, dac, dcd, dad,
  15066. m, m1, m2,
  15067. vm, vm1, vm2,
  15068. vnm, vnm1, vnm2,
  15069. vcm, vcm1, vcm2,
  15070. triA, triB,
  15071. quadA, quadB,
  15072. edge;
  15073. var faces = [];
  15074. var faceVertexUvs = [];
  15075. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15076. faceVertexUvs[ i ] = [];
  15077. }
  15078. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15079. face = geometry.faces[ i ];
  15080. if ( face instanceof THREE.Face3 ) {
  15081. a = face.a;
  15082. b = face.b;
  15083. c = face.c;
  15084. va = geometry.vertices[ a ];
  15085. vb = geometry.vertices[ b ];
  15086. vc = geometry.vertices[ c ];
  15087. dab = va.distanceTo( vb );
  15088. dbc = vb.distanceTo( vc );
  15089. dac = va.distanceTo( vc );
  15090. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  15091. m = geometry.vertices.length;
  15092. triA = face.clone();
  15093. triB = face.clone();
  15094. if ( dab >= dbc && dab >= dac ) {
  15095. vm = va.clone();
  15096. vm.lerpSelf( vb, 0.5 );
  15097. triA.a = a;
  15098. triA.b = m;
  15099. triA.c = c;
  15100. triB.a = m;
  15101. triB.b = b;
  15102. triB.c = c;
  15103. if ( face.vertexNormals.length === 3 ) {
  15104. vnm = face.vertexNormals[ 0 ].clone();
  15105. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  15106. triA.vertexNormals[ 1 ].copy( vnm );
  15107. triB.vertexNormals[ 0 ].copy( vnm );
  15108. }
  15109. if ( face.vertexColors.length === 3 ) {
  15110. vcm = face.vertexColors[ 0 ].clone();
  15111. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  15112. triA.vertexColors[ 1 ].copy( vcm );
  15113. triB.vertexColors[ 0 ].copy( vcm );
  15114. }
  15115. edge = 0;
  15116. } else if ( dbc >= dab && dbc >= dac ) {
  15117. vm = vb.clone();
  15118. vm.lerpSelf( vc, 0.5 );
  15119. triA.a = a;
  15120. triA.b = b;
  15121. triA.c = m;
  15122. triB.a = m;
  15123. triB.b = c;
  15124. triB.c = a;
  15125. if ( face.vertexNormals.length === 3 ) {
  15126. vnm = face.vertexNormals[ 1 ].clone();
  15127. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  15128. triA.vertexNormals[ 2 ].copy( vnm );
  15129. triB.vertexNormals[ 0 ].copy( vnm );
  15130. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  15131. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  15132. }
  15133. if ( face.vertexColors.length === 3 ) {
  15134. vcm = face.vertexColors[ 1 ].clone();
  15135. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  15136. triA.vertexColors[ 2 ].copy( vcm );
  15137. triB.vertexColors[ 0 ].copy( vcm );
  15138. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  15139. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  15140. }
  15141. edge = 1;
  15142. } else {
  15143. vm = va.clone();
  15144. vm.lerpSelf( vc, 0.5 );
  15145. triA.a = a;
  15146. triA.b = b;
  15147. triA.c = m;
  15148. triB.a = m;
  15149. triB.b = b;
  15150. triB.c = c;
  15151. if ( face.vertexNormals.length === 3 ) {
  15152. vnm = face.vertexNormals[ 0 ].clone();
  15153. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  15154. triA.vertexNormals[ 2 ].copy( vnm );
  15155. triB.vertexNormals[ 0 ].copy( vnm );
  15156. }
  15157. if ( face.vertexColors.length === 3 ) {
  15158. vcm = face.vertexColors[ 0 ].clone();
  15159. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  15160. triA.vertexColors[ 2 ].copy( vcm );
  15161. triB.vertexColors[ 0 ].copy( vcm );
  15162. }
  15163. edge = 2;
  15164. }
  15165. faces.push( triA, triB );
  15166. geometry.vertices.push( vm );
  15167. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  15168. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15169. if ( geometry.faceVertexUvs[ j ].length ) {
  15170. uvs = geometry.faceVertexUvs[ j ][ i ];
  15171. uvA = uvs[ 0 ];
  15172. uvB = uvs[ 1 ];
  15173. uvC = uvs[ 2 ];
  15174. // AB
  15175. if ( edge === 0 ) {
  15176. uvM = uvA.clone();
  15177. uvM.lerpSelf( uvB, 0.5 );
  15178. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  15179. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  15180. // BC
  15181. } else if ( edge === 1 ) {
  15182. uvM = uvB.clone();
  15183. uvM.lerpSelf( uvC, 0.5 );
  15184. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  15185. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  15186. // AC
  15187. } else {
  15188. uvM = uvA.clone();
  15189. uvM.lerpSelf( uvC, 0.5 );
  15190. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  15191. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  15192. }
  15193. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  15194. }
  15195. }
  15196. } else {
  15197. faces.push( face );
  15198. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15199. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15200. }
  15201. }
  15202. } else {
  15203. a = face.a;
  15204. b = face.b;
  15205. c = face.c;
  15206. d = face.d;
  15207. va = geometry.vertices[ a ];
  15208. vb = geometry.vertices[ b ];
  15209. vc = geometry.vertices[ c ];
  15210. vd = geometry.vertices[ d ];
  15211. dab = va.distanceTo( vb );
  15212. dbc = vb.distanceTo( vc );
  15213. dcd = vc.distanceTo( vd );
  15214. dad = va.distanceTo( vd );
  15215. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  15216. m1 = geometry.vertices.length;
  15217. m2 = geometry.vertices.length + 1;
  15218. quadA = face.clone();
  15219. quadB = face.clone();
  15220. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  15221. vm1 = va.clone();
  15222. vm1.lerpSelf( vb, 0.5 );
  15223. vm2 = vc.clone();
  15224. vm2.lerpSelf( vd, 0.5 );
  15225. quadA.a = a;
  15226. quadA.b = m1;
  15227. quadA.c = m2;
  15228. quadA.d = d;
  15229. quadB.a = m1;
  15230. quadB.b = b;
  15231. quadB.c = c;
  15232. quadB.d = m2;
  15233. if ( face.vertexNormals.length === 4 ) {
  15234. vnm1 = face.vertexNormals[ 0 ].clone();
  15235. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  15236. vnm2 = face.vertexNormals[ 2 ].clone();
  15237. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  15238. quadA.vertexNormals[ 1 ].copy( vnm1 );
  15239. quadA.vertexNormals[ 2 ].copy( vnm2 );
  15240. quadB.vertexNormals[ 0 ].copy( vnm1 );
  15241. quadB.vertexNormals[ 3 ].copy( vnm2 );
  15242. }
  15243. if ( face.vertexColors.length === 4 ) {
  15244. vcm1 = face.vertexColors[ 0 ].clone();
  15245. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  15246. vcm2 = face.vertexColors[ 2 ].clone();
  15247. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  15248. quadA.vertexColors[ 1 ].copy( vcm1 );
  15249. quadA.vertexColors[ 2 ].copy( vcm2 );
  15250. quadB.vertexColors[ 0 ].copy( vcm1 );
  15251. quadB.vertexColors[ 3 ].copy( vcm2 );
  15252. }
  15253. edge = 0;
  15254. } else {
  15255. vm1 = vb.clone();
  15256. vm1.lerpSelf( vc, 0.5 );
  15257. vm2 = vd.clone();
  15258. vm2.lerpSelf( va, 0.5 );
  15259. quadA.a = a;
  15260. quadA.b = b;
  15261. quadA.c = m1;
  15262. quadA.d = m2;
  15263. quadB.a = m2;
  15264. quadB.b = m1;
  15265. quadB.c = c;
  15266. quadB.d = d;
  15267. if ( face.vertexNormals.length === 4 ) {
  15268. vnm1 = face.vertexNormals[ 1 ].clone();
  15269. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  15270. vnm2 = face.vertexNormals[ 3 ].clone();
  15271. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  15272. quadA.vertexNormals[ 2 ].copy( vnm1 );
  15273. quadA.vertexNormals[ 3 ].copy( vnm2 );
  15274. quadB.vertexNormals[ 0 ].copy( vnm2 );
  15275. quadB.vertexNormals[ 1 ].copy( vnm1 );
  15276. }
  15277. if ( face.vertexColors.length === 4 ) {
  15278. vcm1 = face.vertexColors[ 1 ].clone();
  15279. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  15280. vcm2 = face.vertexColors[ 3 ].clone();
  15281. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  15282. quadA.vertexColors[ 2 ].copy( vcm1 );
  15283. quadA.vertexColors[ 3 ].copy( vcm2 );
  15284. quadB.vertexColors[ 0 ].copy( vcm2 );
  15285. quadB.vertexColors[ 1 ].copy( vcm1 );
  15286. }
  15287. edge = 1;
  15288. }
  15289. faces.push( quadA, quadB );
  15290. geometry.vertices.push( vm1, vm2 );
  15291. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  15292. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15293. if ( geometry.faceVertexUvs[ j ].length ) {
  15294. uvs = geometry.faceVertexUvs[ j ][ i ];
  15295. uvA = uvs[ 0 ];
  15296. uvB = uvs[ 1 ];
  15297. uvC = uvs[ 2 ];
  15298. uvD = uvs[ 3 ];
  15299. // AB + CD
  15300. if ( edge === 0 ) {
  15301. uvM1 = uvA.clone();
  15302. uvM1.lerpSelf( uvB, 0.5 );
  15303. uvM2 = uvC.clone();
  15304. uvM2.lerpSelf( uvD, 0.5 );
  15305. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  15306. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  15307. // BC + AD
  15308. } else {
  15309. uvM1 = uvB.clone();
  15310. uvM1.lerpSelf( uvC, 0.5 );
  15311. uvM2 = uvD.clone();
  15312. uvM2.lerpSelf( uvA, 0.5 );
  15313. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  15314. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  15315. }
  15316. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  15317. }
  15318. }
  15319. } else {
  15320. faces.push( face );
  15321. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15322. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15323. }
  15324. }
  15325. }
  15326. }
  15327. geometry.faces = faces;
  15328. geometry.faceVertexUvs = faceVertexUvs;
  15329. }
  15330. };
  15331. THREE.GeometryUtils.random = THREE.Math.random16;
  15332. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  15333. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  15334. /**
  15335. * @author alteredq / http://alteredqualia.com/
  15336. * @author mrdoob / http://mrdoob.com/
  15337. */
  15338. THREE.ImageUtils = {
  15339. crossOrigin: 'anonymous',
  15340. loadTexture: function ( url, mapping, onLoad, onError ) {
  15341. var image = new Image();
  15342. var texture = new THREE.Texture( image, mapping );
  15343. var loader = new THREE.ImageLoader();
  15344. loader.addEventListener( 'load', function ( event ) {
  15345. texture.image = event.content;
  15346. texture.needsUpdate = true;
  15347. if ( onLoad ) onLoad( texture );
  15348. } );
  15349. loader.addEventListener( 'error', function ( event ) {
  15350. if ( onError ) onError( event.message );
  15351. } );
  15352. loader.crossOrigin = this.crossOrigin;
  15353. loader.load( url, image );
  15354. texture.sourceFile = url;
  15355. return texture;
  15356. },
  15357. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15358. var texture = new THREE.CompressedTexture();
  15359. texture.mapping = mapping;
  15360. var request = new XMLHttpRequest();
  15361. request.onload = function () {
  15362. var buffer = request.response;
  15363. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15364. texture.format = dds.format;
  15365. texture.mipmaps = dds.mipmaps;
  15366. texture.image.width = dds.width;
  15367. texture.image.height = dds.height;
  15368. // gl.generateMipmap fails for compressed textures
  15369. // mipmaps must be embedded in the DDS file
  15370. // or texture filters must not use mipmapping
  15371. texture.generateMipmaps = false;
  15372. texture.needsUpdate = true;
  15373. if ( onLoad ) onLoad( texture );
  15374. }
  15375. request.onerror = onError;
  15376. request.open( 'GET', url, true );
  15377. request.responseType = "arraybuffer";
  15378. request.send( null );
  15379. return texture;
  15380. },
  15381. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15382. var images = [];
  15383. images.loadCount = 0;
  15384. var texture = new THREE.Texture();
  15385. texture.image = images;
  15386. if ( mapping !== undefined ) texture.mapping = mapping;
  15387. // no flipping needed for cube textures
  15388. texture.flipY = false;
  15389. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15390. var cubeImage = new Image();
  15391. images[ i ] = cubeImage;
  15392. cubeImage.onload = function () {
  15393. images.loadCount += 1;
  15394. if ( images.loadCount === 6 ) {
  15395. texture.needsUpdate = true;
  15396. if ( onLoad ) onLoad( texture );
  15397. }
  15398. };
  15399. cubeImage.onerror = onError;
  15400. cubeImage.crossOrigin = this.crossOrigin;
  15401. cubeImage.src = array[ i ];
  15402. }
  15403. return texture;
  15404. },
  15405. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15406. var images = [];
  15407. images.loadCount = 0;
  15408. var texture = new THREE.CompressedTexture();
  15409. texture.image = images;
  15410. if ( mapping !== undefined ) texture.mapping = mapping;
  15411. // no flipping for cube textures
  15412. // (also flipping doesn't work for compressed textures )
  15413. texture.flipY = false;
  15414. // can't generate mipmaps for compressed textures
  15415. // mips must be embedded in DDS files
  15416. texture.generateMipmaps = false;
  15417. var generateCubeFaceCallback = function ( rq, img ) {
  15418. return function () {
  15419. var buffer = rq.response;
  15420. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15421. img.format = dds.format;
  15422. img.mipmaps = dds.mipmaps;
  15423. img.width = dds.width;
  15424. img.height = dds.height;
  15425. images.loadCount += 1;
  15426. if ( images.loadCount === 6 ) {
  15427. texture.format = dds.format;
  15428. texture.needsUpdate = true;
  15429. if ( onLoad ) onLoad( texture );
  15430. }
  15431. }
  15432. }
  15433. // compressed cubemap textures as 6 separate DDS files
  15434. if ( array instanceof Array ) {
  15435. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15436. var cubeImage = {};
  15437. images[ i ] = cubeImage;
  15438. var request = new XMLHttpRequest();
  15439. request.onload = generateCubeFaceCallback( request, cubeImage );
  15440. request.onerror = onError;
  15441. var url = array[ i ];
  15442. request.open( 'GET', url, true );
  15443. request.responseType = "arraybuffer";
  15444. request.send( null );
  15445. }
  15446. // compressed cubemap texture stored in a single DDS file
  15447. } else {
  15448. var url = array;
  15449. var request = new XMLHttpRequest();
  15450. request.onload = function( ) {
  15451. var buffer = request.response;
  15452. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15453. if ( dds.isCubemap ) {
  15454. var faces = dds.mipmaps.length / dds.mipmapCount;
  15455. for ( var f = 0; f < faces; f ++ ) {
  15456. images[ f ] = { mipmaps : [] };
  15457. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15458. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15459. images[ f ].format = dds.format;
  15460. images[ f ].width = dds.width;
  15461. images[ f ].height = dds.height;
  15462. }
  15463. }
  15464. texture.format = dds.format;
  15465. texture.needsUpdate = true;
  15466. if ( onLoad ) onLoad( texture );
  15467. }
  15468. }
  15469. request.onerror = onError;
  15470. request.open( 'GET', url, true );
  15471. request.responseType = "arraybuffer";
  15472. request.send( null );
  15473. }
  15474. return texture;
  15475. },
  15476. parseDDS: function ( buffer, loadMipmaps ) {
  15477. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15478. // Adapted from @toji's DDS utils
  15479. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15480. // All values and structures referenced from:
  15481. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15482. var DDS_MAGIC = 0x20534444;
  15483. var DDSD_CAPS = 0x1,
  15484. DDSD_HEIGHT = 0x2,
  15485. DDSD_WIDTH = 0x4,
  15486. DDSD_PITCH = 0x8,
  15487. DDSD_PIXELFORMAT = 0x1000,
  15488. DDSD_MIPMAPCOUNT = 0x20000,
  15489. DDSD_LINEARSIZE = 0x80000,
  15490. DDSD_DEPTH = 0x800000;
  15491. var DDSCAPS_COMPLEX = 0x8,
  15492. DDSCAPS_MIPMAP = 0x400000,
  15493. DDSCAPS_TEXTURE = 0x1000;
  15494. var DDSCAPS2_CUBEMAP = 0x200,
  15495. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15496. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15497. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15498. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15499. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15500. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15501. DDSCAPS2_VOLUME = 0x200000;
  15502. var DDPF_ALPHAPIXELS = 0x1,
  15503. DDPF_ALPHA = 0x2,
  15504. DDPF_FOURCC = 0x4,
  15505. DDPF_RGB = 0x40,
  15506. DDPF_YUV = 0x200,
  15507. DDPF_LUMINANCE = 0x20000;
  15508. function fourCCToInt32( value ) {
  15509. return value.charCodeAt(0) +
  15510. (value.charCodeAt(1) << 8) +
  15511. (value.charCodeAt(2) << 16) +
  15512. (value.charCodeAt(3) << 24);
  15513. }
  15514. function int32ToFourCC( value ) {
  15515. return String.fromCharCode(
  15516. value & 0xff,
  15517. (value >> 8) & 0xff,
  15518. (value >> 16) & 0xff,
  15519. (value >> 24) & 0xff
  15520. );
  15521. }
  15522. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15523. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15524. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15525. var headerLengthInt = 31; // The header length in 32 bit ints
  15526. // Offsets into the header array
  15527. var off_magic = 0;
  15528. var off_size = 1;
  15529. var off_flags = 2;
  15530. var off_height = 3;
  15531. var off_width = 4;
  15532. var off_mipmapCount = 7;
  15533. var off_pfFlags = 20;
  15534. var off_pfFourCC = 21;
  15535. var off_caps = 27;
  15536. var off_caps2 = 28;
  15537. var off_caps3 = 29;
  15538. var off_caps4 = 30;
  15539. // Parse header
  15540. var header = new Int32Array( buffer, 0, headerLengthInt );
  15541. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15542. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15543. return dds;
  15544. }
  15545. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15546. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15547. return dds;
  15548. }
  15549. var blockBytes;
  15550. var fourCC = header[ off_pfFourCC ];
  15551. switch ( fourCC ) {
  15552. case FOURCC_DXT1:
  15553. blockBytes = 8;
  15554. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15555. break;
  15556. case FOURCC_DXT3:
  15557. blockBytes = 16;
  15558. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15559. break;
  15560. case FOURCC_DXT5:
  15561. blockBytes = 16;
  15562. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15563. break;
  15564. default:
  15565. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15566. return dds;
  15567. }
  15568. dds.mipmapCount = 1;
  15569. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15570. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15571. }
  15572. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15573. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15574. dds.width = header[ off_width ];
  15575. dds.height = header[ off_height ];
  15576. var dataOffset = header[ off_size ] + 4;
  15577. // Extract mipmaps buffers
  15578. var width = dds.width;
  15579. var height = dds.height;
  15580. var faces = dds.isCubemap ? 6 : 1;
  15581. for ( var face = 0; face < faces; face ++ ) {
  15582. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15583. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  15584. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  15585. var mipmap = { "data": byteArray, "width": width, "height": height };
  15586. dds.mipmaps.push( mipmap );
  15587. dataOffset += dataLength;
  15588. width = Math.max( width * 0.5, 1 );
  15589. height = Math.max( height * 0.5, 1 );
  15590. }
  15591. width = dds.width;
  15592. height = dds.height;
  15593. }
  15594. return dds;
  15595. },
  15596. getNormalMap: function ( image, depth ) {
  15597. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15598. var cross = function ( a, b ) {
  15599. 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 ] ];
  15600. }
  15601. var subtract = function ( a, b ) {
  15602. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15603. }
  15604. var normalize = function ( a ) {
  15605. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15606. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15607. }
  15608. depth = depth | 1;
  15609. var width = image.width;
  15610. var height = image.height;
  15611. var canvas = document.createElement( 'canvas' );
  15612. canvas.width = width;
  15613. canvas.height = height;
  15614. var context = canvas.getContext( '2d' );
  15615. context.drawImage( image, 0, 0 );
  15616. var data = context.getImageData( 0, 0, width, height ).data;
  15617. var imageData = context.createImageData( width, height );
  15618. var output = imageData.data;
  15619. for ( var x = 0; x < width; x ++ ) {
  15620. for ( var y = 0; y < height; y ++ ) {
  15621. var ly = y - 1 < 0 ? 0 : y - 1;
  15622. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15623. var lx = x - 1 < 0 ? 0 : x - 1;
  15624. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15625. var points = [];
  15626. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15627. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15628. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15629. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15630. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15631. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15632. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15633. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15634. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15635. var normals = [];
  15636. var num_points = points.length;
  15637. for ( var i = 0; i < num_points; i ++ ) {
  15638. var v1 = points[ i ];
  15639. var v2 = points[ ( i + 1 ) % num_points ];
  15640. v1 = subtract( v1, origin );
  15641. v2 = subtract( v2, origin );
  15642. normals.push( normalize( cross( v1, v2 ) ) );
  15643. }
  15644. var normal = [ 0, 0, 0 ];
  15645. for ( var i = 0; i < normals.length; i ++ ) {
  15646. normal[ 0 ] += normals[ i ][ 0 ];
  15647. normal[ 1 ] += normals[ i ][ 1 ];
  15648. normal[ 2 ] += normals[ i ][ 2 ];
  15649. }
  15650. normal[ 0 ] /= normals.length;
  15651. normal[ 1 ] /= normals.length;
  15652. normal[ 2 ] /= normals.length;
  15653. var idx = ( y * width + x ) * 4;
  15654. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15655. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15656. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15657. output[ idx + 3 ] = 255;
  15658. }
  15659. }
  15660. context.putImageData( imageData, 0, 0 );
  15661. return canvas;
  15662. },
  15663. generateDataTexture: function ( width, height, color ) {
  15664. var size = width * height;
  15665. var data = new Uint8Array( 3 * size );
  15666. var r = Math.floor( color.r * 255 );
  15667. var g = Math.floor( color.g * 255 );
  15668. var b = Math.floor( color.b * 255 );
  15669. for ( var i = 0; i < size; i ++ ) {
  15670. data[ i * 3 ] = r;
  15671. data[ i * 3 + 1 ] = g;
  15672. data[ i * 3 + 2 ] = b;
  15673. }
  15674. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15675. texture.needsUpdate = true;
  15676. return texture;
  15677. }
  15678. };
  15679. /**
  15680. * @author alteredq / http://alteredqualia.com/
  15681. */
  15682. THREE.SceneUtils = {
  15683. createMultiMaterialObject: function ( geometry, materials ) {
  15684. var group = new THREE.Object3D();
  15685. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15686. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15687. }
  15688. return group;
  15689. },
  15690. detach : function ( child, parent, scene ) {
  15691. child.applyMatrix( parent.matrixWorld );
  15692. parent.remove( child );
  15693. scene.add( child );
  15694. },
  15695. attach: function ( child, scene, parent ) {
  15696. var matrixWorldInverse = new THREE.Matrix4();
  15697. matrixWorldInverse.getInverse( parent.matrixWorld );
  15698. child.applyMatrix( matrixWorldInverse );
  15699. scene.remove( child );
  15700. parent.add( child );
  15701. }
  15702. };
  15703. /**
  15704. * @author alteredq / http://alteredqualia.com/
  15705. * @author mrdoob / http://mrdoob.com/
  15706. *
  15707. * ShaderUtils currently contains:
  15708. *
  15709. * fresnel
  15710. * normal
  15711. * cube
  15712. *
  15713. */
  15714. THREE.ShaderUtils = {
  15715. lib: {
  15716. /* -------------------------------------------------------------------------
  15717. // Fresnel shader
  15718. // - based on Nvidia Cg tutorial
  15719. ------------------------------------------------------------------------- */
  15720. 'fresnel': {
  15721. uniforms: {
  15722. "mRefractionRatio": { type: "f", value: 1.02 },
  15723. "mFresnelBias": { type: "f", value: 0.1 },
  15724. "mFresnelPower": { type: "f", value: 2.0 },
  15725. "mFresnelScale": { type: "f", value: 1.0 },
  15726. "tCube": { type: "t", value: null }
  15727. },
  15728. fragmentShader: [
  15729. "uniform samplerCube tCube;",
  15730. "varying vec3 vReflect;",
  15731. "varying vec3 vRefract[3];",
  15732. "varying float vReflectionFactor;",
  15733. "void main() {",
  15734. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15735. "vec4 refractedColor = vec4( 1.0 );",
  15736. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  15737. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  15738. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  15739. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  15740. "}"
  15741. ].join("\n"),
  15742. vertexShader: [
  15743. "uniform float mRefractionRatio;",
  15744. "uniform float mFresnelBias;",
  15745. "uniform float mFresnelScale;",
  15746. "uniform float mFresnelPower;",
  15747. "varying vec3 vReflect;",
  15748. "varying vec3 vRefract[3];",
  15749. "varying float vReflectionFactor;",
  15750. "void main() {",
  15751. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  15752. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15753. "vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  15754. "vec3 I = worldPosition.xyz - cameraPosition;",
  15755. "vReflect = reflect( I, worldNormal );",
  15756. "vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );",
  15757. "vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );",
  15758. "vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );",
  15759. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );",
  15760. "gl_Position = projectionMatrix * mvPosition;",
  15761. "}"
  15762. ].join("\n")
  15763. },
  15764. /* -------------------------------------------------------------------------
  15765. // Normal map shader
  15766. // - Blinn-Phong
  15767. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  15768. // - point and directional lights (use with "lights: true" material option)
  15769. ------------------------------------------------------------------------- */
  15770. 'normal' : {
  15771. uniforms: THREE.UniformsUtils.merge( [
  15772. THREE.UniformsLib[ "fog" ],
  15773. THREE.UniformsLib[ "lights" ],
  15774. THREE.UniformsLib[ "shadowmap" ],
  15775. {
  15776. "enableAO" : { type: "i", value: 0 },
  15777. "enableDiffuse" : { type: "i", value: 0 },
  15778. "enableSpecular" : { type: "i", value: 0 },
  15779. "enableReflection": { type: "i", value: 0 },
  15780. "enableDisplacement": { type: "i", value: 0 },
  15781. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  15782. "tDiffuse" : { type: "t", value: null },
  15783. "tCube" : { type: "t", value: null },
  15784. "tNormal" : { type: "t", value: null },
  15785. "tSpecular" : { type: "t", value: null },
  15786. "tAO" : { type: "t", value: null },
  15787. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  15788. "uDisplacementBias": { type: "f", value: 0.0 },
  15789. "uDisplacementScale": { type: "f", value: 1.0 },
  15790. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  15791. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  15792. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  15793. "uShininess": { type: "f", value: 30 },
  15794. "uOpacity": { type: "f", value: 1 },
  15795. "useRefract": { type: "i", value: 0 },
  15796. "uRefractionRatio": { type: "f", value: 0.98 },
  15797. "uReflectivity": { type: "f", value: 0.5 },
  15798. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  15799. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  15800. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  15801. }
  15802. ] ),
  15803. fragmentShader: [
  15804. "uniform vec3 uAmbientColor;",
  15805. "uniform vec3 uDiffuseColor;",
  15806. "uniform vec3 uSpecularColor;",
  15807. "uniform float uShininess;",
  15808. "uniform float uOpacity;",
  15809. "uniform bool enableDiffuse;",
  15810. "uniform bool enableSpecular;",
  15811. "uniform bool enableAO;",
  15812. "uniform bool enableReflection;",
  15813. "uniform sampler2D tDiffuse;",
  15814. "uniform sampler2D tNormal;",
  15815. "uniform sampler2D tSpecular;",
  15816. "uniform sampler2D tAO;",
  15817. "uniform samplerCube tCube;",
  15818. "uniform vec2 uNormalScale;",
  15819. "uniform bool useRefract;",
  15820. "uniform float uRefractionRatio;",
  15821. "uniform float uReflectivity;",
  15822. "varying vec3 vTangent;",
  15823. "varying vec3 vBinormal;",
  15824. "varying vec3 vNormal;",
  15825. "varying vec2 vUv;",
  15826. "uniform vec3 ambientLightColor;",
  15827. "#if MAX_DIR_LIGHTS > 0",
  15828. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  15829. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  15830. "#endif",
  15831. "#if MAX_HEMI_LIGHTS > 0",
  15832. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  15833. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  15834. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  15835. "#endif",
  15836. "#if MAX_POINT_LIGHTS > 0",
  15837. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  15838. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  15839. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  15840. "#endif",
  15841. "#if MAX_SPOT_LIGHTS > 0",
  15842. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  15843. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  15844. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  15845. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  15846. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  15847. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  15848. "#endif",
  15849. "#ifdef WRAP_AROUND",
  15850. "uniform vec3 wrapRGB;",
  15851. "#endif",
  15852. "varying vec3 vWorldPosition;",
  15853. "varying vec3 vViewPosition;",
  15854. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  15855. THREE.ShaderChunk[ "fog_pars_fragment" ],
  15856. "void main() {",
  15857. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  15858. "vec3 specularTex = vec3( 1.0 );",
  15859. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  15860. "normalTex.xy *= uNormalScale;",
  15861. "normalTex = normalize( normalTex );",
  15862. "if( enableDiffuse ) {",
  15863. "#ifdef GAMMA_INPUT",
  15864. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  15865. "texelColor.xyz *= texelColor.xyz;",
  15866. "gl_FragColor = gl_FragColor * texelColor;",
  15867. "#else",
  15868. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  15869. "#endif",
  15870. "}",
  15871. "if( enableAO ) {",
  15872. "#ifdef GAMMA_INPUT",
  15873. "vec4 aoColor = texture2D( tAO, vUv );",
  15874. "aoColor.xyz *= aoColor.xyz;",
  15875. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  15876. "#else",
  15877. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  15878. "#endif",
  15879. "}",
  15880. "if( enableSpecular )",
  15881. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  15882. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  15883. "vec3 finalNormal = tsb * normalTex;",
  15884. "#ifdef FLIP_SIDED",
  15885. "finalNormal = -finalNormal;",
  15886. "#endif",
  15887. "vec3 normal = normalize( finalNormal );",
  15888. "vec3 viewPosition = normalize( vViewPosition );",
  15889. // point lights
  15890. "#if MAX_POINT_LIGHTS > 0",
  15891. "vec3 pointDiffuse = vec3( 0.0 );",
  15892. "vec3 pointSpecular = vec3( 0.0 );",
  15893. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  15894. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  15895. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  15896. "float pointDistance = 1.0;",
  15897. "if ( pointLightDistance[ i ] > 0.0 )",
  15898. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  15899. "pointVector = normalize( pointVector );",
  15900. // diffuse
  15901. "#ifdef WRAP_AROUND",
  15902. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  15903. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  15904. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  15905. "#else",
  15906. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  15907. "#endif",
  15908. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  15909. // specular
  15910. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  15911. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  15912. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  15913. "#ifdef PHYSICALLY_BASED_SHADING",
  15914. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15915. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15916. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  15917. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  15918. "#else",
  15919. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  15920. "#endif",
  15921. "}",
  15922. "#endif",
  15923. // spot lights
  15924. "#if MAX_SPOT_LIGHTS > 0",
  15925. "vec3 spotDiffuse = vec3( 0.0 );",
  15926. "vec3 spotSpecular = vec3( 0.0 );",
  15927. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  15928. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  15929. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  15930. "float spotDistance = 1.0;",
  15931. "if ( spotLightDistance[ i ] > 0.0 )",
  15932. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  15933. "spotVector = normalize( spotVector );",
  15934. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  15935. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  15936. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  15937. // diffuse
  15938. "#ifdef WRAP_AROUND",
  15939. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  15940. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  15941. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  15942. "#else",
  15943. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  15944. "#endif",
  15945. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  15946. // specular
  15947. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  15948. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  15949. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  15950. "#ifdef PHYSICALLY_BASED_SHADING",
  15951. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15952. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15953. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  15954. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  15955. "#else",
  15956. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  15957. "#endif",
  15958. "}",
  15959. "}",
  15960. "#endif",
  15961. // directional lights
  15962. "#if MAX_DIR_LIGHTS > 0",
  15963. "vec3 dirDiffuse = vec3( 0.0 );",
  15964. "vec3 dirSpecular = vec3( 0.0 );",
  15965. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  15966. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  15967. "vec3 dirVector = normalize( lDirection.xyz );",
  15968. // diffuse
  15969. "#ifdef WRAP_AROUND",
  15970. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  15971. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  15972. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  15973. "#else",
  15974. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  15975. "#endif",
  15976. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  15977. // specular
  15978. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  15979. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  15980. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  15981. "#ifdef PHYSICALLY_BASED_SHADING",
  15982. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15983. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15984. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  15985. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  15986. "#else",
  15987. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  15988. "#endif",
  15989. "}",
  15990. "#endif",
  15991. // hemisphere lights
  15992. "#if MAX_HEMI_LIGHTS > 0",
  15993. "vec3 hemiDiffuse = vec3( 0.0 );",
  15994. "vec3 hemiSpecular = vec3( 0.0 );" ,
  15995. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  15996. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  15997. "vec3 lVector = normalize( lDirection.xyz );",
  15998. // diffuse
  15999. "float dotProduct = dot( normal, lVector );",
  16000. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  16001. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  16002. "hemiDiffuse += uDiffuseColor * hemiColor;",
  16003. // specular (sky light)
  16004. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  16005. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  16006. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  16007. // specular (ground light)
  16008. "vec3 lVectorGround = -lVector;",
  16009. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  16010. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  16011. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  16012. "#ifdef PHYSICALLY_BASED_SHADING",
  16013. "float dotProductGround = dot( normal, lVectorGround );",
  16014. // 2.0 => 2.0001 is hack to work around ANGLE bug
  16015. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  16016. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  16017. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  16018. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  16019. "#else",
  16020. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  16021. "#endif",
  16022. "}",
  16023. "#endif",
  16024. // all lights contribution summation
  16025. "vec3 totalDiffuse = vec3( 0.0 );",
  16026. "vec3 totalSpecular = vec3( 0.0 );",
  16027. "#if MAX_DIR_LIGHTS > 0",
  16028. "totalDiffuse += dirDiffuse;",
  16029. "totalSpecular += dirSpecular;",
  16030. "#endif",
  16031. "#if MAX_HEMI_LIGHTS > 0",
  16032. "totalDiffuse += hemiDiffuse;",
  16033. "totalSpecular += hemiSpecular;",
  16034. "#endif",
  16035. "#if MAX_POINT_LIGHTS > 0",
  16036. "totalDiffuse += pointDiffuse;",
  16037. "totalSpecular += pointSpecular;",
  16038. "#endif",
  16039. "#if MAX_SPOT_LIGHTS > 0",
  16040. "totalDiffuse += spotDiffuse;",
  16041. "totalSpecular += spotSpecular;",
  16042. "#endif",
  16043. "#ifdef METAL",
  16044. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  16045. "#else",
  16046. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  16047. "#endif",
  16048. "if ( enableReflection ) {",
  16049. "vec3 vReflect;",
  16050. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  16051. "if ( useRefract ) {",
  16052. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  16053. "} else {",
  16054. "vReflect = reflect( cameraToVertex, normal );",
  16055. "}",
  16056. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  16057. "#ifdef GAMMA_INPUT",
  16058. "cubeColor.xyz *= cubeColor.xyz;",
  16059. "#endif",
  16060. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  16061. "}",
  16062. THREE.ShaderChunk[ "shadowmap_fragment" ],
  16063. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  16064. THREE.ShaderChunk[ "fog_fragment" ],
  16065. "}"
  16066. ].join("\n"),
  16067. vertexShader: [
  16068. "attribute vec4 tangent;",
  16069. "uniform vec2 uOffset;",
  16070. "uniform vec2 uRepeat;",
  16071. "uniform bool enableDisplacement;",
  16072. "#ifdef VERTEX_TEXTURES",
  16073. "uniform sampler2D tDisplacement;",
  16074. "uniform float uDisplacementScale;",
  16075. "uniform float uDisplacementBias;",
  16076. "#endif",
  16077. "varying vec3 vTangent;",
  16078. "varying vec3 vBinormal;",
  16079. "varying vec3 vNormal;",
  16080. "varying vec2 vUv;",
  16081. "varying vec3 vWorldPosition;",
  16082. "varying vec3 vViewPosition;",
  16083. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  16084. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  16085. "void main() {",
  16086. THREE.ShaderChunk[ "skinbase_vertex" ],
  16087. THREE.ShaderChunk[ "skinnormal_vertex" ],
  16088. // normal, tangent and binormal vectors
  16089. "#ifdef USE_SKINNING",
  16090. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  16091. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  16092. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  16093. "#else",
  16094. "vNormal = normalize( normalMatrix * normal );",
  16095. "vTangent = normalize( normalMatrix * tangent.xyz );",
  16096. "#endif",
  16097. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  16098. "vUv = uv * uRepeat + uOffset;",
  16099. // displacement mapping
  16100. "vec3 displacedPosition;",
  16101. "#ifdef VERTEX_TEXTURES",
  16102. "if ( enableDisplacement ) {",
  16103. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  16104. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  16105. "displacedPosition = position + normalize( normal ) * df;",
  16106. "} else {",
  16107. "#ifdef USE_SKINNING",
  16108. "vec4 skinVertex = vec4( position, 1.0 );",
  16109. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  16110. "skinned += boneMatY * skinVertex * skinWeight.y;",
  16111. "displacedPosition = skinned.xyz;",
  16112. "#else",
  16113. "displacedPosition = position;",
  16114. "#endif",
  16115. "}",
  16116. "#else",
  16117. "#ifdef USE_SKINNING",
  16118. "vec4 skinVertex = vec4( position, 1.0 );",
  16119. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  16120. "skinned += boneMatY * skinVertex * skinWeight.y;",
  16121. "displacedPosition = skinned.xyz;",
  16122. "#else",
  16123. "displacedPosition = position;",
  16124. "#endif",
  16125. "#endif",
  16126. //
  16127. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  16128. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  16129. "gl_Position = projectionMatrix * mvPosition;",
  16130. //
  16131. "vWorldPosition = worldPosition.xyz;",
  16132. "vViewPosition = -mvPosition.xyz;",
  16133. // shadows
  16134. "#ifdef USE_SHADOWMAP",
  16135. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  16136. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  16137. "}",
  16138. "#endif",
  16139. "}"
  16140. ].join("\n")
  16141. },
  16142. /* -------------------------------------------------------------------------
  16143. // Cube map shader
  16144. ------------------------------------------------------------------------- */
  16145. 'cube': {
  16146. uniforms: { "tCube": { type: "t", value: null },
  16147. "tFlip": { type: "f", value: -1 } },
  16148. vertexShader: [
  16149. "varying vec3 vWorldPosition;",
  16150. "void main() {",
  16151. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  16152. "vWorldPosition = worldPosition.xyz;",
  16153. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  16154. "}"
  16155. ].join("\n"),
  16156. fragmentShader: [
  16157. "uniform samplerCube tCube;",
  16158. "uniform float tFlip;",
  16159. "varying vec3 vWorldPosition;",
  16160. "void main() {",
  16161. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  16162. "}"
  16163. ].join("\n")
  16164. }
  16165. }
  16166. };
  16167. /**
  16168. * @author zz85 / http://www.lab4games.net/zz85/blog
  16169. * @author alteredq / http://alteredqualia.com/
  16170. *
  16171. * For Text operations in three.js (See TextGeometry)
  16172. *
  16173. * It uses techniques used in:
  16174. *
  16175. * typeface.js and canvastext
  16176. * For converting fonts and rendering with javascript
  16177. * http://typeface.neocracy.org
  16178. *
  16179. * Triangulation ported from AS3
  16180. * Simple Polygon Triangulation
  16181. * http://actionsnippet.com/?p=1462
  16182. *
  16183. * A Method to triangulate shapes with holes
  16184. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16185. *
  16186. */
  16187. THREE.FontUtils = {
  16188. faces : {},
  16189. // Just for now. face[weight][style]
  16190. face : "helvetiker",
  16191. weight: "normal",
  16192. style : "normal",
  16193. size : 150,
  16194. divisions : 10,
  16195. getFace : function() {
  16196. return this.faces[ this.face ][ this.weight ][ this.style ];
  16197. },
  16198. loadFace : function( data ) {
  16199. var family = data.familyName.toLowerCase();
  16200. var ThreeFont = this;
  16201. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16202. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16203. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16204. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16205. return data;
  16206. },
  16207. drawText : function( text ) {
  16208. var characterPts = [], allPts = [];
  16209. // RenderText
  16210. var i, p,
  16211. face = this.getFace(),
  16212. scale = this.size / face.resolution,
  16213. offset = 0,
  16214. chars = String( text ).split( '' ),
  16215. length = chars.length;
  16216. var fontPaths = [];
  16217. for ( i = 0; i < length; i ++ ) {
  16218. var path = new THREE.Path();
  16219. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16220. offset += ret.offset;
  16221. fontPaths.push( ret.path );
  16222. }
  16223. // get the width
  16224. var width = offset / 2;
  16225. //
  16226. // for ( p = 0; p < allPts.length; p++ ) {
  16227. //
  16228. // allPts[ p ].x -= width;
  16229. //
  16230. // }
  16231. //var extract = this.extractPoints( allPts, characterPts );
  16232. //extract.contour = allPts;
  16233. //extract.paths = fontPaths;
  16234. //extract.offset = width;
  16235. return { paths : fontPaths, offset : width };
  16236. },
  16237. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16238. var pts = [];
  16239. var i, i2, divisions,
  16240. outline, action, length,
  16241. scaleX, scaleY,
  16242. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16243. laste,
  16244. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16245. if ( !glyph ) return;
  16246. if ( glyph.o ) {
  16247. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16248. length = outline.length;
  16249. scaleX = scale;
  16250. scaleY = scale;
  16251. for ( i = 0; i < length; ) {
  16252. action = outline[ i ++ ];
  16253. //console.log( action );
  16254. switch( action ) {
  16255. case 'm':
  16256. // Move To
  16257. x = outline[ i++ ] * scaleX + offset;
  16258. y = outline[ i++ ] * scaleY;
  16259. path.moveTo( x, y );
  16260. break;
  16261. case 'l':
  16262. // Line To
  16263. x = outline[ i++ ] * scaleX + offset;
  16264. y = outline[ i++ ] * scaleY;
  16265. path.lineTo(x,y);
  16266. break;
  16267. case 'q':
  16268. // QuadraticCurveTo
  16269. cpx = outline[ i++ ] * scaleX + offset;
  16270. cpy = outline[ i++ ] * scaleY;
  16271. cpx1 = outline[ i++ ] * scaleX + offset;
  16272. cpy1 = outline[ i++ ] * scaleY;
  16273. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16274. laste = pts[ pts.length - 1 ];
  16275. if ( laste ) {
  16276. cpx0 = laste.x;
  16277. cpy0 = laste.y;
  16278. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16279. var t = i2 / divisions;
  16280. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16281. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16282. }
  16283. }
  16284. break;
  16285. case 'b':
  16286. // Cubic Bezier Curve
  16287. cpx = outline[ i++ ] * scaleX + offset;
  16288. cpy = outline[ i++ ] * scaleY;
  16289. cpx1 = outline[ i++ ] * scaleX + offset;
  16290. cpy1 = outline[ i++ ] * -scaleY;
  16291. cpx2 = outline[ i++ ] * scaleX + offset;
  16292. cpy2 = outline[ i++ ] * -scaleY;
  16293. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16294. laste = pts[ pts.length - 1 ];
  16295. if ( laste ) {
  16296. cpx0 = laste.x;
  16297. cpy0 = laste.y;
  16298. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16299. var t = i2 / divisions;
  16300. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16301. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16302. }
  16303. }
  16304. break;
  16305. }
  16306. }
  16307. }
  16308. return { offset: glyph.ha*scale, path:path};
  16309. }
  16310. };
  16311. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16312. // Parameters
  16313. parameters = parameters || {};
  16314. var size = parameters.size !== undefined ? parameters.size : 100;
  16315. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16316. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16317. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16318. var style = parameters.style !== undefined ? parameters.style : "normal";
  16319. THREE.FontUtils.size = size;
  16320. THREE.FontUtils.divisions = curveSegments;
  16321. THREE.FontUtils.face = font;
  16322. THREE.FontUtils.weight = weight;
  16323. THREE.FontUtils.style = style;
  16324. // Get a Font data json object
  16325. var data = THREE.FontUtils.drawText( text );
  16326. var paths = data.paths;
  16327. var shapes = [];
  16328. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16329. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16330. }
  16331. return shapes;
  16332. };
  16333. /**
  16334. * This code is a quick port of code written in C++ which was submitted to
  16335. * flipcode.com by John W. Ratcliff // July 22, 2000
  16336. * See original code and more information here:
  16337. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16338. *
  16339. * ported to actionscript by Zevan Rosser
  16340. * www.actionsnippet.com
  16341. *
  16342. * ported to javascript by Joshua Koo
  16343. * http://www.lab4games.net/zz85/blog
  16344. *
  16345. */
  16346. ( function( namespace ) {
  16347. var EPSILON = 0.0000000001;
  16348. // takes in an contour array and returns
  16349. var process = function( contour, indices ) {
  16350. var n = contour.length;
  16351. if ( n < 3 ) return null;
  16352. var result = [],
  16353. verts = [],
  16354. vertIndices = [];
  16355. /* we want a counter-clockwise polygon in verts */
  16356. var u, v, w;
  16357. if ( area( contour ) > 0.0 ) {
  16358. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16359. } else {
  16360. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16361. }
  16362. var nv = n;
  16363. /* remove nv - 2 vertices, creating 1 triangle every time */
  16364. var count = 2 * nv; /* error detection */
  16365. for( v = nv - 1; nv > 2; ) {
  16366. /* if we loop, it is probably a non-simple polygon */
  16367. if ( ( count-- ) <= 0 ) {
  16368. //** Triangulate: ERROR - probable bad polygon!
  16369. //throw ( "Warning, unable to triangulate polygon!" );
  16370. //return null;
  16371. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16372. console.log( "Warning, unable to triangulate polygon!" );
  16373. if ( indices ) return vertIndices;
  16374. return result;
  16375. }
  16376. /* three consecutive vertices in current polygon, <u,v,w> */
  16377. u = v; if ( nv <= u ) u = 0; /* previous */
  16378. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16379. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16380. if ( snip( contour, u, v, w, nv, verts ) ) {
  16381. var a, b, c, s, t;
  16382. /* true names of the vertices */
  16383. a = verts[ u ];
  16384. b = verts[ v ];
  16385. c = verts[ w ];
  16386. /* output Triangle */
  16387. result.push( [ contour[ a ],
  16388. contour[ b ],
  16389. contour[ c ] ] );
  16390. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16391. /* remove v from the remaining polygon */
  16392. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16393. verts[ s ] = verts[ t ];
  16394. }
  16395. nv--;
  16396. /* reset error detection counter */
  16397. count = 2 * nv;
  16398. }
  16399. }
  16400. if ( indices ) return vertIndices;
  16401. return result;
  16402. };
  16403. // calculate area of the contour polygon
  16404. var area = function ( contour ) {
  16405. var n = contour.length;
  16406. var a = 0.0;
  16407. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16408. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16409. }
  16410. return a * 0.5;
  16411. };
  16412. var snip = function ( contour, u, v, w, n, verts ) {
  16413. var p;
  16414. var ax, ay, bx, by;
  16415. var cx, cy, px, py;
  16416. ax = contour[ verts[ u ] ].x;
  16417. ay = contour[ verts[ u ] ].y;
  16418. bx = contour[ verts[ v ] ].x;
  16419. by = contour[ verts[ v ] ].y;
  16420. cx = contour[ verts[ w ] ].x;
  16421. cy = contour[ verts[ w ] ].y;
  16422. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16423. var aX, aY, bX, bY, cX, cY;
  16424. var apx, apy, bpx, bpy, cpx, cpy;
  16425. var cCROSSap, bCROSScp, aCROSSbp;
  16426. aX = cx - bx; aY = cy - by;
  16427. bX = ax - cx; bY = ay - cy;
  16428. cX = bx - ax; cY = by - ay;
  16429. for ( p = 0; p < n; p++ ) {
  16430. if( (p === u) || (p === v) || (p === w) ) continue;
  16431. px = contour[ verts[ p ] ].x
  16432. py = contour[ verts[ p ] ].y
  16433. apx = px - ax; apy = py - ay;
  16434. bpx = px - bx; bpy = py - by;
  16435. cpx = px - cx; cpy = py - cy;
  16436. // see if p is inside triangle abc
  16437. aCROSSbp = aX*bpy - aY*bpx;
  16438. cCROSSap = cX*apy - cY*apx;
  16439. bCROSScp = bX*cpy - bY*cpx;
  16440. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16441. }
  16442. return true;
  16443. };
  16444. namespace.Triangulate = process;
  16445. namespace.Triangulate.area = area;
  16446. return namespace;
  16447. })(THREE.FontUtils);
  16448. // To use the typeface.js face files, hook up the API
  16449. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  16450. * @author zz85 / http://www.lab4games.net/zz85/blog
  16451. * Extensible curve object
  16452. *
  16453. * Some common of Curve methods
  16454. * .getPoint(t), getTangent(t)
  16455. * .getPointAt(u), getTagentAt(u)
  16456. * .getPoints(), .getSpacedPoints()
  16457. * .getLength()
  16458. * .updateArcLengths()
  16459. *
  16460. * This file contains following classes:
  16461. *
  16462. * -- 2d classes --
  16463. * THREE.Curve
  16464. * THREE.LineCurve
  16465. * THREE.QuadraticBezierCurve
  16466. * THREE.CubicBezierCurve
  16467. * THREE.SplineCurve
  16468. * THREE.ArcCurve
  16469. * THREE.EllipseCurve
  16470. *
  16471. * -- 3d classes --
  16472. * THREE.LineCurve3
  16473. * THREE.QuadraticBezierCurve3
  16474. * THREE.CubicBezierCurve3
  16475. * THREE.SplineCurve3
  16476. * THREE.ClosedSplineCurve3
  16477. *
  16478. * A series of curves can be represented as a THREE.CurvePath
  16479. *
  16480. **/
  16481. /**************************************************************
  16482. * Abstract Curve base class
  16483. **************************************************************/
  16484. THREE.Curve = function () {
  16485. };
  16486. // Virtual base class method to overwrite and implement in subclasses
  16487. // - t [0 .. 1]
  16488. THREE.Curve.prototype.getPoint = function ( t ) {
  16489. console.log( "Warning, getPoint() not implemented!" );
  16490. return null;
  16491. };
  16492. // Get point at relative position in curve according to arc length
  16493. // - u [0 .. 1]
  16494. THREE.Curve.prototype.getPointAt = function ( u ) {
  16495. var t = this.getUtoTmapping( u );
  16496. return this.getPoint( t );
  16497. };
  16498. // Get sequence of points using getPoint( t )
  16499. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16500. if ( !divisions ) divisions = 5;
  16501. var d, pts = [];
  16502. for ( d = 0; d <= divisions; d ++ ) {
  16503. pts.push( this.getPoint( d / divisions ) );
  16504. }
  16505. return pts;
  16506. };
  16507. // Get sequence of points using getPointAt( u )
  16508. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16509. if ( !divisions ) divisions = 5;
  16510. var d, pts = [];
  16511. for ( d = 0; d <= divisions; d ++ ) {
  16512. pts.push( this.getPointAt( d / divisions ) );
  16513. }
  16514. return pts;
  16515. };
  16516. // Get total curve arc length
  16517. THREE.Curve.prototype.getLength = function () {
  16518. var lengths = this.getLengths();
  16519. return lengths[ lengths.length - 1 ];
  16520. };
  16521. // Get list of cumulative segment lengths
  16522. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16523. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16524. if ( this.cacheArcLengths
  16525. && ( this.cacheArcLengths.length == divisions + 1 )
  16526. && !this.needsUpdate) {
  16527. //console.log( "cached", this.cacheArcLengths );
  16528. return this.cacheArcLengths;
  16529. }
  16530. this.needsUpdate = false;
  16531. var cache = [];
  16532. var current, last = this.getPoint( 0 );
  16533. var p, sum = 0;
  16534. cache.push( 0 );
  16535. for ( p = 1; p <= divisions; p ++ ) {
  16536. current = this.getPoint ( p / divisions );
  16537. sum += current.distanceTo( last );
  16538. cache.push( sum );
  16539. last = current;
  16540. }
  16541. this.cacheArcLengths = cache;
  16542. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16543. };
  16544. THREE.Curve.prototype.updateArcLengths = function() {
  16545. this.needsUpdate = true;
  16546. this.getLengths();
  16547. };
  16548. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16549. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16550. var arcLengths = this.getLengths();
  16551. var i = 0, il = arcLengths.length;
  16552. var targetArcLength; // The targeted u distance value to get
  16553. if ( distance ) {
  16554. targetArcLength = distance;
  16555. } else {
  16556. targetArcLength = u * arcLengths[ il - 1 ];
  16557. }
  16558. //var time = Date.now();
  16559. // binary search for the index with largest value smaller than target u distance
  16560. var low = 0, high = il - 1, comparison;
  16561. while ( low <= high ) {
  16562. 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
  16563. comparison = arcLengths[ i ] - targetArcLength;
  16564. if ( comparison < 0 ) {
  16565. low = i + 1;
  16566. continue;
  16567. } else if ( comparison > 0 ) {
  16568. high = i - 1;
  16569. continue;
  16570. } else {
  16571. high = i;
  16572. break;
  16573. // DONE
  16574. }
  16575. }
  16576. i = high;
  16577. //console.log('b' , i, low, high, Date.now()- time);
  16578. if ( arcLengths[ i ] == targetArcLength ) {
  16579. var t = i / ( il - 1 );
  16580. return t;
  16581. }
  16582. // we could get finer grain at lengths, or use simple interpolatation between two points
  16583. var lengthBefore = arcLengths[ i ];
  16584. var lengthAfter = arcLengths[ i + 1 ];
  16585. var segmentLength = lengthAfter - lengthBefore;
  16586. // determine where we are between the 'before' and 'after' points
  16587. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16588. // add that fractional amount to t
  16589. var t = ( i + segmentFraction ) / ( il -1 );
  16590. return t;
  16591. };
  16592. // Returns a unit vector tangent at t
  16593. // In case any sub curve does not implement its tangent derivation,
  16594. // 2 points a small delta apart will be used to find its gradient
  16595. // which seems to give a reasonable approximation
  16596. THREE.Curve.prototype.getTangent = function( t ) {
  16597. var delta = 0.0001;
  16598. var t1 = t - delta;
  16599. var t2 = t + delta;
  16600. // Capping in case of danger
  16601. if ( t1 < 0 ) t1 = 0;
  16602. if ( t2 > 1 ) t2 = 1;
  16603. var pt1 = this.getPoint( t1 );
  16604. var pt2 = this.getPoint( t2 );
  16605. var vec = pt2.clone().subSelf(pt1);
  16606. return vec.normalize();
  16607. };
  16608. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16609. var t = this.getUtoTmapping( u );
  16610. return this.getTangent( t );
  16611. };
  16612. /**************************************************************
  16613. * Line
  16614. **************************************************************/
  16615. THREE.LineCurve = function ( v1, v2 ) {
  16616. this.v1 = v1;
  16617. this.v2 = v2;
  16618. };
  16619. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16620. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16621. var point = this.v2.clone().subSelf(this.v1);
  16622. point.multiplyScalar( t ).addSelf( this.v1 );
  16623. return point;
  16624. };
  16625. // Line curve is linear, so we can overwrite default getPointAt
  16626. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16627. return this.getPoint( u );
  16628. };
  16629. THREE.LineCurve.prototype.getTangent = function( t ) {
  16630. var tangent = this.v2.clone().subSelf(this.v1);
  16631. return tangent.normalize();
  16632. };
  16633. /**************************************************************
  16634. * Quadratic Bezier curve
  16635. **************************************************************/
  16636. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16637. this.v0 = v0;
  16638. this.v1 = v1;
  16639. this.v2 = v2;
  16640. };
  16641. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16642. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16643. var tx, ty;
  16644. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16645. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16646. return new THREE.Vector2( tx, ty );
  16647. };
  16648. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16649. var tx, ty;
  16650. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16651. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16652. // returns unit vector
  16653. var tangent = new THREE.Vector2( tx, ty );
  16654. tangent.normalize();
  16655. return tangent;
  16656. };
  16657. /**************************************************************
  16658. * Cubic Bezier curve
  16659. **************************************************************/
  16660. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16661. this.v0 = v0;
  16662. this.v1 = v1;
  16663. this.v2 = v2;
  16664. this.v3 = v3;
  16665. };
  16666. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16667. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16668. var tx, ty;
  16669. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16670. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16671. return new THREE.Vector2( tx, ty );
  16672. };
  16673. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16674. var tx, ty;
  16675. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16676. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16677. var tangent = new THREE.Vector2( tx, ty );
  16678. tangent.normalize();
  16679. return tangent;
  16680. };
  16681. /**************************************************************
  16682. * Spline curve
  16683. **************************************************************/
  16684. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16685. this.points = (points == undefined) ? [] : points;
  16686. };
  16687. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16688. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16689. var v = new THREE.Vector2();
  16690. var c = [];
  16691. var points = this.points, point, intPoint, weight;
  16692. point = ( points.length - 1 ) * t;
  16693. intPoint = Math.floor( point );
  16694. weight = point - intPoint;
  16695. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16696. c[ 1 ] = intPoint;
  16697. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16698. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16699. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16700. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16701. return v;
  16702. };
  16703. /**************************************************************
  16704. * Ellipse curve
  16705. **************************************************************/
  16706. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16707. aStartAngle, aEndAngle,
  16708. aClockwise ) {
  16709. this.aX = aX;
  16710. this.aY = aY;
  16711. this.xRadius = xRadius;
  16712. this.yRadius = yRadius;
  16713. this.aStartAngle = aStartAngle;
  16714. this.aEndAngle = aEndAngle;
  16715. this.aClockwise = aClockwise;
  16716. };
  16717. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16718. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16719. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16720. if ( !this.aClockwise ) {
  16721. t = 1 - t;
  16722. }
  16723. var angle = this.aStartAngle + t * deltaAngle;
  16724. var tx = this.aX + this.xRadius * Math.cos( angle );
  16725. var ty = this.aY + this.yRadius * Math.sin( angle );
  16726. return new THREE.Vector2( tx, ty );
  16727. };
  16728. /**************************************************************
  16729. * Arc curve
  16730. **************************************************************/
  16731. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16732. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16733. };
  16734. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16735. /**************************************************************
  16736. * Utils
  16737. **************************************************************/
  16738. THREE.Curve.Utils = {
  16739. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16740. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16741. },
  16742. // Puay Bing, thanks for helping with this derivative!
  16743. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16744. return -3 * p0 * (1 - t) * (1 - t) +
  16745. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16746. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16747. 3 * t * t * p3;
  16748. },
  16749. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16750. // To check if my formulas are correct
  16751. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16752. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16753. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16754. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16755. return h00 + h10 + h01 + h11;
  16756. },
  16757. // Catmull-Rom
  16758. interpolate: function( p0, p1, p2, p3, t ) {
  16759. var v0 = ( p2 - p0 ) * 0.5;
  16760. var v1 = ( p3 - p1 ) * 0.5;
  16761. var t2 = t * t;
  16762. var t3 = t * t2;
  16763. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16764. }
  16765. };
  16766. // TODO: Transformation for Curves?
  16767. /**************************************************************
  16768. * 3D Curves
  16769. **************************************************************/
  16770. // A Factory method for creating new curve subclasses
  16771. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16772. constructor.prototype = Object.create( THREE.Curve.prototype );
  16773. constructor.prototype.getPoint = getPointFunc;
  16774. return constructor;
  16775. };
  16776. /**************************************************************
  16777. * Line3D
  16778. **************************************************************/
  16779. THREE.LineCurve3 = THREE.Curve.create(
  16780. function ( v1, v2 ) {
  16781. this.v1 = v1;
  16782. this.v2 = v2;
  16783. },
  16784. function ( t ) {
  16785. var r = new THREE.Vector3();
  16786. r.sub( this.v2, this.v1 ); // diff
  16787. r.multiplyScalar( t );
  16788. r.addSelf( this.v1 );
  16789. return r;
  16790. }
  16791. );
  16792. /**************************************************************
  16793. * Quadratic Bezier 3D curve
  16794. **************************************************************/
  16795. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  16796. function ( v0, v1, v2 ) {
  16797. this.v0 = v0;
  16798. this.v1 = v1;
  16799. this.v2 = v2;
  16800. },
  16801. function ( t ) {
  16802. var tx, ty, tz;
  16803. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16804. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16805. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16806. return new THREE.Vector3( tx, ty, tz );
  16807. }
  16808. );
  16809. /**************************************************************
  16810. * Cubic Bezier 3D curve
  16811. **************************************************************/
  16812. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16813. function ( v0, v1, v2, v3 ) {
  16814. this.v0 = v0;
  16815. this.v1 = v1;
  16816. this.v2 = v2;
  16817. this.v3 = v3;
  16818. },
  16819. function ( t ) {
  16820. var tx, ty, tz;
  16821. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16822. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16823. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16824. return new THREE.Vector3( tx, ty, tz );
  16825. }
  16826. );
  16827. /**************************************************************
  16828. * Spline 3D curve
  16829. **************************************************************/
  16830. THREE.SplineCurve3 = THREE.Curve.create(
  16831. function ( points /* array of Vector3 */) {
  16832. this.points = (points == undefined) ? [] : points;
  16833. },
  16834. function ( t ) {
  16835. var v = new THREE.Vector3();
  16836. var c = [];
  16837. var points = this.points, point, intPoint, weight;
  16838. point = ( points.length - 1 ) * t;
  16839. intPoint = Math.floor( point );
  16840. weight = point - intPoint;
  16841. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16842. c[ 1 ] = intPoint;
  16843. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16844. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16845. var pt0 = points[ c[0] ],
  16846. pt1 = points[ c[1] ],
  16847. pt2 = points[ c[2] ],
  16848. pt3 = points[ c[3] ];
  16849. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16850. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16851. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16852. return v;
  16853. }
  16854. );
  16855. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16856. // var v = new THREE.Vector3();
  16857. // var c = [];
  16858. // var points = this.points, point, intPoint, weight;
  16859. // point = ( points.length - 1 ) * t;
  16860. // intPoint = Math.floor( point );
  16861. // weight = point - intPoint;
  16862. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16863. // c[ 1 ] = intPoint;
  16864. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16865. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16866. // var pt0 = points[ c[0] ],
  16867. // pt1 = points[ c[1] ],
  16868. // pt2 = points[ c[2] ],
  16869. // pt3 = points[ c[3] ];
  16870. // // t = weight;
  16871. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16872. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16873. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16874. // return v;
  16875. // }
  16876. /**************************************************************
  16877. * Closed Spline 3D curve
  16878. **************************************************************/
  16879. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16880. function ( points /* array of Vector3 */) {
  16881. this.points = (points == undefined) ? [] : points;
  16882. },
  16883. function ( t ) {
  16884. var v = new THREE.Vector3();
  16885. var c = [];
  16886. var points = this.points, point, intPoint, weight;
  16887. point = ( points.length - 0 ) * t;
  16888. // This needs to be from 0-length +1
  16889. intPoint = Math.floor( point );
  16890. weight = point - intPoint;
  16891. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16892. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16893. c[ 1 ] = ( intPoint ) % points.length;
  16894. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16895. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16896. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16897. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16898. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16899. return v;
  16900. }
  16901. );
  16902. /**
  16903. * @author zz85 / http://www.lab4games.net/zz85/blog
  16904. *
  16905. **/
  16906. /**************************************************************
  16907. * Curved Path - a curve path is simply a array of connected
  16908. * curves, but retains the api of a curve
  16909. **************************************************************/
  16910. THREE.CurvePath = function () {
  16911. this.curves = [];
  16912. this.bends = [];
  16913. this.autoClose = false; // Automatically closes the path
  16914. };
  16915. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16916. THREE.CurvePath.prototype.add = function ( curve ) {
  16917. this.curves.push( curve );
  16918. };
  16919. THREE.CurvePath.prototype.checkConnection = function() {
  16920. // TODO
  16921. // If the ending of curve is not connected to the starting
  16922. // or the next curve, then, this is not a real path
  16923. };
  16924. THREE.CurvePath.prototype.closePath = function() {
  16925. // TODO Test
  16926. // and verify for vector3 (needs to implement equals)
  16927. // Add a line curve if start and end of lines are not connected
  16928. var startPoint = this.curves[0].getPoint(0);
  16929. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16930. if (!startPoint.equals(endPoint)) {
  16931. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16932. }
  16933. };
  16934. // To get accurate point with reference to
  16935. // entire path distance at time t,
  16936. // following has to be done:
  16937. // 1. Length of each sub path have to be known
  16938. // 2. Locate and identify type of curve
  16939. // 3. Get t for the curve
  16940. // 4. Return curve.getPointAt(t')
  16941. THREE.CurvePath.prototype.getPoint = function( t ) {
  16942. var d = t * this.getLength();
  16943. var curveLengths = this.getCurveLengths();
  16944. var i = 0, diff, curve;
  16945. // To think about boundaries points.
  16946. while ( i < curveLengths.length ) {
  16947. if ( curveLengths[ i ] >= d ) {
  16948. diff = curveLengths[ i ] - d;
  16949. curve = this.curves[ i ];
  16950. var u = 1 - diff / curve.getLength();
  16951. return curve.getPointAt( u );
  16952. break;
  16953. }
  16954. i ++;
  16955. }
  16956. return null;
  16957. // loop where sum != 0, sum > d , sum+1 <d
  16958. };
  16959. /*
  16960. THREE.CurvePath.prototype.getTangent = function( t ) {
  16961. };*/
  16962. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16963. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16964. // getPoint() depends on getLength
  16965. THREE.CurvePath.prototype.getLength = function() {
  16966. var lens = this.getCurveLengths();
  16967. return lens[ lens.length - 1 ];
  16968. };
  16969. // Compute lengths and cache them
  16970. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16971. THREE.CurvePath.prototype.getCurveLengths = function() {
  16972. // We use cache values if curves and cache array are same length
  16973. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16974. return this.cacheLengths;
  16975. };
  16976. // Get length of subsurve
  16977. // Push sums into cached array
  16978. var lengths = [], sums = 0;
  16979. var i, il = this.curves.length;
  16980. for ( i = 0; i < il; i ++ ) {
  16981. sums += this.curves[ i ].getLength();
  16982. lengths.push( sums );
  16983. }
  16984. this.cacheLengths = lengths;
  16985. return lengths;
  16986. };
  16987. // Returns min and max coordinates, as well as centroid
  16988. THREE.CurvePath.prototype.getBoundingBox = function () {
  16989. var points = this.getPoints();
  16990. var maxX, maxY, maxZ;
  16991. var minX, minY, minZ;
  16992. maxX = maxY = Number.NEGATIVE_INFINITY;
  16993. minX = minY = Number.POSITIVE_INFINITY;
  16994. var p, i, il, sum;
  16995. var v3 = points[0] instanceof THREE.Vector3;
  16996. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16997. for ( i = 0, il = points.length; i < il; i ++ ) {
  16998. p = points[ i ];
  16999. if ( p.x > maxX ) maxX = p.x;
  17000. else if ( p.x < minX ) minX = p.x;
  17001. if ( p.y > maxY ) maxY = p.y;
  17002. else if ( p.y < minY ) minY = p.y;
  17003. if (v3) {
  17004. if ( p.z > maxZ ) maxZ = p.z;
  17005. else if ( p.z < minZ ) minZ = p.z;
  17006. }
  17007. sum.addSelf( p );
  17008. }
  17009. var ret = {
  17010. minX: minX,
  17011. minY: minY,
  17012. maxX: maxX,
  17013. maxY: maxY,
  17014. centroid: sum.divideScalar( il )
  17015. };
  17016. if (v3) {
  17017. ret.maxZ = maxZ;
  17018. ret.minZ = minZ;
  17019. }
  17020. return ret;
  17021. };
  17022. /**************************************************************
  17023. * Create Geometries Helpers
  17024. **************************************************************/
  17025. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17026. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17027. var pts = this.getPoints( divisions, true );
  17028. return this.createGeometry( pts );
  17029. };
  17030. // Generate geometry from equidistance sampling along the path
  17031. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17032. var pts = this.getSpacedPoints( divisions, true );
  17033. return this.createGeometry( pts );
  17034. };
  17035. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17036. var geometry = new THREE.Geometry();
  17037. for ( var i = 0; i < points.length; i ++ ) {
  17038. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17039. }
  17040. return geometry;
  17041. };
  17042. /**************************************************************
  17043. * Bend / Wrap Helper Methods
  17044. **************************************************************/
  17045. // Wrap path / Bend modifiers?
  17046. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17047. this.bends.push( bendpath );
  17048. };
  17049. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17050. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17051. var i, il;
  17052. if ( !bends ) {
  17053. bends = this.bends;
  17054. }
  17055. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17056. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17057. }
  17058. return oldPts;
  17059. };
  17060. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17061. var oldPts = this.getSpacedPoints( segments );
  17062. var i, il;
  17063. if ( !bends ) {
  17064. bends = this.bends;
  17065. }
  17066. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17067. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17068. }
  17069. return oldPts;
  17070. };
  17071. // This returns getPoints() bend/wrapped around the contour of a path.
  17072. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17073. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17074. var bounds = this.getBoundingBox();
  17075. var i, il, p, oldX, oldY, xNorm;
  17076. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17077. p = oldPts[ i ];
  17078. oldX = p.x;
  17079. oldY = p.y;
  17080. xNorm = oldX / bounds.maxX;
  17081. // If using actual distance, for length > path, requires line extrusions
  17082. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17083. xNorm = path.getUtoTmapping( xNorm, oldX );
  17084. // check for out of bounds?
  17085. var pathPt = path.getPoint( xNorm );
  17086. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  17087. p.x = pathPt.x + normal.x;
  17088. p.y = pathPt.y + normal.y;
  17089. }
  17090. return oldPts;
  17091. };
  17092. /**
  17093. * @author alteredq / http://alteredqualia.com/
  17094. */
  17095. THREE.Gyroscope = function () {
  17096. THREE.Object3D.call( this );
  17097. };
  17098. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17099. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17100. this.matrixAutoUpdate && this.updateMatrix();
  17101. // update matrixWorld
  17102. if ( this.matrixWorldNeedsUpdate || force ) {
  17103. if ( this.parent ) {
  17104. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  17105. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  17106. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  17107. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  17108. } else {
  17109. this.matrixWorld.copy( this.matrix );
  17110. }
  17111. this.matrixWorldNeedsUpdate = false;
  17112. force = true;
  17113. }
  17114. // update children
  17115. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17116. this.children[ i ].updateMatrixWorld( force );
  17117. }
  17118. };
  17119. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17120. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17121. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  17122. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  17123. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17124. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17125. /**
  17126. * @author zz85 / http://www.lab4games.net/zz85/blog
  17127. * Creates free form 2d path using series of points, lines or curves.
  17128. *
  17129. **/
  17130. THREE.Path = function ( points ) {
  17131. THREE.CurvePath.call(this);
  17132. this.actions = [];
  17133. if ( points ) {
  17134. this.fromPoints( points );
  17135. }
  17136. };
  17137. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17138. THREE.PathActions = {
  17139. MOVE_TO: 'moveTo',
  17140. LINE_TO: 'lineTo',
  17141. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17142. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17143. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17144. ARC: 'arc', // Circle
  17145. ELLIPSE: 'ellipse'
  17146. };
  17147. // TODO Clean up PATH API
  17148. // Create path using straight lines to connect all points
  17149. // - vectors: array of Vector2
  17150. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17151. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17152. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17153. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17154. };
  17155. };
  17156. // startPath() endPath()?
  17157. THREE.Path.prototype.moveTo = function ( x, y ) {
  17158. var args = Array.prototype.slice.call( arguments );
  17159. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17160. };
  17161. THREE.Path.prototype.lineTo = function ( x, y ) {
  17162. var args = Array.prototype.slice.call( arguments );
  17163. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17164. var x0 = lastargs[ lastargs.length - 2 ];
  17165. var y0 = lastargs[ lastargs.length - 1 ];
  17166. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17167. this.curves.push( curve );
  17168. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17169. };
  17170. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17171. var args = Array.prototype.slice.call( arguments );
  17172. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17173. var x0 = lastargs[ lastargs.length - 2 ];
  17174. var y0 = lastargs[ lastargs.length - 1 ];
  17175. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17176. new THREE.Vector2( aCPx, aCPy ),
  17177. new THREE.Vector2( aX, aY ) );
  17178. this.curves.push( curve );
  17179. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17180. };
  17181. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17182. aCP2x, aCP2y,
  17183. aX, aY ) {
  17184. var args = Array.prototype.slice.call( arguments );
  17185. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17186. var x0 = lastargs[ lastargs.length - 2 ];
  17187. var y0 = lastargs[ lastargs.length - 1 ];
  17188. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17189. new THREE.Vector2( aCP1x, aCP1y ),
  17190. new THREE.Vector2( aCP2x, aCP2y ),
  17191. new THREE.Vector2( aX, aY ) );
  17192. this.curves.push( curve );
  17193. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17194. };
  17195. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17196. var args = Array.prototype.slice.call( arguments );
  17197. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17198. var x0 = lastargs[ lastargs.length - 2 ];
  17199. var y0 = lastargs[ lastargs.length - 1 ];
  17200. //---
  17201. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17202. Array.prototype.push.apply( npts, pts );
  17203. var curve = new THREE.SplineCurve( npts );
  17204. this.curves.push( curve );
  17205. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17206. };
  17207. // FUTURE: Change the API or follow canvas API?
  17208. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17209. aStartAngle, aEndAngle, aClockwise ) {
  17210. var lastargs = this.actions[ this.actions.length - 1].args;
  17211. var x0 = lastargs[ lastargs.length - 2 ];
  17212. var y0 = lastargs[ lastargs.length - 1 ];
  17213. this.absarc(aX + x0, aY + y0, aRadius,
  17214. aStartAngle, aEndAngle, aClockwise );
  17215. };
  17216. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17217. aStartAngle, aEndAngle, aClockwise ) {
  17218. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17219. };
  17220. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17221. aStartAngle, aEndAngle, aClockwise ) {
  17222. var lastargs = this.actions[ this.actions.length - 1].args;
  17223. var x0 = lastargs[ lastargs.length - 2 ];
  17224. var y0 = lastargs[ lastargs.length - 1 ];
  17225. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17226. aStartAngle, aEndAngle, aClockwise );
  17227. };
  17228. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17229. aStartAngle, aEndAngle, aClockwise ) {
  17230. var args = Array.prototype.slice.call( arguments );
  17231. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17232. aStartAngle, aEndAngle, aClockwise );
  17233. this.curves.push( curve );
  17234. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17235. args.push(lastPoint.x);
  17236. args.push(lastPoint.y);
  17237. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17238. };
  17239. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17240. if ( ! divisions ) divisions = 40;
  17241. var points = [];
  17242. for ( var i = 0; i < divisions; i ++ ) {
  17243. points.push( this.getPoint( i / divisions ) );
  17244. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17245. }
  17246. // if ( closedPath ) {
  17247. //
  17248. // points.push( points[ 0 ] );
  17249. //
  17250. // }
  17251. return points;
  17252. };
  17253. /* Return an array of vectors based on contour of the path */
  17254. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17255. if (this.useSpacedPoints) {
  17256. console.log('tata');
  17257. return this.getSpacedPoints( divisions, closedPath );
  17258. }
  17259. divisions = divisions || 12;
  17260. var points = [];
  17261. var i, il, item, action, args;
  17262. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17263. laste, j,
  17264. t, tx, ty;
  17265. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17266. item = this.actions[ i ];
  17267. action = item.action;
  17268. args = item.args;
  17269. switch( action ) {
  17270. case THREE.PathActions.MOVE_TO:
  17271. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17272. break;
  17273. case THREE.PathActions.LINE_TO:
  17274. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17275. break;
  17276. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17277. cpx = args[ 2 ];
  17278. cpy = args[ 3 ];
  17279. cpx1 = args[ 0 ];
  17280. cpy1 = args[ 1 ];
  17281. if ( points.length > 0 ) {
  17282. laste = points[ points.length - 1 ];
  17283. cpx0 = laste.x;
  17284. cpy0 = laste.y;
  17285. } else {
  17286. laste = this.actions[ i - 1 ].args;
  17287. cpx0 = laste[ laste.length - 2 ];
  17288. cpy0 = laste[ laste.length - 1 ];
  17289. }
  17290. for ( j = 1; j <= divisions; j ++ ) {
  17291. t = j / divisions;
  17292. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17293. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17294. points.push( new THREE.Vector2( tx, ty ) );
  17295. }
  17296. break;
  17297. case THREE.PathActions.BEZIER_CURVE_TO:
  17298. cpx = args[ 4 ];
  17299. cpy = args[ 5 ];
  17300. cpx1 = args[ 0 ];
  17301. cpy1 = args[ 1 ];
  17302. cpx2 = args[ 2 ];
  17303. cpy2 = args[ 3 ];
  17304. if ( points.length > 0 ) {
  17305. laste = points[ points.length - 1 ];
  17306. cpx0 = laste.x;
  17307. cpy0 = laste.y;
  17308. } else {
  17309. laste = this.actions[ i - 1 ].args;
  17310. cpx0 = laste[ laste.length - 2 ];
  17311. cpy0 = laste[ laste.length - 1 ];
  17312. }
  17313. for ( j = 1; j <= divisions; j ++ ) {
  17314. t = j / divisions;
  17315. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17316. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17317. points.push( new THREE.Vector2( tx, ty ) );
  17318. }
  17319. break;
  17320. case THREE.PathActions.CSPLINE_THRU:
  17321. laste = this.actions[ i - 1 ].args;
  17322. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17323. var spts = [ last ];
  17324. var n = divisions * args[ 0 ].length;
  17325. spts = spts.concat( args[ 0 ] );
  17326. var spline = new THREE.SplineCurve( spts );
  17327. for ( j = 1; j <= n; j ++ ) {
  17328. points.push( spline.getPointAt( j / n ) ) ;
  17329. }
  17330. break;
  17331. case THREE.PathActions.ARC:
  17332. var aX = args[ 0 ], aY = args[ 1 ],
  17333. aRadius = args[ 2 ],
  17334. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17335. aClockwise = !!args[ 5 ];
  17336. var deltaAngle = aEndAngle - aStartAngle;
  17337. var angle;
  17338. var tdivisions = divisions * 2;
  17339. for ( j = 1; j <= tdivisions; j ++ ) {
  17340. t = j / tdivisions;
  17341. if ( ! aClockwise ) {
  17342. t = 1 - t;
  17343. }
  17344. angle = aStartAngle + t * deltaAngle;
  17345. tx = aX + aRadius * Math.cos( angle );
  17346. ty = aY + aRadius * Math.sin( angle );
  17347. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17348. points.push( new THREE.Vector2( tx, ty ) );
  17349. }
  17350. //console.log(points);
  17351. break;
  17352. case THREE.PathActions.ELLIPSE:
  17353. var aX = args[ 0 ], aY = args[ 1 ],
  17354. xRadius = args[ 2 ],
  17355. yRadius = args[ 3 ],
  17356. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17357. aClockwise = !!args[ 6 ];
  17358. var deltaAngle = aEndAngle - aStartAngle;
  17359. var angle;
  17360. var tdivisions = divisions * 2;
  17361. for ( j = 1; j <= tdivisions; j ++ ) {
  17362. t = j / tdivisions;
  17363. if ( ! aClockwise ) {
  17364. t = 1 - t;
  17365. }
  17366. angle = aStartAngle + t * deltaAngle;
  17367. tx = aX + xRadius * Math.cos( angle );
  17368. ty = aY + yRadius * Math.sin( angle );
  17369. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17370. points.push( new THREE.Vector2( tx, ty ) );
  17371. }
  17372. //console.log(points);
  17373. break;
  17374. } // end switch
  17375. }
  17376. // Normalize to remove the closing point by default.
  17377. var lastPoint = points[ points.length - 1];
  17378. var EPSILON = 0.0000000001;
  17379. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17380. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17381. points.splice( points.length - 1, 1);
  17382. if ( closedPath ) {
  17383. points.push( points[ 0 ] );
  17384. }
  17385. return points;
  17386. };
  17387. // Breaks path into shapes
  17388. THREE.Path.prototype.toShapes = function() {
  17389. var i, il, item, action, args;
  17390. var subPaths = [], lastPath = new THREE.Path();
  17391. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17392. item = this.actions[ i ];
  17393. args = item.args;
  17394. action = item.action;
  17395. if ( action == THREE.PathActions.MOVE_TO ) {
  17396. if ( lastPath.actions.length != 0 ) {
  17397. subPaths.push( lastPath );
  17398. lastPath = new THREE.Path();
  17399. }
  17400. }
  17401. lastPath[ action ].apply( lastPath, args );
  17402. }
  17403. if ( lastPath.actions.length != 0 ) {
  17404. subPaths.push( lastPath );
  17405. }
  17406. // console.log(subPaths);
  17407. if ( subPaths.length == 0 ) return [];
  17408. var tmpPath, tmpShape, shapes = [];
  17409. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17410. // console.log("Holes first", holesFirst);
  17411. if ( subPaths.length == 1) {
  17412. tmpPath = subPaths[0];
  17413. tmpShape = new THREE.Shape();
  17414. tmpShape.actions = tmpPath.actions;
  17415. tmpShape.curves = tmpPath.curves;
  17416. shapes.push( tmpShape );
  17417. return shapes;
  17418. };
  17419. if ( holesFirst ) {
  17420. tmpShape = new THREE.Shape();
  17421. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17422. tmpPath = subPaths[ i ];
  17423. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17424. tmpShape.actions = tmpPath.actions;
  17425. tmpShape.curves = tmpPath.curves;
  17426. shapes.push( tmpShape );
  17427. tmpShape = new THREE.Shape();
  17428. //console.log('cw', i);
  17429. } else {
  17430. tmpShape.holes.push( tmpPath );
  17431. //console.log('ccw', i);
  17432. }
  17433. }
  17434. } else {
  17435. // Shapes first
  17436. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17437. tmpPath = subPaths[ i ];
  17438. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17439. if ( tmpShape ) shapes.push( tmpShape );
  17440. tmpShape = new THREE.Shape();
  17441. tmpShape.actions = tmpPath.actions;
  17442. tmpShape.curves = tmpPath.curves;
  17443. } else {
  17444. tmpShape.holes.push( tmpPath );
  17445. }
  17446. }
  17447. shapes.push( tmpShape );
  17448. }
  17449. //console.log("shape", shapes);
  17450. return shapes;
  17451. };
  17452. /**
  17453. * @author zz85 / http://www.lab4games.net/zz85/blog
  17454. * Defines a 2d shape plane using paths.
  17455. **/
  17456. // STEP 1 Create a path.
  17457. // STEP 2 Turn path into shape.
  17458. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17459. // STEP 3a - Extract points from each shape, turn to vertices
  17460. // STEP 3b - Triangulate each shape, add faces.
  17461. THREE.Shape = function ( ) {
  17462. THREE.Path.apply( this, arguments );
  17463. this.holes = [];
  17464. };
  17465. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17466. // Convenience method to return ExtrudeGeometry
  17467. THREE.Shape.prototype.extrude = function ( options ) {
  17468. var extruded = new THREE.ExtrudeGeometry( this, options );
  17469. return extruded;
  17470. };
  17471. // Convenience method to return ShapeGeometry
  17472. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17473. var geometry = new THREE.ShapeGeometry( this, options );
  17474. return geometry;
  17475. };
  17476. // Get points of holes
  17477. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17478. var i, il = this.holes.length, holesPts = [];
  17479. for ( i = 0; i < il; i ++ ) {
  17480. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17481. }
  17482. return holesPts;
  17483. };
  17484. // Get points of holes (spaced by regular distance)
  17485. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17486. var i, il = this.holes.length, holesPts = [];
  17487. for ( i = 0; i < il; i ++ ) {
  17488. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17489. }
  17490. return holesPts;
  17491. };
  17492. // Get points of shape and holes (keypoints based on segments parameter)
  17493. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17494. return {
  17495. shape: this.getTransformedPoints( divisions ),
  17496. holes: this.getPointsHoles( divisions )
  17497. };
  17498. };
  17499. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17500. if (this.useSpacedPoints) {
  17501. return this.extractAllSpacedPoints(divisions);
  17502. }
  17503. return this.extractAllPoints(divisions);
  17504. };
  17505. //
  17506. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17507. //
  17508. // return {
  17509. //
  17510. // shape: this.transform( bend, divisions ),
  17511. // holes: this.getPointsHoles( divisions, bend )
  17512. //
  17513. // };
  17514. //
  17515. // };
  17516. // Get points of shape and holes (spaced by regular distance)
  17517. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17518. return {
  17519. shape: this.getTransformedSpacedPoints( divisions ),
  17520. holes: this.getSpacedPointsHoles( divisions )
  17521. };
  17522. };
  17523. /**************************************************************
  17524. * Utils
  17525. **************************************************************/
  17526. THREE.Shape.Utils = {
  17527. /*
  17528. contour - array of vector2 for contour
  17529. holes - array of array of vector2
  17530. */
  17531. removeHoles: function ( contour, holes ) {
  17532. var shape = contour.concat(); // work on this shape
  17533. var allpoints = shape.concat();
  17534. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17535. var prevShapeVert, nextShapeVert,
  17536. prevHoleVert, nextHoleVert,
  17537. holeIndex, shapeIndex,
  17538. shapeId, shapeGroup,
  17539. h, h2,
  17540. hole, shortest, d,
  17541. p, pts1, pts2,
  17542. tmpShape1, tmpShape2,
  17543. tmpHole1, tmpHole2,
  17544. verts = [];
  17545. for ( h = 0; h < holes.length; h ++ ) {
  17546. hole = holes[ h ];
  17547. /*
  17548. shapeholes[ h ].concat(); // preserves original
  17549. holes.push( hole );
  17550. */
  17551. Array.prototype.push.apply( allpoints, hole );
  17552. shortest = Number.POSITIVE_INFINITY;
  17553. // Find the shortest pair of pts between shape and hole
  17554. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17555. // Using distanceToSquared() intead of distanceTo() should speed a little
  17556. // since running square roots operations are reduced.
  17557. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17558. pts1 = hole[ h2 ];
  17559. var dist = [];
  17560. for ( p = 0; p < shape.length; p++ ) {
  17561. pts2 = shape[ p ];
  17562. d = pts1.distanceToSquared( pts2 );
  17563. dist.push( d );
  17564. if ( d < shortest ) {
  17565. shortest = d;
  17566. holeIndex = h2;
  17567. shapeIndex = p;
  17568. }
  17569. }
  17570. }
  17571. //console.log("shortest", shortest, dist);
  17572. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17573. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17574. var areaapts = [
  17575. hole[ holeIndex ],
  17576. shape[ shapeIndex ],
  17577. shape[ prevShapeVert ]
  17578. ];
  17579. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17580. var areabpts = [
  17581. hole[ holeIndex ],
  17582. hole[ prevHoleVert ],
  17583. shape[ shapeIndex ]
  17584. ];
  17585. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17586. var shapeOffset = 1;
  17587. var holeOffset = -1;
  17588. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17589. shapeIndex += shapeOffset;
  17590. holeIndex += holeOffset;
  17591. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17592. shapeIndex %= shape.length;
  17593. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17594. holeIndex %= hole.length;
  17595. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17596. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17597. areaapts = [
  17598. hole[ holeIndex ],
  17599. shape[ shapeIndex ],
  17600. shape[ prevShapeVert ]
  17601. ];
  17602. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17603. areabpts = [
  17604. hole[ holeIndex ],
  17605. hole[ prevHoleVert ],
  17606. shape[ shapeIndex ]
  17607. ];
  17608. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17609. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17610. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17611. // In case areas are not correct.
  17612. //console.log("USE THIS");
  17613. shapeIndex = oldShapeIndex;
  17614. holeIndex = oldHoleIndex ;
  17615. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17616. shapeIndex %= shape.length;
  17617. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17618. holeIndex %= hole.length;
  17619. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17620. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17621. } else {
  17622. //console.log("USE THAT ")
  17623. }
  17624. tmpShape1 = shape.slice( 0, shapeIndex );
  17625. tmpShape2 = shape.slice( shapeIndex );
  17626. tmpHole1 = hole.slice( holeIndex );
  17627. tmpHole2 = hole.slice( 0, holeIndex );
  17628. // Should check orders here again?
  17629. var trianglea = [
  17630. hole[ holeIndex ],
  17631. shape[ shapeIndex ],
  17632. shape[ prevShapeVert ]
  17633. ];
  17634. var triangleb = [
  17635. hole[ holeIndex ] ,
  17636. hole[ prevHoleVert ],
  17637. shape[ shapeIndex ]
  17638. ];
  17639. verts.push( trianglea );
  17640. verts.push( triangleb );
  17641. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17642. }
  17643. return {
  17644. shape:shape, /* shape with no holes */
  17645. isolatedPts: verts, /* isolated faces */
  17646. allpoints: allpoints
  17647. }
  17648. },
  17649. triangulateShape: function ( contour, holes ) {
  17650. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17651. var shape = shapeWithoutHoles.shape,
  17652. allpoints = shapeWithoutHoles.allpoints,
  17653. isolatedPts = shapeWithoutHoles.isolatedPts;
  17654. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17655. // 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.
  17656. //console.log( "triangles",triangles, triangles.length );
  17657. //console.log( "allpoints",allpoints, allpoints.length );
  17658. var i, il, f, face,
  17659. key, index,
  17660. allPointsMap = {},
  17661. isolatedPointsMap = {};
  17662. // prepare all points map
  17663. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17664. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17665. if ( allPointsMap[ key ] !== undefined ) {
  17666. console.log( "Duplicate point", key );
  17667. }
  17668. allPointsMap[ key ] = i;
  17669. }
  17670. // check all face vertices against all points map
  17671. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17672. face = triangles[ i ];
  17673. for ( f = 0; f < 3; f ++ ) {
  17674. key = face[ f ].x + ":" + face[ f ].y;
  17675. index = allPointsMap[ key ];
  17676. if ( index !== undefined ) {
  17677. face[ f ] = index;
  17678. }
  17679. }
  17680. }
  17681. // check isolated points vertices against all points map
  17682. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17683. face = isolatedPts[ i ];
  17684. for ( f = 0; f < 3; f ++ ) {
  17685. key = face[ f ].x + ":" + face[ f ].y;
  17686. index = allPointsMap[ key ];
  17687. if ( index !== undefined ) {
  17688. face[ f ] = index;
  17689. }
  17690. }
  17691. }
  17692. return triangles.concat( isolatedPts );
  17693. }, // end triangulate shapes
  17694. /*
  17695. triangulate2 : function( pts, holes ) {
  17696. // For use with Poly2Tri.js
  17697. var allpts = pts.concat();
  17698. var shape = [];
  17699. for (var p in pts) {
  17700. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17701. }
  17702. var swctx = new js.poly2tri.SweepContext(shape);
  17703. for (var h in holes) {
  17704. var aHole = holes[h];
  17705. var newHole = []
  17706. for (i in aHole) {
  17707. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17708. allpts.push(aHole[i]);
  17709. }
  17710. swctx.AddHole(newHole);
  17711. }
  17712. var find;
  17713. var findIndexForPt = function (pt) {
  17714. find = new THREE.Vector2(pt.x, pt.y);
  17715. var p;
  17716. for (p=0, pl = allpts.length; p<pl; p++) {
  17717. if (allpts[p].equals(find)) return p;
  17718. }
  17719. return -1;
  17720. };
  17721. // triangulate
  17722. js.poly2tri.sweep.Triangulate(swctx);
  17723. var triangles = swctx.GetTriangles();
  17724. var tr ;
  17725. var facesPts = [];
  17726. for (var t in triangles) {
  17727. tr = triangles[t];
  17728. facesPts.push([
  17729. findIndexForPt(tr.GetPoint(0)),
  17730. findIndexForPt(tr.GetPoint(1)),
  17731. findIndexForPt(tr.GetPoint(2))
  17732. ]);
  17733. }
  17734. // console.log(facesPts);
  17735. // console.log("triangles", triangles.length, triangles);
  17736. // Returns array of faces with 3 element each
  17737. return facesPts;
  17738. },
  17739. */
  17740. isClockWise: function ( pts ) {
  17741. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17742. },
  17743. // Bezier Curves formulas obtained from
  17744. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17745. // Quad Bezier Functions
  17746. b2p0: function ( t, p ) {
  17747. var k = 1 - t;
  17748. return k * k * p;
  17749. },
  17750. b2p1: function ( t, p ) {
  17751. return 2 * ( 1 - t ) * t * p;
  17752. },
  17753. b2p2: function ( t, p ) {
  17754. return t * t * p;
  17755. },
  17756. b2: function ( t, p0, p1, p2 ) {
  17757. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17758. },
  17759. // Cubic Bezier Functions
  17760. b3p0: function ( t, p ) {
  17761. var k = 1 - t;
  17762. return k * k * k * p;
  17763. },
  17764. b3p1: function ( t, p ) {
  17765. var k = 1 - t;
  17766. return 3 * k * k * t * p;
  17767. },
  17768. b3p2: function ( t, p ) {
  17769. var k = 1 - t;
  17770. return 3 * k * t * t * p;
  17771. },
  17772. b3p3: function ( t, p ) {
  17773. return t * t * t * p;
  17774. },
  17775. b3: function ( t, p0, p1, p2, p3 ) {
  17776. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17777. }
  17778. };
  17779. /**
  17780. * @author mikael emtinger / http://gomo.se/
  17781. */
  17782. THREE.AnimationHandler = (function() {
  17783. var playing = [];
  17784. var library = {};
  17785. var that = {};
  17786. //--- update ---
  17787. that.update = function( deltaTimeMS ) {
  17788. for( var i = 0; i < playing.length; i ++ )
  17789. playing[ i ].update( deltaTimeMS );
  17790. };
  17791. //--- add ---
  17792. that.addToUpdate = function( animation ) {
  17793. if ( playing.indexOf( animation ) === -1 )
  17794. playing.push( animation );
  17795. };
  17796. //--- remove ---
  17797. that.removeFromUpdate = function( animation ) {
  17798. var index = playing.indexOf( animation );
  17799. if( index !== -1 )
  17800. playing.splice( index, 1 );
  17801. };
  17802. //--- add ---
  17803. that.add = function( data ) {
  17804. if ( library[ data.name ] !== undefined )
  17805. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17806. library[ data.name ] = data;
  17807. initData( data );
  17808. };
  17809. //--- get ---
  17810. that.get = function( name ) {
  17811. if ( typeof name === "string" ) {
  17812. if ( library[ name ] ) {
  17813. return library[ name ];
  17814. } else {
  17815. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17816. return null;
  17817. }
  17818. } else {
  17819. // todo: add simple tween library
  17820. }
  17821. };
  17822. //--- parse ---
  17823. that.parse = function( root ) {
  17824. // setup hierarchy
  17825. var hierarchy = [];
  17826. if ( root instanceof THREE.SkinnedMesh ) {
  17827. for( var b = 0; b < root.bones.length; b++ ) {
  17828. hierarchy.push( root.bones[ b ] );
  17829. }
  17830. } else {
  17831. parseRecurseHierarchy( root, hierarchy );
  17832. }
  17833. return hierarchy;
  17834. };
  17835. var parseRecurseHierarchy = function( root, hierarchy ) {
  17836. hierarchy.push( root );
  17837. for( var c = 0; c < root.children.length; c++ )
  17838. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17839. }
  17840. //--- init data ---
  17841. var initData = function( data ) {
  17842. if( data.initialized === true )
  17843. return;
  17844. // loop through all keys
  17845. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17846. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17847. // remove minus times
  17848. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17849. data.hierarchy[ h ].keys[ k ].time = 0;
  17850. // create quaternions
  17851. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17852. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17853. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17854. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17855. }
  17856. }
  17857. // prepare morph target keys
  17858. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17859. // get all used
  17860. var usedMorphTargets = {};
  17861. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17862. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17863. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17864. usedMorphTargets[ morphTargetName ] = -1;
  17865. }
  17866. }
  17867. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17868. // set all used on all frames
  17869. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17870. var influences = {};
  17871. for ( var morphTargetName in usedMorphTargets ) {
  17872. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17873. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17874. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17875. break;
  17876. }
  17877. }
  17878. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17879. influences[ morphTargetName ] = 0;
  17880. }
  17881. }
  17882. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17883. }
  17884. }
  17885. // remove all keys that are on the same time
  17886. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17887. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17888. data.hierarchy[ h ].keys.splice( k, 1 );
  17889. k --;
  17890. }
  17891. }
  17892. // set index
  17893. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17894. data.hierarchy[ h ].keys[ k ].index = k;
  17895. }
  17896. }
  17897. // JIT
  17898. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17899. data.JIT = {};
  17900. data.JIT.hierarchy = [];
  17901. for( var h = 0; h < data.hierarchy.length; h ++ )
  17902. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17903. // done
  17904. data.initialized = true;
  17905. };
  17906. // interpolation types
  17907. that.LINEAR = 0;
  17908. that.CATMULLROM = 1;
  17909. that.CATMULLROM_FORWARD = 2;
  17910. return that;
  17911. }());
  17912. /**
  17913. * @author mikael emtinger / http://gomo.se/
  17914. * @author mrdoob / http://mrdoob.com/
  17915. * @author alteredq / http://alteredqualia.com/
  17916. */
  17917. THREE.Animation = function ( root, name, interpolationType ) {
  17918. this.root = root;
  17919. this.data = THREE.AnimationHandler.get( name );
  17920. this.hierarchy = THREE.AnimationHandler.parse( root );
  17921. this.currentTime = 0;
  17922. this.timeScale = 1;
  17923. this.isPlaying = false;
  17924. this.isPaused = true;
  17925. this.loop = true;
  17926. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17927. this.points = [];
  17928. this.target = new THREE.Vector3();
  17929. };
  17930. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17931. if ( this.isPlaying === false ) {
  17932. this.isPlaying = true;
  17933. this.loop = loop !== undefined ? loop : true;
  17934. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17935. // reset key cache
  17936. var h, hl = this.hierarchy.length,
  17937. object;
  17938. for ( h = 0; h < hl; h ++ ) {
  17939. object = this.hierarchy[ h ];
  17940. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17941. object.useQuaternion = true;
  17942. }
  17943. object.matrixAutoUpdate = true;
  17944. if ( object.animationCache === undefined ) {
  17945. object.animationCache = {};
  17946. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17947. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17948. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17949. }
  17950. var prevKey = object.animationCache.prevKey;
  17951. var nextKey = object.animationCache.nextKey;
  17952. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17953. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17954. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17955. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17956. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17957. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17958. }
  17959. this.update( 0 );
  17960. }
  17961. this.isPaused = false;
  17962. THREE.AnimationHandler.addToUpdate( this );
  17963. };
  17964. THREE.Animation.prototype.pause = function() {
  17965. if ( this.isPaused === true ) {
  17966. THREE.AnimationHandler.addToUpdate( this );
  17967. } else {
  17968. THREE.AnimationHandler.removeFromUpdate( this );
  17969. }
  17970. this.isPaused = !this.isPaused;
  17971. };
  17972. THREE.Animation.prototype.stop = function() {
  17973. this.isPlaying = false;
  17974. this.isPaused = false;
  17975. THREE.AnimationHandler.removeFromUpdate( this );
  17976. };
  17977. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17978. // early out
  17979. if ( this.isPlaying === false ) return;
  17980. // vars
  17981. var types = [ "pos", "rot", "scl" ];
  17982. var type;
  17983. var scale;
  17984. var vector;
  17985. var prevXYZ, nextXYZ;
  17986. var prevKey, nextKey;
  17987. var object;
  17988. var animationCache;
  17989. var frame;
  17990. var JIThierarchy = this.data.JIT.hierarchy;
  17991. var currentTime, unloopedCurrentTime;
  17992. var currentPoint, forwardPoint, angle;
  17993. this.currentTime += deltaTimeMS * this.timeScale;
  17994. unloopedCurrentTime = this.currentTime;
  17995. currentTime = this.currentTime = this.currentTime % this.data.length;
  17996. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17997. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17998. object = this.hierarchy[ h ];
  17999. animationCache = object.animationCache;
  18000. // loop through pos/rot/scl
  18001. for ( var t = 0; t < 3; t ++ ) {
  18002. // get keys
  18003. type = types[ t ];
  18004. prevKey = animationCache.prevKey[ type ];
  18005. nextKey = animationCache.nextKey[ type ];
  18006. // switch keys?
  18007. if ( nextKey.time <= unloopedCurrentTime ) {
  18008. // did we loop?
  18009. if ( currentTime < unloopedCurrentTime ) {
  18010. if ( this.loop ) {
  18011. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18012. nextKey = this.getNextKeyWith( type, h, 1 );
  18013. while( nextKey.time < currentTime ) {
  18014. prevKey = nextKey;
  18015. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18016. }
  18017. } else {
  18018. this.stop();
  18019. return;
  18020. }
  18021. } else {
  18022. do {
  18023. prevKey = nextKey;
  18024. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18025. } while( nextKey.time < currentTime )
  18026. }
  18027. animationCache.prevKey[ type ] = prevKey;
  18028. animationCache.nextKey[ type ] = nextKey;
  18029. }
  18030. object.matrixAutoUpdate = true;
  18031. object.matrixWorldNeedsUpdate = true;
  18032. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18033. prevXYZ = prevKey[ type ];
  18034. nextXYZ = nextKey[ type ];
  18035. // check scale error
  18036. if ( scale < 0 || scale > 1 ) {
  18037. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18038. scale = scale < 0 ? 0 : 1;
  18039. }
  18040. // interpolate
  18041. if ( type === "pos" ) {
  18042. vector = object.position;
  18043. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18044. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18045. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18046. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18047. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18048. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18049. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18050. this.points[ 1 ] = prevXYZ;
  18051. this.points[ 2 ] = nextXYZ;
  18052. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18053. scale = scale * 0.33 + 0.33;
  18054. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18055. vector.x = currentPoint[ 0 ];
  18056. vector.y = currentPoint[ 1 ];
  18057. vector.z = currentPoint[ 2 ];
  18058. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18059. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18060. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18061. this.target.subSelf( vector );
  18062. this.target.y = 0;
  18063. this.target.normalize();
  18064. angle = Math.atan2( this.target.x, this.target.z );
  18065. object.rotation.set( 0, angle, 0 );
  18066. }
  18067. }
  18068. } else if ( type === "rot" ) {
  18069. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18070. } else if ( type === "scl" ) {
  18071. vector = object.scale;
  18072. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18073. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18074. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18075. }
  18076. }
  18077. }
  18078. };
  18079. // Catmull-Rom spline
  18080. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18081. var c = [], v3 = [],
  18082. point, intPoint, weight, w2, w3,
  18083. pa, pb, pc, pd;
  18084. point = ( points.length - 1 ) * scale;
  18085. intPoint = Math.floor( point );
  18086. weight = point - intPoint;
  18087. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18088. c[ 1 ] = intPoint;
  18089. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18090. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18091. pa = points[ c[ 0 ] ];
  18092. pb = points[ c[ 1 ] ];
  18093. pc = points[ c[ 2 ] ];
  18094. pd = points[ c[ 3 ] ];
  18095. w2 = weight * weight;
  18096. w3 = weight * w2;
  18097. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18098. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18099. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18100. return v3;
  18101. };
  18102. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18103. var v0 = ( p2 - p0 ) * 0.5,
  18104. v1 = ( p3 - p1 ) * 0.5;
  18105. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18106. };
  18107. // Get next key with
  18108. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18109. var keys = this.data.hierarchy[ h ].keys;
  18110. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18111. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18112. key = key < keys.length - 1 ? key : keys.length - 1;
  18113. } else {
  18114. key = key % keys.length;
  18115. }
  18116. for ( ; key < keys.length; key++ ) {
  18117. if ( keys[ key ][ type ] !== undefined ) {
  18118. return keys[ key ];
  18119. }
  18120. }
  18121. return this.data.hierarchy[ h ].keys[ 0 ];
  18122. };
  18123. // Get previous key with
  18124. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18125. var keys = this.data.hierarchy[ h ].keys;
  18126. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18127. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18128. key = key > 0 ? key : 0;
  18129. } else {
  18130. key = key >= 0 ? key : key + keys.length;
  18131. }
  18132. for ( ; key >= 0; key -- ) {
  18133. if ( keys[ key ][ type ] !== undefined ) {
  18134. return keys[ key ];
  18135. }
  18136. }
  18137. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18138. };
  18139. /**
  18140. * @author mikael emtinger / http://gomo.se/
  18141. * @author mrdoob / http://mrdoob.com/
  18142. * @author alteredq / http://alteredqualia.com/
  18143. * @author khang duong
  18144. * @author erik kitson
  18145. */
  18146. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18147. this.root = root;
  18148. this.data = THREE.AnimationHandler.get( data );
  18149. this.hierarchy = THREE.AnimationHandler.parse( root );
  18150. this.currentTime = 0;
  18151. this.timeScale = 0.001;
  18152. this.isPlaying = false;
  18153. this.isPaused = true;
  18154. this.loop = true;
  18155. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18156. // initialize to first keyframes
  18157. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18158. var keys = this.data.hierarchy[h].keys,
  18159. sids = this.data.hierarchy[h].sids,
  18160. obj = this.hierarchy[h];
  18161. if ( keys.length && sids ) {
  18162. for ( var s = 0; s < sids.length; s++ ) {
  18163. var sid = sids[ s ],
  18164. next = this.getNextKeyWith( sid, h, 0 );
  18165. if ( next ) {
  18166. next.apply( sid );
  18167. }
  18168. }
  18169. obj.matrixAutoUpdate = false;
  18170. this.data.hierarchy[h].node.updateMatrix();
  18171. obj.matrixWorldNeedsUpdate = true;
  18172. }
  18173. }
  18174. };
  18175. // Play
  18176. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18177. if( !this.isPlaying ) {
  18178. this.isPlaying = true;
  18179. this.loop = loop !== undefined ? loop : true;
  18180. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18181. this.startTimeMs = startTimeMS;
  18182. this.startTime = 10000000;
  18183. this.endTime = -this.startTime;
  18184. // reset key cache
  18185. var h, hl = this.hierarchy.length,
  18186. object,
  18187. node;
  18188. for ( h = 0; h < hl; h++ ) {
  18189. object = this.hierarchy[ h ];
  18190. node = this.data.hierarchy[ h ];
  18191. object.useQuaternion = true;
  18192. if ( node.animationCache === undefined ) {
  18193. node.animationCache = {};
  18194. node.animationCache.prevKey = null;
  18195. node.animationCache.nextKey = null;
  18196. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18197. }
  18198. var keys = this.data.hierarchy[h].keys;
  18199. if (keys.length) {
  18200. node.animationCache.prevKey = keys[ 0 ];
  18201. node.animationCache.nextKey = keys[ 1 ];
  18202. this.startTime = Math.min( keys[0].time, this.startTime );
  18203. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18204. }
  18205. }
  18206. this.update( 0 );
  18207. }
  18208. this.isPaused = false;
  18209. THREE.AnimationHandler.addToUpdate( this );
  18210. };
  18211. // Pause
  18212. THREE.KeyFrameAnimation.prototype.pause = function() {
  18213. if( this.isPaused ) {
  18214. THREE.AnimationHandler.addToUpdate( this );
  18215. } else {
  18216. THREE.AnimationHandler.removeFromUpdate( this );
  18217. }
  18218. this.isPaused = !this.isPaused;
  18219. };
  18220. // Stop
  18221. THREE.KeyFrameAnimation.prototype.stop = function() {
  18222. this.isPlaying = false;
  18223. this.isPaused = false;
  18224. THREE.AnimationHandler.removeFromUpdate( this );
  18225. // reset JIT matrix and remove cache
  18226. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18227. var obj = this.hierarchy[ h ];
  18228. var node = this.data.hierarchy[ h ];
  18229. if ( node.animationCache !== undefined ) {
  18230. var original = node.animationCache.originalMatrix;
  18231. if( obj instanceof THREE.Bone ) {
  18232. original.copy( obj.skinMatrix );
  18233. obj.skinMatrix = original;
  18234. } else {
  18235. original.copy( obj.matrix );
  18236. obj.matrix = original;
  18237. }
  18238. delete node.animationCache;
  18239. }
  18240. }
  18241. };
  18242. // Update
  18243. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18244. // early out
  18245. if( !this.isPlaying ) return;
  18246. // vars
  18247. var prevKey, nextKey;
  18248. var object;
  18249. var node;
  18250. var frame;
  18251. var JIThierarchy = this.data.JIT.hierarchy;
  18252. var currentTime, unloopedCurrentTime;
  18253. var looped;
  18254. // update
  18255. this.currentTime += deltaTimeMS * this.timeScale;
  18256. unloopedCurrentTime = this.currentTime;
  18257. currentTime = this.currentTime = this.currentTime % this.data.length;
  18258. // if looped around, the current time should be based on the startTime
  18259. if ( currentTime < this.startTimeMs ) {
  18260. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18261. }
  18262. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18263. looped = currentTime < unloopedCurrentTime;
  18264. if ( looped && !this.loop ) {
  18265. // Set the animation to the last keyframes and stop
  18266. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18267. var keys = this.data.hierarchy[h].keys,
  18268. sids = this.data.hierarchy[h].sids,
  18269. end = keys.length-1,
  18270. obj = this.hierarchy[h];
  18271. if ( keys.length ) {
  18272. for ( var s = 0; s < sids.length; s++ ) {
  18273. var sid = sids[ s ],
  18274. prev = this.getPrevKeyWith( sid, h, end );
  18275. if ( prev ) {
  18276. prev.apply( sid );
  18277. }
  18278. }
  18279. this.data.hierarchy[h].node.updateMatrix();
  18280. obj.matrixWorldNeedsUpdate = true;
  18281. }
  18282. }
  18283. this.stop();
  18284. return;
  18285. }
  18286. // check pre-infinity
  18287. if ( currentTime < this.startTime ) {
  18288. return;
  18289. }
  18290. // update
  18291. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18292. object = this.hierarchy[ h ];
  18293. node = this.data.hierarchy[ h ];
  18294. var keys = node.keys,
  18295. animationCache = node.animationCache;
  18296. // use JIT?
  18297. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18298. if( object instanceof THREE.Bone ) {
  18299. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18300. object.matrixWorldNeedsUpdate = false;
  18301. } else {
  18302. object.matrix = JIThierarchy[ h ][ frame ];
  18303. object.matrixWorldNeedsUpdate = true;
  18304. }
  18305. // use interpolation
  18306. } else if ( keys.length ) {
  18307. // make sure so original matrix and not JIT matrix is set
  18308. if ( this.JITCompile && animationCache ) {
  18309. if( object instanceof THREE.Bone ) {
  18310. object.skinMatrix = animationCache.originalMatrix;
  18311. } else {
  18312. object.matrix = animationCache.originalMatrix;
  18313. }
  18314. }
  18315. prevKey = animationCache.prevKey;
  18316. nextKey = animationCache.nextKey;
  18317. if ( prevKey && nextKey ) {
  18318. // switch keys?
  18319. if ( nextKey.time <= unloopedCurrentTime ) {
  18320. // did we loop?
  18321. if ( looped && this.loop ) {
  18322. prevKey = keys[ 0 ];
  18323. nextKey = keys[ 1 ];
  18324. while ( nextKey.time < currentTime ) {
  18325. prevKey = nextKey;
  18326. nextKey = keys[ prevKey.index + 1 ];
  18327. }
  18328. } else if ( !looped ) {
  18329. var lastIndex = keys.length - 1;
  18330. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18331. prevKey = nextKey;
  18332. nextKey = keys[ prevKey.index + 1 ];
  18333. }
  18334. }
  18335. animationCache.prevKey = prevKey;
  18336. animationCache.nextKey = nextKey;
  18337. }
  18338. if(nextKey.time >= currentTime)
  18339. prevKey.interpolate( nextKey, currentTime );
  18340. else
  18341. prevKey.interpolate( nextKey, nextKey.time);
  18342. }
  18343. this.data.hierarchy[h].node.updateMatrix();
  18344. object.matrixWorldNeedsUpdate = true;
  18345. }
  18346. }
  18347. // update JIT?
  18348. if ( this.JITCompile ) {
  18349. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18350. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18351. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18352. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18353. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18354. } else {
  18355. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18356. }
  18357. }
  18358. }
  18359. }
  18360. };
  18361. // Get next key with
  18362. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18363. var keys = this.data.hierarchy[ h ].keys;
  18364. key = key % keys.length;
  18365. for ( ; key < keys.length; key++ ) {
  18366. if ( keys[ key ].hasTarget( sid ) ) {
  18367. return keys[ key ];
  18368. }
  18369. }
  18370. return keys[ 0 ];
  18371. };
  18372. // Get previous key with
  18373. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18374. var keys = this.data.hierarchy[ h ].keys;
  18375. key = key >= 0 ? key : key + keys.length;
  18376. for ( ; key >= 0; key-- ) {
  18377. if ( keys[ key ].hasTarget( sid ) ) {
  18378. return keys[ key ];
  18379. }
  18380. }
  18381. return keys[ keys.length - 1 ];
  18382. };
  18383. /**
  18384. * Camera for rendering cube maps
  18385. * - renders scene into axis-aligned cube
  18386. *
  18387. * @author alteredq / http://alteredqualia.com/
  18388. */
  18389. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18390. THREE.Object3D.call( this );
  18391. var fov = 90, aspect = 1;
  18392. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18393. cameraPX.up.set( 0, -1, 0 );
  18394. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18395. this.add( cameraPX );
  18396. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18397. cameraNX.up.set( 0, -1, 0 );
  18398. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18399. this.add( cameraNX );
  18400. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18401. cameraPY.up.set( 0, 0, 1 );
  18402. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18403. this.add( cameraPY );
  18404. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18405. cameraNY.up.set( 0, 0, -1 );
  18406. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18407. this.add( cameraNY );
  18408. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18409. cameraPZ.up.set( 0, -1, 0 );
  18410. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18411. this.add( cameraPZ );
  18412. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18413. cameraNZ.up.set( 0, -1, 0 );
  18414. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18415. this.add( cameraNZ );
  18416. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18417. this.updateCubeMap = function ( renderer, scene ) {
  18418. var renderTarget = this.renderTarget;
  18419. var generateMipmaps = renderTarget.generateMipmaps;
  18420. renderTarget.generateMipmaps = false;
  18421. renderTarget.activeCubeFace = 0;
  18422. renderer.render( scene, cameraPX, renderTarget );
  18423. renderTarget.activeCubeFace = 1;
  18424. renderer.render( scene, cameraNX, renderTarget );
  18425. renderTarget.activeCubeFace = 2;
  18426. renderer.render( scene, cameraPY, renderTarget );
  18427. renderTarget.activeCubeFace = 3;
  18428. renderer.render( scene, cameraNY, renderTarget );
  18429. renderTarget.activeCubeFace = 4;
  18430. renderer.render( scene, cameraPZ, renderTarget );
  18431. renderTarget.generateMipmaps = generateMipmaps;
  18432. renderTarget.activeCubeFace = 5;
  18433. renderer.render( scene, cameraNZ, renderTarget );
  18434. };
  18435. };
  18436. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18437. /*
  18438. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18439. *
  18440. * A general perpose camera, for setting FOV, Lens Focal Length,
  18441. * and switching between perspective and orthographic views easily.
  18442. * Use this only if you do not wish to manage
  18443. * both a Orthographic and Perspective Camera
  18444. *
  18445. */
  18446. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18447. THREE.Camera.call( this );
  18448. this.fov = fov;
  18449. this.left = -width / 2;
  18450. this.right = width / 2
  18451. this.top = height / 2;
  18452. this.bottom = -height / 2;
  18453. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18454. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18455. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18456. this.zoom = 1;
  18457. this.toPerspective();
  18458. var aspect = width/height;
  18459. };
  18460. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18461. THREE.CombinedCamera.prototype.toPerspective = function () {
  18462. // Switches to the Perspective Camera
  18463. this.near = this.cameraP.near;
  18464. this.far = this.cameraP.far;
  18465. this.cameraP.fov = this.fov / this.zoom ;
  18466. this.cameraP.updateProjectionMatrix();
  18467. this.projectionMatrix = this.cameraP.projectionMatrix;
  18468. this.inPerspectiveMode = true;
  18469. this.inOrthographicMode = false;
  18470. };
  18471. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18472. // Switches to the Orthographic camera estimating viewport from Perspective
  18473. var fov = this.fov;
  18474. var aspect = this.cameraP.aspect;
  18475. var near = this.cameraP.near;
  18476. var far = this.cameraP.far;
  18477. // The size that we set is the mid plane of the viewing frustum
  18478. var hyperfocus = ( near + far ) / 2;
  18479. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18480. var planeHeight = 2 * halfHeight;
  18481. var planeWidth = planeHeight * aspect;
  18482. var halfWidth = planeWidth / 2;
  18483. halfHeight /= this.zoom;
  18484. halfWidth /= this.zoom;
  18485. this.cameraO.left = -halfWidth;
  18486. this.cameraO.right = halfWidth;
  18487. this.cameraO.top = halfHeight;
  18488. this.cameraO.bottom = -halfHeight;
  18489. // this.cameraO.left = -farHalfWidth;
  18490. // this.cameraO.right = farHalfWidth;
  18491. // this.cameraO.top = farHalfHeight;
  18492. // this.cameraO.bottom = -farHalfHeight;
  18493. // this.cameraO.left = this.left / this.zoom;
  18494. // this.cameraO.right = this.right / this.zoom;
  18495. // this.cameraO.top = this.top / this.zoom;
  18496. // this.cameraO.bottom = this.bottom / this.zoom;
  18497. this.cameraO.updateProjectionMatrix();
  18498. this.near = this.cameraO.near;
  18499. this.far = this.cameraO.far;
  18500. this.projectionMatrix = this.cameraO.projectionMatrix;
  18501. this.inPerspectiveMode = false;
  18502. this.inOrthographicMode = true;
  18503. };
  18504. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18505. this.cameraP.aspect = width / height;
  18506. this.left = -width / 2;
  18507. this.right = width / 2
  18508. this.top = height / 2;
  18509. this.bottom = -height / 2;
  18510. };
  18511. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18512. this.fov = fov;
  18513. if ( this.inPerspectiveMode ) {
  18514. this.toPerspective();
  18515. } else {
  18516. this.toOrthographic();
  18517. }
  18518. };
  18519. // For mantaining similar API with PerspectiveCamera
  18520. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18521. if ( this.inPerspectiveMode ) {
  18522. this.toPerspective();
  18523. } else {
  18524. this.toPerspective();
  18525. this.toOrthographic();
  18526. }
  18527. };
  18528. /*
  18529. * Uses Focal Length (in mm) to estimate and set FOV
  18530. * 35mm (fullframe) camera is used if frame size is not specified;
  18531. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18532. */
  18533. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18534. if ( frameHeight === undefined ) frameHeight = 24;
  18535. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  18536. this.setFov( fov );
  18537. return fov;
  18538. };
  18539. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18540. this.zoom = zoom;
  18541. if ( this.inPerspectiveMode ) {
  18542. this.toPerspective();
  18543. } else {
  18544. this.toOrthographic();
  18545. }
  18546. };
  18547. THREE.CombinedCamera.prototype.toFrontView = function() {
  18548. this.rotation.x = 0;
  18549. this.rotation.y = 0;
  18550. this.rotation.z = 0;
  18551. // should we be modifing the matrix instead?
  18552. this.rotationAutoUpdate = false;
  18553. };
  18554. THREE.CombinedCamera.prototype.toBackView = function() {
  18555. this.rotation.x = 0;
  18556. this.rotation.y = Math.PI;
  18557. this.rotation.z = 0;
  18558. this.rotationAutoUpdate = false;
  18559. };
  18560. THREE.CombinedCamera.prototype.toLeftView = function() {
  18561. this.rotation.x = 0;
  18562. this.rotation.y = - Math.PI / 2;
  18563. this.rotation.z = 0;
  18564. this.rotationAutoUpdate = false;
  18565. };
  18566. THREE.CombinedCamera.prototype.toRightView = function() {
  18567. this.rotation.x = 0;
  18568. this.rotation.y = Math.PI / 2;
  18569. this.rotation.z = 0;
  18570. this.rotationAutoUpdate = false;
  18571. };
  18572. THREE.CombinedCamera.prototype.toTopView = function() {
  18573. this.rotation.x = - Math.PI / 2;
  18574. this.rotation.y = 0;
  18575. this.rotation.z = 0;
  18576. this.rotationAutoUpdate = false;
  18577. };
  18578. THREE.CombinedCamera.prototype.toBottomView = function() {
  18579. this.rotation.x = Math.PI / 2;
  18580. this.rotation.y = 0;
  18581. this.rotation.z = 0;
  18582. this.rotationAutoUpdate = false;
  18583. };
  18584. /**
  18585. * @author alteredq / http://alteredqualia.com/
  18586. *
  18587. * - 3d asterisk shape (for line pieces THREE.Line)
  18588. */
  18589. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  18590. THREE.Geometry.call( this );
  18591. var sd = innerRadius;
  18592. var ed = outerRadius;
  18593. var sd2 = 0.707 * sd;
  18594. var ed2 = 0.707 * ed;
  18595. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  18596. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  18597. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  18598. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  18599. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  18600. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  18601. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  18602. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  18603. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  18604. ];
  18605. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  18606. var x = rays[ i ][ 0 ];
  18607. var y = rays[ i ][ 1 ];
  18608. var z = rays[ i ][ 2 ];
  18609. this.vertices.push( new THREE.Vector3( x, y, z ) );
  18610. }
  18611. };
  18612. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  18613. * @author hughes
  18614. */
  18615. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18616. THREE.Geometry.call( this );
  18617. radius = radius || 50;
  18618. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18619. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18620. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18621. var i, uvs = [],
  18622. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18623. this.vertices.push(center);
  18624. uvs.push( centerUV );
  18625. for ( i = 0; i <= segments; i ++ ) {
  18626. var vertex = new THREE.Vector3();
  18627. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  18628. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  18629. this.vertices.push( vertex );
  18630. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  18631. }
  18632. var n = new THREE.Vector3( 0, 0, -1 );
  18633. for ( i = 1; i <= segments; i ++ ) {
  18634. var v1 = i;
  18635. var v2 = i + 1 ;
  18636. var v3 = 0;
  18637. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18638. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18639. }
  18640. this.computeCentroids();
  18641. this.computeFaceNormals();
  18642. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18643. };
  18644. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18645. /**
  18646. * @author mrdoob / http://mrdoob.com/
  18647. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18648. */
  18649. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18650. THREE.Geometry.call( this );
  18651. var scope = this;
  18652. this.width = width;
  18653. this.height = height;
  18654. this.depth = depth;
  18655. this.widthSegments = widthSegments || 1;
  18656. this.heightSegments = heightSegments || 1;
  18657. this.depthSegments = depthSegments || 1;
  18658. var width_half = this.width / 2;
  18659. var height_half = this.height / 2;
  18660. var depth_half = this.depth / 2;
  18661. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18662. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18663. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18664. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18665. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18666. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18667. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18668. var w, ix, iy,
  18669. gridX = scope.widthSegments,
  18670. gridY = scope.heightSegments,
  18671. width_half = width / 2,
  18672. height_half = height / 2,
  18673. offset = scope.vertices.length;
  18674. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18675. w = 'z';
  18676. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18677. w = 'y';
  18678. gridY = scope.depthSegments;
  18679. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18680. w = 'x';
  18681. gridX = scope.depthSegments;
  18682. }
  18683. var gridX1 = gridX + 1,
  18684. gridY1 = gridY + 1,
  18685. segment_width = width / gridX,
  18686. segment_height = height / gridY,
  18687. normal = new THREE.Vector3();
  18688. normal[ w ] = depth > 0 ? 1 : - 1;
  18689. for ( iy = 0; iy < gridY1; iy ++ ) {
  18690. for ( ix = 0; ix < gridX1; ix ++ ) {
  18691. var vector = new THREE.Vector3();
  18692. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18693. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18694. vector[ w ] = depth;
  18695. scope.vertices.push( vector );
  18696. }
  18697. }
  18698. for ( iy = 0; iy < gridY; iy++ ) {
  18699. for ( ix = 0; ix < gridX; ix++ ) {
  18700. var a = ix + gridX1 * iy;
  18701. var b = ix + gridX1 * ( iy + 1 );
  18702. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18703. var d = ( ix + 1 ) + gridX1 * iy;
  18704. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18705. face.normal.copy( normal );
  18706. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18707. face.materialIndex = materialIndex;
  18708. scope.faces.push( face );
  18709. scope.faceVertexUvs[ 0 ].push( [
  18710. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18711. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18712. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18713. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18714. ] );
  18715. }
  18716. }
  18717. }
  18718. this.computeCentroids();
  18719. this.mergeVertices();
  18720. };
  18721. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18722. /**
  18723. * @author mrdoob / http://mrdoob.com/
  18724. */
  18725. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18726. THREE.Geometry.call( this );
  18727. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18728. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18729. height = height !== undefined ? height : 100;
  18730. var heightHalf = height / 2;
  18731. var segmentsX = radiusSegments || 8;
  18732. var segmentsY = heightSegments || 1;
  18733. var x, y, vertices = [], uvs = [];
  18734. for ( y = 0; y <= segmentsY; y ++ ) {
  18735. var verticesRow = [];
  18736. var uvsRow = [];
  18737. var v = y / segmentsY;
  18738. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18739. for ( x = 0; x <= segmentsX; x ++ ) {
  18740. var u = x / segmentsX;
  18741. var vertex = new THREE.Vector3();
  18742. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18743. vertex.y = - v * height + heightHalf;
  18744. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18745. this.vertices.push( vertex );
  18746. verticesRow.push( this.vertices.length - 1 );
  18747. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18748. }
  18749. vertices.push( verticesRow );
  18750. uvs.push( uvsRow );
  18751. }
  18752. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18753. var na, nb;
  18754. for ( x = 0; x < segmentsX; x ++ ) {
  18755. if ( radiusTop !== 0 ) {
  18756. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18757. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18758. } else {
  18759. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18760. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18761. }
  18762. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18763. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18764. for ( y = 0; y < segmentsY; y ++ ) {
  18765. var v1 = vertices[ y ][ x ];
  18766. var v2 = vertices[ y + 1 ][ x ];
  18767. var v3 = vertices[ y + 1 ][ x + 1 ];
  18768. var v4 = vertices[ y ][ x + 1 ];
  18769. var n1 = na.clone();
  18770. var n2 = na.clone();
  18771. var n3 = nb.clone();
  18772. var n4 = nb.clone();
  18773. var uv1 = uvs[ y ][ x ].clone();
  18774. var uv2 = uvs[ y + 1 ][ x ].clone();
  18775. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18776. var uv4 = uvs[ y ][ x + 1 ].clone();
  18777. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18778. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18779. }
  18780. }
  18781. // top cap
  18782. if ( !openEnded && radiusTop > 0 ) {
  18783. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18784. for ( x = 0; x < segmentsX; x ++ ) {
  18785. var v1 = vertices[ 0 ][ x ];
  18786. var v2 = vertices[ 0 ][ x + 1 ];
  18787. var v3 = this.vertices.length - 1;
  18788. var n1 = new THREE.Vector3( 0, 1, 0 );
  18789. var n2 = new THREE.Vector3( 0, 1, 0 );
  18790. var n3 = new THREE.Vector3( 0, 1, 0 );
  18791. var uv1 = uvs[ 0 ][ x ].clone();
  18792. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18793. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18794. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18795. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18796. }
  18797. }
  18798. // bottom cap
  18799. if ( !openEnded && radiusBottom > 0 ) {
  18800. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18801. for ( x = 0; x < segmentsX; x ++ ) {
  18802. var v1 = vertices[ y ][ x + 1 ];
  18803. var v2 = vertices[ y ][ x ];
  18804. var v3 = this.vertices.length - 1;
  18805. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18806. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18807. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18808. var uv1 = uvs[ y ][ x + 1 ].clone();
  18809. var uv2 = uvs[ y ][ x ].clone();
  18810. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18811. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18812. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18813. }
  18814. }
  18815. this.computeCentroids();
  18816. this.computeFaceNormals();
  18817. }
  18818. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18819. /**
  18820. * @author zz85 / http://www.lab4games.net/zz85/blog
  18821. *
  18822. * Creates extruded geometry from a path shape.
  18823. *
  18824. * parameters = {
  18825. *
  18826. * size: <float>, // size of the text
  18827. * height: <float>, // thickness to extrude text
  18828. * curveSegments: <int>, // number of points on the curves
  18829. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18830. * amount: <int>, // Amount
  18831. *
  18832. * bevelEnabled: <bool>, // turn on bevel
  18833. * bevelThickness: <float>, // how deep into text bevel goes
  18834. * bevelSize: <float>, // how far from text outline is bevel
  18835. * bevelSegments: <int>, // number of bevel layers
  18836. *
  18837. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18838. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18839. *
  18840. * material: <int> // material index for front and back faces
  18841. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18842. * uvGenerator: <Object> // object that provides UV generator functions
  18843. *
  18844. * }
  18845. **/
  18846. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18847. if ( typeof( shapes ) === "undefined" ) {
  18848. shapes = [];
  18849. return;
  18850. }
  18851. THREE.Geometry.call( this );
  18852. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18853. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18854. this.addShapeList( shapes, options );
  18855. this.computeCentroids();
  18856. this.computeFaceNormals();
  18857. // can't really use automatic vertex normals
  18858. // as then front and back sides get smoothed too
  18859. // should do separate smoothing just for sides
  18860. //this.computeVertexNormals();
  18861. //console.log( "took", ( Date.now() - startTime ) );
  18862. };
  18863. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18864. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18865. var sl = shapes.length;
  18866. for ( var s = 0; s < sl; s ++ ) {
  18867. var shape = shapes[ s ];
  18868. this.addShape( shape, options );
  18869. }
  18870. };
  18871. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18872. var amount = options.amount !== undefined ? options.amount : 100;
  18873. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18874. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18875. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18876. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18877. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18878. var steps = options.steps !== undefined ? options.steps : 1;
  18879. var extrudePath = options.extrudePath;
  18880. var extrudePts, extrudeByPath = false;
  18881. var material = options.material;
  18882. var extrudeMaterial = options.extrudeMaterial;
  18883. // Use default WorldUVGenerator if no UV generators are specified.
  18884. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18885. var shapebb = this.shapebb;
  18886. //shapebb = shape.getBoundingBox();
  18887. var splineTube, binormal, normal, position2;
  18888. if ( extrudePath ) {
  18889. extrudePts = extrudePath.getSpacedPoints( steps );
  18890. extrudeByPath = true;
  18891. bevelEnabled = false; // bevels not supported for path extrusion
  18892. // SETUP TNB variables
  18893. // Reuse TNB from TubeGeomtry for now.
  18894. // TODO1 - have a .isClosed in spline?
  18895. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18896. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18897. binormal = new THREE.Vector3();
  18898. normal = new THREE.Vector3();
  18899. position2 = new THREE.Vector3();
  18900. }
  18901. // Safeguards if bevels are not enabled
  18902. if ( ! bevelEnabled ) {
  18903. bevelSegments = 0;
  18904. bevelThickness = 0;
  18905. bevelSize = 0;
  18906. }
  18907. // Variables initalization
  18908. var ahole, h, hl; // looping of holes
  18909. var scope = this;
  18910. var bevelPoints = [];
  18911. var shapesOffset = this.vertices.length;
  18912. var shapePoints = shape.extractPoints( curveSegments );
  18913. var vertices = shapePoints.shape;
  18914. var holes = shapePoints.holes;
  18915. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18916. if ( reverse ) {
  18917. vertices = vertices.reverse();
  18918. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18919. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18920. ahole = holes[ h ];
  18921. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18922. holes[ h ] = ahole.reverse();
  18923. }
  18924. }
  18925. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18926. }
  18927. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18928. /* Vertices */
  18929. var contour = vertices; // vertices has all points but contour has only points of circumference
  18930. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18931. ahole = holes[ h ];
  18932. vertices = vertices.concat( ahole );
  18933. }
  18934. function scalePt2 ( pt, vec, size ) {
  18935. if ( !vec ) console.log( "die" );
  18936. return vec.clone().multiplyScalar( size ).addSelf( pt );
  18937. }
  18938. var b, bs, t, z,
  18939. vert, vlen = vertices.length,
  18940. face, flen = faces.length,
  18941. cont, clen = contour.length;
  18942. // Find directions for point movement
  18943. var RAD_TO_DEGREES = 180 / Math.PI;
  18944. function getBevelVec( pt_i, pt_j, pt_k ) {
  18945. // Algorithm 2
  18946. return getBevelVec2( pt_i, pt_j, pt_k );
  18947. }
  18948. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18949. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18950. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18951. if ( anglea > angleb ) {
  18952. angleb += Math.PI * 2;
  18953. }
  18954. var anglec = ( anglea + angleb ) / 2;
  18955. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18956. var x = - Math.cos( anglec );
  18957. var y = - Math.sin( anglec );
  18958. var vec = new THREE.Vector2( x, y ); //.normalize();
  18959. return vec;
  18960. }
  18961. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18962. var a = THREE.ExtrudeGeometry.__v1,
  18963. b = THREE.ExtrudeGeometry.__v2,
  18964. v_hat = THREE.ExtrudeGeometry.__v3,
  18965. w_hat = THREE.ExtrudeGeometry.__v4,
  18966. p = THREE.ExtrudeGeometry.__v5,
  18967. q = THREE.ExtrudeGeometry.__v6,
  18968. v, w,
  18969. v_dot_w_hat, q_sub_p_dot_w_hat,
  18970. s, intersection;
  18971. // good reading for line-line intersection
  18972. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18973. // define a as vector j->i
  18974. // define b as vectot k->i
  18975. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18976. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18977. // get unit vectors
  18978. v = a.normalize();
  18979. w = b.normalize();
  18980. // normals from pt i
  18981. v_hat.set( -v.y, v.x );
  18982. w_hat.set( w.y, -w.x );
  18983. // pts from i
  18984. p.copy( pt_i ).addSelf( v_hat );
  18985. q.copy( pt_i ).addSelf( w_hat );
  18986. if ( p.equals( q ) ) {
  18987. //console.log("Warning: lines are straight");
  18988. return w_hat.clone();
  18989. }
  18990. // Points from j, k. helps prevents points cross overover most of the time
  18991. p.copy( pt_j ).addSelf( v_hat );
  18992. q.copy( pt_k ).addSelf( w_hat );
  18993. v_dot_w_hat = v.dot( w_hat );
  18994. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  18995. // We should not reach these conditions
  18996. if ( v_dot_w_hat === 0 ) {
  18997. console.log( "Either infinite or no solutions!" );
  18998. if ( q_sub_p_dot_w_hat === 0 ) {
  18999. console.log( "Its finite solutions." );
  19000. } else {
  19001. console.log( "Too bad, no solutions." );
  19002. }
  19003. }
  19004. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  19005. if ( s < 0 ) {
  19006. // in case of emergecy, revert to algorithm 1.
  19007. return getBevelVec1( pt_i, pt_j, pt_k );
  19008. }
  19009. intersection = v.multiplyScalar( s ).addSelf( p );
  19010. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  19011. }
  19012. var contourMovements = [];
  19013. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19014. if ( j === il ) j = 0;
  19015. if ( k === il ) k = 0;
  19016. // (j)---(i)---(k)
  19017. // console.log('i,j,k', i, j , k)
  19018. var pt_i = contour[ i ];
  19019. var pt_j = contour[ j ];
  19020. var pt_k = contour[ k ];
  19021. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19022. }
  19023. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19024. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19025. ahole = holes[ h ];
  19026. oneHoleMovements = [];
  19027. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19028. if ( j === il ) j = 0;
  19029. if ( k === il ) k = 0;
  19030. // (j)---(i)---(k)
  19031. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19032. }
  19033. holesMovements.push( oneHoleMovements );
  19034. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19035. }
  19036. // Loop bevelSegments, 1 for the front, 1 for the back
  19037. for ( b = 0; b < bevelSegments; b ++ ) {
  19038. //for ( b = bevelSegments; b > 0; b -- ) {
  19039. t = b / bevelSegments;
  19040. z = bevelThickness * ( 1 - t );
  19041. //z = bevelThickness * t;
  19042. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19043. //bs = bevelSize * t ; // linear
  19044. // contract shape
  19045. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19046. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19047. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19048. v( vert.x, vert.y, - z );
  19049. }
  19050. // expand holes
  19051. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19052. ahole = holes[ h ];
  19053. oneHoleMovements = holesMovements[ h ];
  19054. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19055. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19056. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19057. v( vert.x, vert.y, -z );
  19058. }
  19059. }
  19060. }
  19061. bs = bevelSize;
  19062. // Back facing vertices
  19063. for ( i = 0; i < vlen; i ++ ) {
  19064. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19065. if ( !extrudeByPath ) {
  19066. v( vert.x, vert.y, 0 );
  19067. } else {
  19068. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19069. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19070. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19071. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  19072. v( position2.x, position2.y, position2.z );
  19073. }
  19074. }
  19075. // Add stepped vertices...
  19076. // Including front facing vertices
  19077. var s;
  19078. for ( s = 1; s <= steps; s ++ ) {
  19079. for ( i = 0; i < vlen; i ++ ) {
  19080. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19081. if ( !extrudeByPath ) {
  19082. v( vert.x, vert.y, amount / steps * s );
  19083. } else {
  19084. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19085. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19086. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19087. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  19088. v( position2.x, position2.y, position2.z );
  19089. }
  19090. }
  19091. }
  19092. // Add bevel segments planes
  19093. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19094. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19095. t = b / bevelSegments;
  19096. z = bevelThickness * ( 1 - t );
  19097. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19098. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19099. // contract shape
  19100. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19101. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19102. v( vert.x, vert.y, amount + z );
  19103. }
  19104. // expand holes
  19105. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19106. ahole = holes[ h ];
  19107. oneHoleMovements = holesMovements[ h ];
  19108. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19109. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19110. if ( !extrudeByPath ) {
  19111. v( vert.x, vert.y, amount + z );
  19112. } else {
  19113. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19114. }
  19115. }
  19116. }
  19117. }
  19118. /* Faces */
  19119. // Top and bottom faces
  19120. buildLidFaces();
  19121. // Sides faces
  19122. buildSideFaces();
  19123. ///// Internal functions
  19124. function buildLidFaces() {
  19125. if ( bevelEnabled ) {
  19126. var layer = 0 ; // steps + 1
  19127. var offset = vlen * layer;
  19128. // Bottom faces
  19129. for ( i = 0; i < flen; i ++ ) {
  19130. face = faces[ i ];
  19131. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19132. }
  19133. layer = steps + bevelSegments * 2;
  19134. offset = vlen * layer;
  19135. // Top faces
  19136. for ( i = 0; i < flen; i ++ ) {
  19137. face = faces[ i ];
  19138. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19139. }
  19140. } else {
  19141. // Bottom faces
  19142. for ( i = 0; i < flen; i++ ) {
  19143. face = faces[ i ];
  19144. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19145. }
  19146. // Top faces
  19147. for ( i = 0; i < flen; i ++ ) {
  19148. face = faces[ i ];
  19149. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19150. }
  19151. }
  19152. }
  19153. // Create faces for the z-sides of the shape
  19154. function buildSideFaces() {
  19155. var layeroffset = 0;
  19156. sidewalls( contour, layeroffset );
  19157. layeroffset += contour.length;
  19158. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19159. ahole = holes[ h ];
  19160. sidewalls( ahole, layeroffset );
  19161. //, true
  19162. layeroffset += ahole.length;
  19163. }
  19164. }
  19165. function sidewalls( contour, layeroffset ) {
  19166. var j, k;
  19167. i = contour.length;
  19168. while ( --i >= 0 ) {
  19169. j = i;
  19170. k = i - 1;
  19171. if ( k < 0 ) k = contour.length - 1;
  19172. //console.log('b', i,j, i-1, k,vertices.length);
  19173. var s = 0, sl = steps + bevelSegments * 2;
  19174. for ( s = 0; s < sl; s ++ ) {
  19175. var slen1 = vlen * s;
  19176. var slen2 = vlen * ( s + 1 );
  19177. var a = layeroffset + j + slen1,
  19178. b = layeroffset + k + slen1,
  19179. c = layeroffset + k + slen2,
  19180. d = layeroffset + j + slen2;
  19181. f4( a, b, c, d, contour, s, sl, j, k );
  19182. }
  19183. }
  19184. }
  19185. function v( x, y, z ) {
  19186. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19187. }
  19188. function f3( a, b, c, isBottom ) {
  19189. a += shapesOffset;
  19190. b += shapesOffset;
  19191. c += shapesOffset;
  19192. // normal, color, material
  19193. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19194. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19195. scope.faceVertexUvs[ 0 ].push( uvs );
  19196. }
  19197. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19198. a += shapesOffset;
  19199. b += shapesOffset;
  19200. c += shapesOffset;
  19201. d += shapesOffset;
  19202. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19203. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19204. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19205. scope.faceVertexUvs[ 0 ].push( uvs );
  19206. }
  19207. };
  19208. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19209. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19210. var ax = geometry.vertices[ indexA ].x,
  19211. ay = geometry.vertices[ indexA ].y,
  19212. bx = geometry.vertices[ indexB ].x,
  19213. by = geometry.vertices[ indexB ].y,
  19214. cx = geometry.vertices[ indexC ].x,
  19215. cy = geometry.vertices[ indexC ].y;
  19216. return [
  19217. new THREE.Vector2( ax, ay ),
  19218. new THREE.Vector2( bx, by ),
  19219. new THREE.Vector2( cx, cy )
  19220. ];
  19221. },
  19222. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19223. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19224. },
  19225. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19226. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19227. contourIndex1, contourIndex2 ) {
  19228. var ax = geometry.vertices[ indexA ].x,
  19229. ay = geometry.vertices[ indexA ].y,
  19230. az = geometry.vertices[ indexA ].z,
  19231. bx = geometry.vertices[ indexB ].x,
  19232. by = geometry.vertices[ indexB ].y,
  19233. bz = geometry.vertices[ indexB ].z,
  19234. cx = geometry.vertices[ indexC ].x,
  19235. cy = geometry.vertices[ indexC ].y,
  19236. cz = geometry.vertices[ indexC ].z,
  19237. dx = geometry.vertices[ indexD ].x,
  19238. dy = geometry.vertices[ indexD ].y,
  19239. dz = geometry.vertices[ indexD ].z;
  19240. if ( Math.abs( ay - by ) < 0.01 ) {
  19241. return [
  19242. new THREE.Vector2( ax, 1 - az ),
  19243. new THREE.Vector2( bx, 1 - bz ),
  19244. new THREE.Vector2( cx, 1 - cz ),
  19245. new THREE.Vector2( dx, 1 - dz )
  19246. ];
  19247. } else {
  19248. return [
  19249. new THREE.Vector2( ay, 1 - az ),
  19250. new THREE.Vector2( by, 1 - bz ),
  19251. new THREE.Vector2( cy, 1 - cz ),
  19252. new THREE.Vector2( dy, 1 - dz )
  19253. ];
  19254. }
  19255. }
  19256. };
  19257. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19258. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19259. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19260. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19261. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19262. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19263. /**
  19264. * @author jonobr1 / http://jonobr1.com
  19265. *
  19266. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19267. * ExtrudeGeometry.
  19268. *
  19269. * parameters = {
  19270. *
  19271. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19272. *
  19273. * material: <int> // material index for front and back faces
  19274. * uvGenerator: <Object> // object that provides UV generator functions
  19275. *
  19276. * }
  19277. **/
  19278. THREE.ShapeGeometry = function ( shapes, options ) {
  19279. THREE.Geometry.call( this );
  19280. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19281. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19282. this.addShapeList( shapes, options );
  19283. this.computeCentroids();
  19284. this.computeFaceNormals();
  19285. };
  19286. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19287. /**
  19288. * Add an array of shapes to THREE.ShapeGeometry.
  19289. */
  19290. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19291. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19292. this.addShape( shapes[ i ], options );
  19293. }
  19294. return this;
  19295. };
  19296. /**
  19297. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19298. */
  19299. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19300. if ( options === undefined ) options = {};
  19301. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19302. var material = options.material;
  19303. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19304. var shapebb = this.shapebb;
  19305. //
  19306. var i, l, hole, s;
  19307. var shapesOffset = this.vertices.length;
  19308. var shapePoints = shape.extractPoints( curveSegments );
  19309. var vertices = shapePoints.shape;
  19310. var holes = shapePoints.holes;
  19311. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19312. if ( reverse ) {
  19313. vertices = vertices.reverse();
  19314. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19315. for ( i = 0, l = holes.length; i < l; i++ ) {
  19316. hole = holes[ i ];
  19317. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19318. holes[ i ] = hole.reverse();
  19319. }
  19320. }
  19321. reverse = false;
  19322. }
  19323. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19324. // Vertices
  19325. var contour = vertices;
  19326. for ( i = 0, l = holes.length; i < l; i++ ) {
  19327. hole = holes[ i ];
  19328. vertices = vertices.concat( hole );
  19329. }
  19330. //
  19331. var vert, vlen = vertices.length;
  19332. var face, flen = faces.length;
  19333. var cont, clen = contour.length;
  19334. for ( i = 0; i < vlen; i++ ) {
  19335. vert = vertices[ i ];
  19336. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19337. }
  19338. for ( i = 0; i < flen; i++ ) {
  19339. face = faces[ i ];
  19340. var a = face[ 0 ] + shapesOffset;
  19341. var b = face[ 1 ] + shapesOffset;
  19342. var c = face[ 2 ] + shapesOffset;
  19343. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19344. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19345. }
  19346. };
  19347. /**
  19348. * @author astrodud / http://astrodud.isgreat.org/
  19349. * @author zz85 / https://github.com/zz85
  19350. */
  19351. THREE.LatheGeometry = function ( points, steps, angle ) {
  19352. THREE.Geometry.call( this );
  19353. var _steps = steps || 12;
  19354. var _angle = angle || 2 * Math.PI;
  19355. var _newV = [];
  19356. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  19357. for ( var j = 0; j < points.length; j ++ ) {
  19358. _newV[ j ] = points[ j ].clone();
  19359. this.vertices.push( _newV[ j ] );
  19360. }
  19361. var i, il = _steps + 1;
  19362. for ( i = 0; i < il; i ++ ) {
  19363. for ( var j = 0; j < _newV.length; j ++ ) {
  19364. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  19365. this.vertices.push( _newV[ j ] );
  19366. }
  19367. }
  19368. for ( i = 0; i < _steps; i ++ ) {
  19369. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  19370. var a = i * kl + k;
  19371. var b = ( ( i + 1 ) % il ) * kl + k;
  19372. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  19373. var d = i * kl + ( k + 1 ) % kl;
  19374. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19375. this.faceVertexUvs[ 0 ].push( [
  19376. new THREE.Vector2( 1 - i / _steps, k / kl ),
  19377. new THREE.Vector2( 1 - ( i + 1 ) / _steps, k / kl ),
  19378. new THREE.Vector2( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  19379. new THREE.Vector2( 1 - i / _steps, ( k + 1 ) / kl )
  19380. ] );
  19381. }
  19382. }
  19383. this.computeCentroids();
  19384. this.computeFaceNormals();
  19385. this.computeVertexNormals();
  19386. };
  19387. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19388. /**
  19389. * @author mrdoob / http://mrdoob.com/
  19390. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19391. */
  19392. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19393. THREE.Geometry.call( this );
  19394. this.width = width;
  19395. this.height = height;
  19396. this.widthSegments = widthSegments || 1;
  19397. this.heightSegments = heightSegments || 1;
  19398. var ix, iz;
  19399. var width_half = width / 2;
  19400. var height_half = height / 2;
  19401. var gridX = this.widthSegments;
  19402. var gridZ = this.heightSegments;
  19403. var gridX1 = gridX + 1;
  19404. var gridZ1 = gridZ + 1;
  19405. var segment_width = this.width / gridX;
  19406. var segment_height = this.height / gridZ;
  19407. var normal = new THREE.Vector3( 0, 0, 1 );
  19408. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19409. for ( ix = 0; ix < gridX1; ix ++ ) {
  19410. var x = ix * segment_width - width_half;
  19411. var y = iz * segment_height - height_half;
  19412. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19413. }
  19414. }
  19415. for ( iz = 0; iz < gridZ; iz ++ ) {
  19416. for ( ix = 0; ix < gridX; ix ++ ) {
  19417. var a = ix + gridX1 * iz;
  19418. var b = ix + gridX1 * ( iz + 1 );
  19419. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19420. var d = ( ix + 1 ) + gridX1 * iz;
  19421. var face = new THREE.Face4( a, b, c, d );
  19422. face.normal.copy( normal );
  19423. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19424. this.faces.push( face );
  19425. this.faceVertexUvs[ 0 ].push( [
  19426. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19427. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19428. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19429. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19430. ] );
  19431. }
  19432. }
  19433. this.computeCentroids();
  19434. };
  19435. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19436. /**
  19437. * @author mrdoob / http://mrdoob.com/
  19438. */
  19439. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19440. THREE.Geometry.call( this );
  19441. this.radius = radius || 50;
  19442. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19443. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19444. phiStart = phiStart !== undefined ? phiStart : 0;
  19445. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19446. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19447. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19448. var x, y, vertices = [], uvs = [];
  19449. for ( y = 0; y <= this.heightSegments; y ++ ) {
  19450. var verticesRow = [];
  19451. var uvsRow = [];
  19452. for ( x = 0; x <= this.widthSegments; x ++ ) {
  19453. var u = x / this.widthSegments;
  19454. var v = y / this.heightSegments;
  19455. var vertex = new THREE.Vector3();
  19456. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19457. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  19458. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19459. this.vertices.push( vertex );
  19460. verticesRow.push( this.vertices.length - 1 );
  19461. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19462. }
  19463. vertices.push( verticesRow );
  19464. uvs.push( uvsRow );
  19465. }
  19466. for ( y = 0; y < this.heightSegments; y ++ ) {
  19467. for ( x = 0; x < this.widthSegments; x ++ ) {
  19468. var v1 = vertices[ y ][ x + 1 ];
  19469. var v2 = vertices[ y ][ x ];
  19470. var v3 = vertices[ y + 1 ][ x ];
  19471. var v4 = vertices[ y + 1 ][ x + 1 ];
  19472. var n1 = this.vertices[ v1 ].clone().normalize();
  19473. var n2 = this.vertices[ v2 ].clone().normalize();
  19474. var n3 = this.vertices[ v3 ].clone().normalize();
  19475. var n4 = this.vertices[ v4 ].clone().normalize();
  19476. var uv1 = uvs[ y ][ x + 1 ].clone();
  19477. var uv2 = uvs[ y ][ x ].clone();
  19478. var uv3 = uvs[ y + 1 ][ x ].clone();
  19479. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19480. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19481. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19482. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19483. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19484. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19485. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19486. } else {
  19487. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19488. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19489. }
  19490. }
  19491. }
  19492. this.computeCentroids();
  19493. this.computeFaceNormals();
  19494. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19495. };
  19496. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19497. /**
  19498. * @author zz85 / http://www.lab4games.net/zz85/blog
  19499. * @author alteredq / http://alteredqualia.com/
  19500. *
  19501. * For creating 3D text geometry in three.js
  19502. *
  19503. * Text = 3D Text
  19504. *
  19505. * parameters = {
  19506. * size: <float>, // size of the text
  19507. * height: <float>, // thickness to extrude text
  19508. * curveSegments: <int>, // number of points on the curves
  19509. *
  19510. * font: <string>, // font name
  19511. * weight: <string>, // font weight (normal, bold)
  19512. * style: <string>, // font style (normal, italics)
  19513. *
  19514. * bevelEnabled: <bool>, // turn on bevel
  19515. * bevelThickness: <float>, // how deep into text bevel goes
  19516. * bevelSize: <float>, // how far from text outline is bevel
  19517. * }
  19518. *
  19519. */
  19520. /* Usage Examples
  19521. // TextGeometry wrapper
  19522. var text3d = new TextGeometry( text, options );
  19523. // Complete manner
  19524. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19525. var text3d = new ExtrudeGeometry( textShapes, options );
  19526. */
  19527. THREE.TextGeometry = function ( text, parameters ) {
  19528. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19529. // translate parameters to ExtrudeGeometry API
  19530. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19531. // defaults
  19532. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19533. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19534. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19535. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19536. };
  19537. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19538. /**
  19539. * @author oosmoxiecode
  19540. * @author mrdoob / http://mrdoob.com/
  19541. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19542. */
  19543. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19544. THREE.Geometry.call( this );
  19545. var scope = this;
  19546. this.radius = radius || 100;
  19547. this.tube = tube || 40;
  19548. this.radialSegments = radialSegments || 8;
  19549. this.tubularSegments = tubularSegments || 6;
  19550. this.arc = arc || Math.PI * 2;
  19551. var center = new THREE.Vector3(), uvs = [], normals = [];
  19552. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19553. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19554. var u = i / this.tubularSegments * this.arc;
  19555. var v = j / this.radialSegments * Math.PI * 2;
  19556. center.x = this.radius * Math.cos( u );
  19557. center.y = this.radius * Math.sin( u );
  19558. var vertex = new THREE.Vector3();
  19559. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19560. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19561. vertex.z = this.tube * Math.sin( v );
  19562. this.vertices.push( vertex );
  19563. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19564. normals.push( vertex.clone().subSelf( center ).normalize() );
  19565. }
  19566. }
  19567. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19568. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19569. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19570. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19571. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19572. var d = ( this.tubularSegments + 1 ) * j + i;
  19573. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19574. face.normal.addSelf( normals[ a ] );
  19575. face.normal.addSelf( normals[ b ] );
  19576. face.normal.addSelf( normals[ c ] );
  19577. face.normal.addSelf( normals[ d ] );
  19578. face.normal.normalize();
  19579. this.faces.push( face );
  19580. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19581. }
  19582. }
  19583. this.computeCentroids();
  19584. };
  19585. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19586. /**
  19587. * @author oosmoxiecode
  19588. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19589. */
  19590. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19591. THREE.Geometry.call( this );
  19592. var scope = this;
  19593. this.radius = radius || 100;
  19594. this.tube = tube || 40;
  19595. this.radialSegments = radialSegments || 64;
  19596. this.tubularSegments = tubularSegments || 8;
  19597. this.p = p || 2;
  19598. this.q = q || 3;
  19599. this.heightScale = heightScale || 1;
  19600. this.grid = new Array( this.radialSegments );
  19601. var tang = new THREE.Vector3();
  19602. var n = new THREE.Vector3();
  19603. var bitan = new THREE.Vector3();
  19604. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19605. this.grid[ i ] = new Array( this.tubularSegments );
  19606. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19607. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19608. var v = j / this.tubularSegments * 2 * Math.PI;
  19609. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19610. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19611. var cx, cy;
  19612. tang.sub( p2, p1 );
  19613. n.add( p2, p1 );
  19614. bitan.cross( tang, n );
  19615. n.cross( bitan, tang );
  19616. bitan.normalize();
  19617. n.normalize();
  19618. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19619. cy = this.tube * Math.sin( v );
  19620. p1.x += cx * n.x + cy * bitan.x;
  19621. p1.y += cx * n.y + cy * bitan.y;
  19622. p1.z += cx * n.z + cy * bitan.z;
  19623. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19624. }
  19625. }
  19626. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19627. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19628. var ip = ( i + 1 ) % this.radialSegments;
  19629. var jp = ( j + 1 ) % this.tubularSegments;
  19630. var a = this.grid[ i ][ j ];
  19631. var b = this.grid[ ip ][ j ];
  19632. var c = this.grid[ ip ][ jp ];
  19633. var d = this.grid[ i ][ jp ];
  19634. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19635. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19636. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19637. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19638. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19639. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19640. }
  19641. }
  19642. this.computeCentroids();
  19643. this.computeFaceNormals();
  19644. this.computeVertexNormals();
  19645. function vert( x, y, z ) {
  19646. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19647. }
  19648. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19649. var cu = Math.cos( u );
  19650. var cv = Math.cos( v );
  19651. var su = Math.sin( u );
  19652. var quOverP = in_q / in_p * u;
  19653. var cs = Math.cos( quOverP );
  19654. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19655. var ty = radius * ( 2 + cs ) * su * 0.5;
  19656. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19657. return new THREE.Vector3( tx, ty, tz );
  19658. }
  19659. };
  19660. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19661. /**
  19662. * @author WestLangley / https://github.com/WestLangley
  19663. * @author zz85 / https://github.com/zz85
  19664. * @author miningold / https://github.com/miningold
  19665. *
  19666. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19667. *
  19668. * Creates a tube which extrudes along a 3d spline
  19669. *
  19670. * Uses parallel transport frames as described in
  19671. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19672. */
  19673. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19674. THREE.Geometry.call( this );
  19675. this.path = path;
  19676. this.segments = segments || 64;
  19677. this.radius = radius || 1;
  19678. this.radiusSegments = radiusSegments || 8;
  19679. this.closed = closed || false;
  19680. if ( debug ) this.debug = new THREE.Object3D();
  19681. this.grid = [];
  19682. var scope = this,
  19683. tangent,
  19684. normal,
  19685. binormal,
  19686. numpoints = this.segments + 1,
  19687. x, y, z,
  19688. tx, ty, tz,
  19689. u, v,
  19690. cx, cy,
  19691. pos, pos2 = new THREE.Vector3(),
  19692. i, j,
  19693. ip, jp,
  19694. a, b, c, d,
  19695. uva, uvb, uvc, uvd;
  19696. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19697. tangents = frames.tangents,
  19698. normals = frames.normals,
  19699. binormals = frames.binormals;
  19700. // proxy internals
  19701. this.tangents = tangents;
  19702. this.normals = normals;
  19703. this.binormals = binormals;
  19704. function vert( x, y, z ) {
  19705. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19706. }
  19707. // consruct the grid
  19708. for ( i = 0; i < numpoints; i++ ) {
  19709. this.grid[ i ] = [];
  19710. u = i / ( numpoints - 1 );
  19711. pos = path.getPointAt( u );
  19712. tangent = tangents[ i ];
  19713. normal = normals[ i ];
  19714. binormal = binormals[ i ];
  19715. if ( this.debug ) {
  19716. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19717. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19718. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19719. }
  19720. for ( j = 0; j < this.radiusSegments; j++ ) {
  19721. v = j / this.radiusSegments * 2 * Math.PI;
  19722. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19723. cy = this.radius * Math.sin( v );
  19724. pos2.copy( pos );
  19725. pos2.x += cx * normal.x + cy * binormal.x;
  19726. pos2.y += cx * normal.y + cy * binormal.y;
  19727. pos2.z += cx * normal.z + cy * binormal.z;
  19728. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19729. }
  19730. }
  19731. // construct the mesh
  19732. for ( i = 0; i < this.segments; i++ ) {
  19733. for ( j = 0; j < this.radiusSegments; j++ ) {
  19734. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19735. jp = (j + 1) % this.radiusSegments;
  19736. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19737. b = this.grid[ ip ][ j ];
  19738. c = this.grid[ ip ][ jp ];
  19739. d = this.grid[ i ][ jp ];
  19740. uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
  19741. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19742. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19743. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19744. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19745. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19746. }
  19747. }
  19748. this.computeCentroids();
  19749. this.computeFaceNormals();
  19750. this.computeVertexNormals();
  19751. };
  19752. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19753. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19754. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19755. var tangent = new THREE.Vector3(),
  19756. normal = new THREE.Vector3(),
  19757. binormal = new THREE.Vector3(),
  19758. tangents = [],
  19759. normals = [],
  19760. binormals = [],
  19761. vec = new THREE.Vector3(),
  19762. mat = new THREE.Matrix4(),
  19763. numpoints = segments + 1,
  19764. theta,
  19765. epsilon = 0.0001,
  19766. smallest,
  19767. tx, ty, tz,
  19768. i, u, v;
  19769. // expose internals
  19770. this.tangents = tangents;
  19771. this.normals = normals;
  19772. this.binormals = binormals;
  19773. // compute the tangent vectors for each segment on the path
  19774. for ( i = 0; i < numpoints; i++ ) {
  19775. u = i / ( numpoints - 1 );
  19776. tangents[ i ] = path.getTangentAt( u );
  19777. tangents[ i ].normalize();
  19778. }
  19779. initialNormal3();
  19780. function initialNormal1(lastBinormal) {
  19781. // fixed start binormal. Has dangers of 0 vectors
  19782. normals[ 0 ] = new THREE.Vector3();
  19783. binormals[ 0 ] = new THREE.Vector3();
  19784. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19785. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  19786. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  19787. }
  19788. function initialNormal2() {
  19789. // This uses the Frenet-Serret formula for deriving binormal
  19790. var t2 = path.getTangentAt( epsilon );
  19791. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  19792. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  19793. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19794. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  19795. }
  19796. function initialNormal3() {
  19797. // select an initial normal vector perpenicular to the first tangent vector,
  19798. // and in the direction of the smallest tangent xyz component
  19799. normals[ 0 ] = new THREE.Vector3();
  19800. binormals[ 0 ] = new THREE.Vector3();
  19801. smallest = Number.MAX_VALUE;
  19802. tx = Math.abs( tangents[ 0 ].x );
  19803. ty = Math.abs( tangents[ 0 ].y );
  19804. tz = Math.abs( tangents[ 0 ].z );
  19805. if ( tx <= smallest ) {
  19806. smallest = tx;
  19807. normal.set( 1, 0, 0 );
  19808. }
  19809. if ( ty <= smallest ) {
  19810. smallest = ty;
  19811. normal.set( 0, 1, 0 );
  19812. }
  19813. if ( tz <= smallest ) {
  19814. normal.set( 0, 0, 1 );
  19815. }
  19816. vec.cross( tangents[ 0 ], normal ).normalize();
  19817. normals[ 0 ].cross( tangents[ 0 ], vec );
  19818. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  19819. }
  19820. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19821. for ( i = 1; i < numpoints; i++ ) {
  19822. normals[ i ] = normals[ i-1 ].clone();
  19823. binormals[ i ] = binormals[ i-1 ].clone();
  19824. vec.cross( tangents[ i-1 ], tangents[ i ] );
  19825. if ( vec.length() > epsilon ) {
  19826. vec.normalize();
  19827. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19828. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  19829. }
  19830. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19831. }
  19832. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19833. if ( closed ) {
  19834. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19835. theta /= ( numpoints - 1 );
  19836. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19837. theta = -theta;
  19838. }
  19839. for ( i = 1; i < numpoints; i++ ) {
  19840. // twist a little...
  19841. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  19842. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19843. }
  19844. }
  19845. };
  19846. /**
  19847. * @author clockworkgeek / https://github.com/clockworkgeek
  19848. * @author timothypratley / https://github.com/timothypratley
  19849. */
  19850. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19851. THREE.Geometry.call( this );
  19852. radius = radius || 1;
  19853. detail = detail || 0;
  19854. var that = this;
  19855. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19856. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19857. }
  19858. var midpoints = [], p = this.vertices;
  19859. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19860. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19861. }
  19862. this.mergeVertices();
  19863. // Apply radius
  19864. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19865. this.vertices[ i ].multiplyScalar( radius );
  19866. }
  19867. // Project vector onto sphere's surface
  19868. function prepare( vector ) {
  19869. var vertex = vector.normalize().clone();
  19870. vertex.index = that.vertices.push( vertex ) - 1;
  19871. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19872. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19873. var v = inclination( vector ) / Math.PI + 0.5;
  19874. vertex.uv = new THREE.Vector2( u, 1 - v );
  19875. return vertex;
  19876. }
  19877. // Approximate a curved face with recursively sub-divided triangles.
  19878. function make( v1, v2, v3, detail ) {
  19879. if ( detail < 1 ) {
  19880. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19881. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  19882. face.normal = face.centroid.clone().normalize();
  19883. that.faces.push( face );
  19884. var azi = azimuth( face.centroid );
  19885. that.faceVertexUvs[ 0 ].push( [
  19886. correctUV( v1.uv, v1, azi ),
  19887. correctUV( v2.uv, v2, azi ),
  19888. correctUV( v3.uv, v3, azi )
  19889. ] );
  19890. } else {
  19891. detail -= 1;
  19892. // split triangle into 4 smaller triangles
  19893. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19894. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19895. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19896. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19897. }
  19898. }
  19899. function midpoint( v1, v2 ) {
  19900. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19901. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19902. var mid = midpoints[ v1.index ][ v2.index ];
  19903. if ( mid === undefined ) {
  19904. // generate mean point and project to surface with prepare()
  19905. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19906. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  19907. );
  19908. }
  19909. return mid;
  19910. }
  19911. // Angle around the Y axis, counter-clockwise when looking from above.
  19912. function azimuth( vector ) {
  19913. return Math.atan2( vector.z, -vector.x );
  19914. }
  19915. // Angle above the XZ plane.
  19916. function inclination( vector ) {
  19917. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19918. }
  19919. // Texture fixing helper. Spheres have some odd behaviours.
  19920. function correctUV( uv, vector, azimuth ) {
  19921. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19922. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19923. return uv;
  19924. }
  19925. this.computeCentroids();
  19926. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19927. };
  19928. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19929. /**
  19930. * @author timothypratley / https://github.com/timothypratley
  19931. */
  19932. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19933. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19934. var vertices = [
  19935. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19936. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19937. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19938. ];
  19939. var faces = [
  19940. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19941. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19942. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19943. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19944. ];
  19945. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19946. };
  19947. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19948. /**
  19949. * @author timothypratley / https://github.com/timothypratley
  19950. */
  19951. THREE.OctahedronGeometry = function ( radius, detail ) {
  19952. var vertices = [
  19953. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19954. ];
  19955. var faces = [
  19956. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19957. ];
  19958. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19959. };
  19960. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19961. /**
  19962. * @author timothypratley / https://github.com/timothypratley
  19963. */
  19964. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19965. var vertices = [
  19966. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19967. ];
  19968. var faces = [
  19969. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19970. ];
  19971. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19972. };
  19973. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19974. /**
  19975. * @author zz85 / https://github.com/zz85
  19976. * Parametric Surfaces Geometry
  19977. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19978. *
  19979. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19980. *
  19981. */
  19982. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19983. THREE.Geometry.call( this );
  19984. var verts = this.vertices;
  19985. var faces = this.faces;
  19986. var uvs = this.faceVertexUvs[ 0 ];
  19987. useTris = (useTris === undefined) ? false : useTris;
  19988. var i, il, j, p;
  19989. var u, v;
  19990. var stackCount = stacks + 1;
  19991. var sliceCount = slices + 1;
  19992. for ( i = 0; i <= stacks; i ++ ) {
  19993. v = i / stacks;
  19994. for ( j = 0; j <= slices; j ++ ) {
  19995. u = j / slices;
  19996. p = func( u, v );
  19997. verts.push( p );
  19998. }
  19999. }
  20000. var a, b, c, d;
  20001. var uva, uvb, uvc, uvd;
  20002. for ( i = 0; i < stacks; i ++ ) {
  20003. for ( j = 0; j < slices; j ++ ) {
  20004. a = i * sliceCount + j;
  20005. b = i * sliceCount + j + 1;
  20006. c = (i + 1) * sliceCount + j;
  20007. d = (i + 1) * sliceCount + j + 1;
  20008. uva = new THREE.Vector2( j / slices, i / stacks );
  20009. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20010. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20011. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20012. if ( useTris ) {
  20013. faces.push( new THREE.Face3( a, b, c ) );
  20014. faces.push( new THREE.Face3( b, d, c ) );
  20015. uvs.push( [ uva, uvb, uvc ] );
  20016. uvs.push( [ uvb, uvd, uvc ] );
  20017. } else {
  20018. faces.push( new THREE.Face4( a, b, d, c ) );
  20019. uvs.push( [ uva, uvb, uvd, uvc ] );
  20020. }
  20021. }
  20022. }
  20023. // console.log(this);
  20024. // magic bullet
  20025. // var diff = this.mergeVertices();
  20026. // console.log('removed ', diff, ' vertices by merging');
  20027. this.computeCentroids();
  20028. this.computeFaceNormals();
  20029. this.computeVertexNormals();
  20030. };
  20031. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20032. /**
  20033. * @author qiao / https://github.com/qiao
  20034. * @fileoverview This is a convex hull generator using the incremental method.
  20035. * The complexity is O(n^2) where n is the number of vertices.
  20036. * O(nlogn) algorithms do exist, but they are much more complicated.
  20037. *
  20038. * Benchmark:
  20039. *
  20040. * Platform: CPU: P7350 @2.00GHz Engine: V8
  20041. *
  20042. * Num Vertices Time(ms)
  20043. *
  20044. * 10 1
  20045. * 20 3
  20046. * 30 19
  20047. * 40 48
  20048. * 50 107
  20049. */
  20050. THREE.ConvexGeometry = function( vertices ) {
  20051. THREE.Geometry.call( this );
  20052. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  20053. for ( var i = 3; i < vertices.length; i++ ) {
  20054. addPoint( i );
  20055. }
  20056. function addPoint( vertexId ) {
  20057. var vertex = vertices[ vertexId ].clone();
  20058. var mag = vertex.length();
  20059. vertex.x += mag * randomOffset();
  20060. vertex.y += mag * randomOffset();
  20061. vertex.z += mag * randomOffset();
  20062. var hole = [];
  20063. for ( var f = 0; f < faces.length; ) {
  20064. var face = faces[ f ];
  20065. // for each face, if the vertex can see it,
  20066. // then we try to add the face's edges into the hole.
  20067. if ( visible( face, vertex ) ) {
  20068. for ( var e = 0; e < 3; e++ ) {
  20069. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  20070. var boundary = true;
  20071. // remove duplicated edges.
  20072. for ( var h = 0; h < hole.length; h++ ) {
  20073. if ( equalEdge( hole[ h ], edge ) ) {
  20074. hole[ h ] = hole[ hole.length - 1 ];
  20075. hole.pop();
  20076. boundary = false;
  20077. break;
  20078. }
  20079. }
  20080. if ( boundary ) {
  20081. hole.push( edge );
  20082. }
  20083. }
  20084. // remove faces[ f ]
  20085. faces[ f ] = faces[ faces.length - 1 ];
  20086. faces.pop();
  20087. } else { // not visible
  20088. f++;
  20089. }
  20090. }
  20091. // construct the new faces formed by the edges of the hole and the vertex
  20092. for ( var h = 0; h < hole.length; h++ ) {
  20093. faces.push( [
  20094. hole[ h ][ 0 ],
  20095. hole[ h ][ 1 ],
  20096. vertexId
  20097. ] );
  20098. }
  20099. }
  20100. /**
  20101. * Whether the face is visible from the vertex
  20102. */
  20103. function visible( face, vertex ) {
  20104. var va = vertices[ face[ 0 ] ];
  20105. var vb = vertices[ face[ 1 ] ];
  20106. var vc = vertices[ face[ 2 ] ];
  20107. var n = normal( va, vb, vc );
  20108. // distance from face to origin
  20109. var dist = n.dot( va );
  20110. return n.dot( vertex ) >= dist;
  20111. }
  20112. /**
  20113. * Face normal
  20114. */
  20115. function normal( va, vb, vc ) {
  20116. var cb = new THREE.Vector3();
  20117. var ab = new THREE.Vector3();
  20118. cb.sub( vc, vb );
  20119. ab.sub( va, vb );
  20120. cb.crossSelf( ab );
  20121. cb.normalize();
  20122. return cb;
  20123. }
  20124. /**
  20125. * Detect whether two edges are equal.
  20126. * Note that when constructing the convex hull, two same edges can only
  20127. * be of the negative direction.
  20128. */
  20129. function equalEdge( ea, eb ) {
  20130. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20131. }
  20132. /**
  20133. * Create a random offset between -1e-6 and 1e-6.
  20134. */
  20135. function randomOffset() {
  20136. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20137. }
  20138. /**
  20139. * XXX: Not sure if this is the correct approach. Need someone to review.
  20140. */
  20141. function vertexUv( vertex ) {
  20142. var mag = vertex.length();
  20143. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  20144. }
  20145. // Push vertices into `this.vertices`, skipping those inside the hull
  20146. var id = 0;
  20147. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20148. for ( var i = 0; i < faces.length; i++ ) {
  20149. var face = faces[ i ];
  20150. for ( var j = 0; j < 3; j++ ) {
  20151. if ( newId[ face[ j ] ] === undefined ) {
  20152. newId[ face[ j ] ] = id++;
  20153. this.vertices.push( vertices[ face[ j ] ] );
  20154. }
  20155. face[ j ] = newId[ face[ j ] ];
  20156. }
  20157. }
  20158. // Convert faces into instances of THREE.Face3
  20159. for ( var i = 0; i < faces.length; i++ ) {
  20160. this.faces.push( new THREE.Face3(
  20161. faces[ i ][ 0 ],
  20162. faces[ i ][ 1 ],
  20163. faces[ i ][ 2 ]
  20164. ) );
  20165. }
  20166. // Compute UVs
  20167. for ( var i = 0; i < this.faces.length; i++ ) {
  20168. var face = this.faces[ i ];
  20169. this.faceVertexUvs[ 0 ].push( [
  20170. vertexUv( this.vertices[ face.a ] ),
  20171. vertexUv( this.vertices[ face.b ] ),
  20172. vertexUv( this.vertices[ face.c ])
  20173. ] );
  20174. }
  20175. this.computeCentroids();
  20176. this.computeFaceNormals();
  20177. this.computeVertexNormals();
  20178. };
  20179. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20180. /**
  20181. * @author sroucheray / http://sroucheray.org/
  20182. * @author mrdoob / http://mrdoob.com/
  20183. */
  20184. THREE.AxisHelper = function ( size ) {
  20185. var geometry = new THREE.Geometry();
  20186. geometry.vertices.push(
  20187. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  20188. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  20189. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  20190. );
  20191. geometry.colors.push(
  20192. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20193. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20194. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20195. );
  20196. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20197. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20198. };
  20199. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20200. /**
  20201. * @author WestLangley / http://github.com/WestLangley
  20202. * @author zz85 / https://github.com/zz85
  20203. *
  20204. * Creates an arrow for visualizing directions
  20205. *
  20206. * Parameters:
  20207. * dir - Vector3
  20208. * origin - Vector3
  20209. * length - Number
  20210. * hex - color in hex value
  20211. */
  20212. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20213. THREE.Object3D.call( this );
  20214. if ( hex === undefined ) hex = 0xffff00;
  20215. if ( length === undefined ) length = 20;
  20216. var lineGeometry = new THREE.Geometry();
  20217. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20218. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20219. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20220. this.add( this.line );
  20221. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20222. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20223. this.cone.position.set( 0, 1, 0 );
  20224. this.add( this.cone );
  20225. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  20226. this.setDirection( dir );
  20227. this.setLength( length );
  20228. };
  20229. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20230. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  20231. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  20232. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  20233. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  20234. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  20235. };
  20236. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20237. this.scale.set( length, length, length );
  20238. };
  20239. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20240. this.line.material.color.setHex( hex );
  20241. this.cone.material.color.setHex( hex );
  20242. };
  20243. /**
  20244. * @author alteredq / http://alteredqualia.com/
  20245. *
  20246. * - shows frustum, line of sight and up of the camera
  20247. * - suitable for fast updates
  20248. * - based on frustum visualization in lightgl.js shadowmap example
  20249. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20250. */
  20251. THREE.CameraHelper = function ( camera ) {
  20252. THREE.Line.call( this );
  20253. var scope = this;
  20254. this.geometry = new THREE.Geometry();
  20255. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20256. this.type = THREE.LinePieces;
  20257. this.matrixWorld = camera.matrixWorld;
  20258. this.matrixAutoUpdate = false;
  20259. this.pointMap = {};
  20260. // colors
  20261. var hexFrustum = 0xffaa00;
  20262. var hexCone = 0xff0000;
  20263. var hexUp = 0x00aaff;
  20264. var hexTarget = 0xffffff;
  20265. var hexCross = 0x333333;
  20266. // near
  20267. addLine( "n1", "n2", hexFrustum );
  20268. addLine( "n2", "n4", hexFrustum );
  20269. addLine( "n4", "n3", hexFrustum );
  20270. addLine( "n3", "n1", hexFrustum );
  20271. // far
  20272. addLine( "f1", "f2", hexFrustum );
  20273. addLine( "f2", "f4", hexFrustum );
  20274. addLine( "f4", "f3", hexFrustum );
  20275. addLine( "f3", "f1", hexFrustum );
  20276. // sides
  20277. addLine( "n1", "f1", hexFrustum );
  20278. addLine( "n2", "f2", hexFrustum );
  20279. addLine( "n3", "f3", hexFrustum );
  20280. addLine( "n4", "f4", hexFrustum );
  20281. // cone
  20282. addLine( "p", "n1", hexCone );
  20283. addLine( "p", "n2", hexCone );
  20284. addLine( "p", "n3", hexCone );
  20285. addLine( "p", "n4", hexCone );
  20286. // up
  20287. addLine( "u1", "u2", hexUp );
  20288. addLine( "u2", "u3", hexUp );
  20289. addLine( "u3", "u1", hexUp );
  20290. // target
  20291. addLine( "c", "t", hexTarget );
  20292. addLine( "p", "c", hexCross );
  20293. // cross
  20294. addLine( "cn1", "cn2", hexCross );
  20295. addLine( "cn3", "cn4", hexCross );
  20296. addLine( "cf1", "cf2", hexCross );
  20297. addLine( "cf3", "cf4", hexCross );
  20298. this.camera = camera;
  20299. function addLine( a, b, hex ) {
  20300. addPoint( a, hex );
  20301. addPoint( b, hex );
  20302. }
  20303. function addPoint( id, hex ) {
  20304. scope.geometry.vertices.push( new THREE.Vector3() );
  20305. scope.geometry.colors.push( new THREE.Color( hex ) );
  20306. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  20307. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  20308. }
  20309. this.update( camera );
  20310. };
  20311. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20312. THREE.CameraHelper.prototype.update = function () {
  20313. var scope = this;
  20314. var w = 1, h = 1;
  20315. // we need just camera projection matrix
  20316. // world matrix must be identity
  20317. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  20318. // center / target
  20319. setPoint( "c", 0, 0, -1 );
  20320. setPoint( "t", 0, 0, 1 );
  20321. // near
  20322. setPoint( "n1", -w, -h, -1 );
  20323. setPoint( "n2", w, -h, -1 );
  20324. setPoint( "n3", -w, h, -1 );
  20325. setPoint( "n4", w, h, -1 );
  20326. // far
  20327. setPoint( "f1", -w, -h, 1 );
  20328. setPoint( "f2", w, -h, 1 );
  20329. setPoint( "f3", -w, h, 1 );
  20330. setPoint( "f4", w, h, 1 );
  20331. // up
  20332. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20333. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20334. setPoint( "u3", 0, h * 2, -1 );
  20335. // cross
  20336. setPoint( "cf1", -w, 0, 1 );
  20337. setPoint( "cf2", w, 0, 1 );
  20338. setPoint( "cf3", 0, -h, 1 );
  20339. setPoint( "cf4", 0, h, 1 );
  20340. setPoint( "cn1", -w, 0, -1 );
  20341. setPoint( "cn2", w, 0, -1 );
  20342. setPoint( "cn3", 0, -h, -1 );
  20343. setPoint( "cn4", 0, h, -1 );
  20344. function setPoint( point, x, y, z ) {
  20345. THREE.CameraHelper.__v.set( x, y, z );
  20346. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  20347. var points = scope.pointMap[ point ];
  20348. if ( points !== undefined ) {
  20349. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20350. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  20351. }
  20352. }
  20353. }
  20354. this.geometry.verticesNeedUpdate = true;
  20355. };
  20356. THREE.CameraHelper.__projector = new THREE.Projector();
  20357. THREE.CameraHelper.__v = new THREE.Vector3();
  20358. THREE.CameraHelper.__c = new THREE.Camera();
  20359. /**
  20360. * @author alteredq / http://alteredqualia.com/
  20361. *
  20362. * - shows directional light color, intensity, position, orientation and target
  20363. */
  20364. THREE.DirectionalLightHelper = function ( light, sphereSize, arrowLength ) {
  20365. THREE.Object3D.call( this );
  20366. this.light = light;
  20367. // position
  20368. this.position = light.position;
  20369. // direction
  20370. this.direction = new THREE.Vector3();
  20371. this.direction.sub( light.target.position, light.position );
  20372. // color
  20373. this.color = light.color.clone();
  20374. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20375. this.color.r *= intensity;
  20376. this.color.g *= intensity;
  20377. this.color.b *= intensity;
  20378. var hexColor = this.color.getHex();
  20379. // light helper
  20380. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20381. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20382. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20383. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20384. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  20385. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20386. this.lightArrow.cone.material.fog = false;
  20387. this.lightArrow.line.material.fog = false;
  20388. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20389. this.add( this.lightArrow );
  20390. this.add( this.lightSphere );
  20391. this.add( this.lightRays );
  20392. this.lightSphere.properties.isGizmo = true;
  20393. this.lightSphere.properties.gizmoSubject = light;
  20394. this.lightSphere.properties.gizmoRoot = this;
  20395. // light target helper
  20396. this.targetSphere = null;
  20397. if ( light.target.properties.targetInverse ) {
  20398. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20399. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20400. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20401. this.targetSphere.position = light.target.position;
  20402. this.targetSphere.properties.isGizmo = true;
  20403. this.targetSphere.properties.gizmoSubject = light.target;
  20404. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20405. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20406. var lineGeometry = new THREE.Geometry();
  20407. lineGeometry.vertices.push( this.position.clone() );
  20408. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20409. lineGeometry.computeLineDistances();
  20410. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20411. this.targetLine.properties.isGizmo = true;
  20412. }
  20413. //
  20414. this.properties.isGizmo = true;
  20415. }
  20416. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20417. THREE.DirectionalLightHelper.prototype.update = function () {
  20418. // update arrow orientation
  20419. // pointing from light to target
  20420. this.direction.sub( this.light.target.position, this.light.position );
  20421. this.lightArrow.setDirection( this.direction );
  20422. // update arrow, spheres, rays and line colors to light color * light intensity
  20423. this.color.copy( this.light.color );
  20424. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20425. this.color.r *= intensity;
  20426. this.color.g *= intensity;
  20427. this.color.b *= intensity;
  20428. this.lightArrow.setColor( this.color.getHex() );
  20429. this.lightSphere.material.color.copy( this.color );
  20430. this.lightRays.material.color.copy( this.color );
  20431. this.targetSphere.material.color.copy( this.color );
  20432. this.targetLine.material.color.copy( this.color );
  20433. // update target line vertices
  20434. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20435. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20436. this.targetLine.geometry.computeLineDistances();
  20437. this.targetLine.geometry.verticesNeedUpdate = true;
  20438. }
  20439. /**
  20440. * @author alteredq / http://alteredqualia.com/
  20441. *
  20442. * - shows hemisphere light intensity, sky and ground colors and directions
  20443. */
  20444. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20445. THREE.Object3D.call( this );
  20446. this.light = light;
  20447. // position
  20448. this.position = light.position;
  20449. //
  20450. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20451. // sky color
  20452. this.color = light.color.clone();
  20453. this.color.r *= intensity;
  20454. this.color.g *= intensity;
  20455. this.color.b *= intensity;
  20456. var hexColor = this.color.getHex();
  20457. // ground color
  20458. this.groundColor = light.groundColor.clone();
  20459. this.groundColor.r *= intensity;
  20460. this.groundColor.g *= intensity;
  20461. this.groundColor.b *= intensity;
  20462. var hexColorGround = this.groundColor.getHex();
  20463. // double colored light bulb
  20464. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  20465. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  20466. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20467. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  20468. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  20469. bulbGeometry.faces[ i ].materialIndex = 0;
  20470. }
  20471. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  20472. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  20473. }
  20474. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  20475. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  20476. // arrows for sky and ground light directions
  20477. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  20478. this.lightArrow.rotation.x = Math.PI;
  20479. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  20480. var joint = new THREE.Object3D();
  20481. joint.rotation.x = -Math.PI * 0.5;
  20482. joint.add( this.lightSphere );
  20483. joint.add( this.lightArrow );
  20484. joint.add( this.lightArrowGround );
  20485. this.add( joint );
  20486. //
  20487. this.lightSphere.properties.isGizmo = true;
  20488. this.lightSphere.properties.gizmoSubject = light;
  20489. this.lightSphere.properties.gizmoRoot = this;
  20490. //
  20491. this.properties.isGizmo = true;
  20492. //
  20493. this.target = new THREE.Vector3();
  20494. this.lookAt( this.target );
  20495. }
  20496. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20497. THREE.HemisphereLightHelper.prototype.update = function () {
  20498. // update sphere sky and ground colors to light color * light intensity
  20499. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20500. this.color.copy( this.light.color );
  20501. this.groundColor.copy( this.light.groundColor );
  20502. this.color.r *= intensity;
  20503. this.color.g *= intensity;
  20504. this.color.b *= intensity;
  20505. this.groundColor.r *= intensity;
  20506. this.groundColor.g *= intensity;
  20507. this.groundColor.b *= intensity;
  20508. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  20509. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  20510. this.lightArrow.setColor( this.color.getHex() );
  20511. this.lightArrowGround.setColor( this.groundColor.getHex() );
  20512. this.lookAt( this.target );
  20513. }
  20514. /**
  20515. * @author alteredq / http://alteredqualia.com/
  20516. *
  20517. * - shows point light color, intensity, position and distance
  20518. */
  20519. THREE.PointLightHelper = function ( light, sphereSize ) {
  20520. THREE.Object3D.call( this );
  20521. this.light = light;
  20522. // position
  20523. this.position = light.position;
  20524. // color
  20525. this.color = light.color.clone();
  20526. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20527. this.color.r *= intensity;
  20528. this.color.g *= intensity;
  20529. this.color.b *= intensity;
  20530. var hexColor = this.color.getHex();
  20531. // light helper
  20532. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20533. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20534. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20535. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20536. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20537. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20538. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20539. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20540. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20541. var d = light.distance;
  20542. if ( d === 0.0 ) {
  20543. this.lightDistance.visible = false;
  20544. } else {
  20545. this.lightDistance.scale.set( d, d, d );
  20546. }
  20547. this.add( this.lightSphere );
  20548. this.add( this.lightRays );
  20549. this.add( this.lightDistance );
  20550. //
  20551. this.lightSphere.properties.isGizmo = true;
  20552. this.lightSphere.properties.gizmoSubject = light;
  20553. this.lightSphere.properties.gizmoRoot = this;
  20554. //
  20555. this.properties.isGizmo = true;
  20556. }
  20557. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20558. THREE.PointLightHelper.prototype.update = function () {
  20559. // update sphere and rays colors to light color * light intensity
  20560. this.color.copy( this.light.color );
  20561. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20562. this.color.r *= intensity;
  20563. this.color.g *= intensity;
  20564. this.color.b *= intensity;
  20565. this.lightSphere.material.color.copy( this.color );
  20566. this.lightRays.material.color.copy( this.color );
  20567. this.lightDistance.material.color.copy( this.color );
  20568. //
  20569. var d = this.light.distance;
  20570. if ( d === 0.0 ) {
  20571. this.lightDistance.visible = false;
  20572. } else {
  20573. this.lightDistance.visible = true;
  20574. this.lightDistance.scale.set( d, d, d );
  20575. }
  20576. }
  20577. /**
  20578. * @author alteredq / http://alteredqualia.com/
  20579. *
  20580. * - shows spot light color, intensity, position, orientation, light cone and target
  20581. */
  20582. THREE.SpotLightHelper = function ( light, sphereSize, arrowLength ) {
  20583. THREE.Object3D.call( this );
  20584. this.light = light;
  20585. // position
  20586. this.position = light.position;
  20587. // direction
  20588. this.direction = new THREE.Vector3();
  20589. this.direction.sub( light.target.position, light.position );
  20590. // color
  20591. this.color = light.color.clone();
  20592. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20593. this.color.r *= intensity;
  20594. this.color.g *= intensity;
  20595. this.color.b *= intensity;
  20596. var hexColor = this.color.getHex();
  20597. // light helper
  20598. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20599. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20600. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20601. var coneMatrix = new THREE.Matrix4();
  20602. coneMatrix.rotateX( -Math.PI/2 );
  20603. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  20604. coneGeometry.applyMatrix( coneMatrix );
  20605. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20606. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20607. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20608. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  20609. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20610. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  20611. var coneLength = light.distance ? light.distance : 10000;
  20612. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  20613. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20614. this.lightArrow.cone.material.fog = false;
  20615. this.lightArrow.line.material.fog = false;
  20616. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20617. this.gyroscope = new THREE.Gyroscope();
  20618. this.gyroscope.add( this.lightArrow );
  20619. this.gyroscope.add( this.lightSphere );
  20620. this.gyroscope.add( this.lightRays );
  20621. this.add( this.gyroscope );
  20622. this.add( this.lightCone );
  20623. this.lookAt( light.target.position );
  20624. this.lightSphere.properties.isGizmo = true;
  20625. this.lightSphere.properties.gizmoSubject = light;
  20626. this.lightSphere.properties.gizmoRoot = this;
  20627. // light target helper
  20628. this.targetSphere = null;
  20629. if ( light.target.properties.targetInverse ) {
  20630. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20631. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20632. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20633. this.targetSphere.position = light.target.position;
  20634. this.targetSphere.properties.isGizmo = true;
  20635. this.targetSphere.properties.gizmoSubject = light.target;
  20636. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20637. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20638. var lineGeometry = new THREE.Geometry();
  20639. lineGeometry.vertices.push( this.position.clone() );
  20640. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20641. lineGeometry.computeLineDistances();
  20642. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20643. this.targetLine.properties.isGizmo = true;
  20644. }
  20645. //
  20646. this.properties.isGizmo = true;
  20647. }
  20648. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20649. THREE.SpotLightHelper.prototype.update = function () {
  20650. // update arrow orientation
  20651. // pointing from light to target
  20652. this.direction.sub( this.light.target.position, this.light.position );
  20653. this.lightArrow.setDirection( this.direction );
  20654. // update light cone orientation and size
  20655. this.lookAt( this.light.target.position );
  20656. var coneLength = this.light.distance ? this.light.distance : 10000;
  20657. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  20658. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  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.lightCone.material.color.copy( this.color );
  20669. this.targetSphere.material.color.copy( this.color );
  20670. this.targetLine.material.color.copy( this.color );
  20671. // update target line vertices
  20672. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20673. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20674. this.targetLine.geometry.computeLineDistances();
  20675. this.targetLine.geometry.verticesNeedUpdate = true;
  20676. }
  20677. /**
  20678. * @author alteredq / http://alteredqualia.com/
  20679. */
  20680. THREE.ImmediateRenderObject = function ( ) {
  20681. THREE.Object3D.call( this );
  20682. this.render = function ( renderCallback ) { };
  20683. };
  20684. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20685. /**
  20686. * @author mikael emtinger / http://gomo.se/
  20687. * @author alteredq / http://alteredqualia.com/
  20688. */
  20689. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20690. THREE.Object3D.call( this );
  20691. this.lensFlares = [];
  20692. this.positionScreen = new THREE.Vector3();
  20693. this.customUpdateCallback = undefined;
  20694. if( texture !== undefined ) {
  20695. this.add( texture, size, distance, blending, color );
  20696. }
  20697. };
  20698. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20699. /*
  20700. * Add: adds another flare
  20701. */
  20702. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20703. if( size === undefined ) size = -1;
  20704. if( distance === undefined ) distance = 0;
  20705. if( opacity === undefined ) opacity = 1;
  20706. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20707. if( blending === undefined ) blending = THREE.NormalBlending;
  20708. distance = Math.min( distance, Math.max( 0, distance ) );
  20709. this.lensFlares.push( { texture: texture, // THREE.Texture
  20710. size: size, // size in pixels (-1 = use texture.width)
  20711. distance: distance, // distance (0-1) from light source (0=at light source)
  20712. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20713. scale: 1, // scale
  20714. rotation: 1, // rotation
  20715. opacity: opacity, // opacity
  20716. color: color, // color
  20717. blending: blending } ); // blending
  20718. };
  20719. /*
  20720. * Update lens flares update positions on all flares based on the screen position
  20721. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20722. */
  20723. THREE.LensFlare.prototype.updateLensFlares = function () {
  20724. var f, fl = this.lensFlares.length;
  20725. var flare;
  20726. var vecX = -this.positionScreen.x * 2;
  20727. var vecY = -this.positionScreen.y * 2;
  20728. for( f = 0; f < fl; f ++ ) {
  20729. flare = this.lensFlares[ f ];
  20730. flare.x = this.positionScreen.x + vecX * flare.distance;
  20731. flare.y = this.positionScreen.y + vecY * flare.distance;
  20732. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20733. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20734. }
  20735. };
  20736. /**
  20737. * @author alteredq / http://alteredqualia.com/
  20738. */
  20739. THREE.MorphBlendMesh = function( geometry, material ) {
  20740. THREE.Mesh.call( this, geometry, material );
  20741. this.animationsMap = {};
  20742. this.animationsList = [];
  20743. // prepare default animation
  20744. // (all frames played together in 1 second)
  20745. var numFrames = this.geometry.morphTargets.length;
  20746. var name = "__default";
  20747. var startFrame = 0;
  20748. var endFrame = numFrames - 1;
  20749. var fps = numFrames / 1;
  20750. this.createAnimation( name, startFrame, endFrame, fps );
  20751. this.setAnimationWeight( name, 1 );
  20752. };
  20753. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20754. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20755. var animation = {
  20756. startFrame: start,
  20757. endFrame: end,
  20758. length: end - start + 1,
  20759. fps: fps,
  20760. duration: ( end - start ) / fps,
  20761. lastFrame: 0,
  20762. currentFrame: 0,
  20763. active: false,
  20764. time: 0,
  20765. direction: 1,
  20766. weight: 1,
  20767. directionBackwards: false,
  20768. mirroredLoop: false
  20769. };
  20770. this.animationsMap[ name ] = animation;
  20771. this.animationsList.push( animation );
  20772. };
  20773. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20774. var pattern = /([a-z]+)(\d+)/;
  20775. var firstAnimation, frameRanges = {};
  20776. var geometry = this.geometry;
  20777. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20778. var morph = geometry.morphTargets[ i ];
  20779. var chunks = morph.name.match( pattern );
  20780. if ( chunks && chunks.length > 1 ) {
  20781. var name = chunks[ 1 ];
  20782. var num = chunks[ 2 ];
  20783. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20784. var range = frameRanges[ name ];
  20785. if ( i < range.start ) range.start = i;
  20786. if ( i > range.end ) range.end = i;
  20787. if ( ! firstAnimation ) firstAnimation = name;
  20788. }
  20789. }
  20790. for ( var name in frameRanges ) {
  20791. var range = frameRanges[ name ];
  20792. this.createAnimation( name, range.start, range.end, fps );
  20793. }
  20794. this.firstAnimation = firstAnimation;
  20795. };
  20796. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20797. var animation = this.animationsMap[ name ];
  20798. if ( animation ) {
  20799. animation.direction = 1;
  20800. animation.directionBackwards = false;
  20801. }
  20802. };
  20803. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20804. var animation = this.animationsMap[ name ];
  20805. if ( animation ) {
  20806. animation.direction = -1;
  20807. animation.directionBackwards = true;
  20808. }
  20809. };
  20810. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20811. var animation = this.animationsMap[ name ];
  20812. if ( animation ) {
  20813. animation.fps = fps;
  20814. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20815. }
  20816. };
  20817. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20818. var animation = this.animationsMap[ name ];
  20819. if ( animation ) {
  20820. animation.duration = duration;
  20821. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20822. }
  20823. };
  20824. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20825. var animation = this.animationsMap[ name ];
  20826. if ( animation ) {
  20827. animation.weight = weight;
  20828. }
  20829. };
  20830. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20831. var animation = this.animationsMap[ name ];
  20832. if ( animation ) {
  20833. animation.time = time;
  20834. }
  20835. };
  20836. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20837. var time = 0;
  20838. var animation = this.animationsMap[ name ];
  20839. if ( animation ) {
  20840. time = animation.time;
  20841. }
  20842. return time;
  20843. };
  20844. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20845. var duration = -1;
  20846. var animation = this.animationsMap[ name ];
  20847. if ( animation ) {
  20848. duration = animation.duration;
  20849. }
  20850. return duration;
  20851. };
  20852. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20853. var animation = this.animationsMap[ name ];
  20854. if ( animation ) {
  20855. animation.time = 0;
  20856. animation.active = true;
  20857. } else {
  20858. console.warn( "animation[" + name + "] undefined" );
  20859. }
  20860. };
  20861. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20862. var animation = this.animationsMap[ name ];
  20863. if ( animation ) {
  20864. animation.active = false;
  20865. }
  20866. };
  20867. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20868. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20869. var animation = this.animationsList[ i ];
  20870. if ( ! animation.active ) continue;
  20871. var frameTime = animation.duration / animation.length;
  20872. animation.time += animation.direction * delta;
  20873. if ( animation.mirroredLoop ) {
  20874. if ( animation.time > animation.duration || animation.time < 0 ) {
  20875. animation.direction *= -1;
  20876. if ( animation.time > animation.duration ) {
  20877. animation.time = animation.duration;
  20878. animation.directionBackwards = true;
  20879. }
  20880. if ( animation.time < 0 ) {
  20881. animation.time = 0;
  20882. animation.directionBackwards = false;
  20883. }
  20884. }
  20885. } else {
  20886. animation.time = animation.time % animation.duration;
  20887. if ( animation.time < 0 ) animation.time += animation.duration;
  20888. }
  20889. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20890. var weight = animation.weight;
  20891. if ( keyframe !== animation.currentFrame ) {
  20892. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20893. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20894. this.morphTargetInfluences[ keyframe ] = 0;
  20895. animation.lastFrame = animation.currentFrame;
  20896. animation.currentFrame = keyframe;
  20897. }
  20898. var mix = ( animation.time % frameTime ) / frameTime;
  20899. if ( animation.directionBackwards ) mix = 1 - mix;
  20900. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20901. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20902. }
  20903. };
  20904. /**
  20905. * @author mikael emtinger / http://gomo.se/
  20906. * @author alteredq / http://alteredqualia.com/
  20907. */
  20908. THREE.LensFlarePlugin = function ( ) {
  20909. var _gl, _renderer, _lensFlare = {};
  20910. this.init = function ( renderer ) {
  20911. _gl = renderer.context;
  20912. _renderer = renderer;
  20913. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20914. _lensFlare.faces = new Uint16Array( 6 );
  20915. var i = 0;
  20916. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20917. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20918. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20919. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20920. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20921. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20922. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20923. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20924. i = 0;
  20925. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20926. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20927. // buffers
  20928. _lensFlare.vertexBuffer = _gl.createBuffer();
  20929. _lensFlare.elementBuffer = _gl.createBuffer();
  20930. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20931. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20932. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20933. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20934. // textures
  20935. _lensFlare.tempTexture = _gl.createTexture();
  20936. _lensFlare.occlusionTexture = _gl.createTexture();
  20937. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20938. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20939. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20940. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20941. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20942. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20943. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20944. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20945. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20946. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20947. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20948. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20949. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20950. _lensFlare.hasVertexTexture = false;
  20951. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  20952. } else {
  20953. _lensFlare.hasVertexTexture = true;
  20954. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  20955. }
  20956. _lensFlare.attributes = {};
  20957. _lensFlare.uniforms = {};
  20958. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20959. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20960. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20961. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20962. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20963. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20964. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20965. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20966. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20967. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20968. };
  20969. /*
  20970. * Render lens flares
  20971. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20972. * reads these back and calculates occlusion.
  20973. * Then _lensFlare.update_lensFlares() is called to re-position and
  20974. * update transparency of flares. Then they are rendered.
  20975. *
  20976. */
  20977. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20978. var flares = scene.__webglFlares,
  20979. nFlares = flares.length;
  20980. if ( ! nFlares ) return;
  20981. var tempPosition = new THREE.Vector3();
  20982. var invAspect = viewportHeight / viewportWidth,
  20983. halfViewportWidth = viewportWidth * 0.5,
  20984. halfViewportHeight = viewportHeight * 0.5;
  20985. var size = 16 / viewportHeight,
  20986. scale = new THREE.Vector2( size * invAspect, size );
  20987. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20988. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20989. var uniforms = _lensFlare.uniforms,
  20990. attributes = _lensFlare.attributes;
  20991. // set _lensFlare program and reset blending
  20992. _gl.useProgram( _lensFlare.program );
  20993. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20994. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20995. // loop through all lens flares to update their occlusion and positions
  20996. // setup gl and common used attribs/unforms
  20997. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20998. _gl.uniform1i( uniforms.map, 1 );
  20999. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21000. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21001. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21002. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21003. _gl.disable( _gl.CULL_FACE );
  21004. _gl.depthMask( false );
  21005. var i, j, jl, flare, sprite;
  21006. for ( i = 0; i < nFlares; i ++ ) {
  21007. size = 16 / viewportHeight;
  21008. scale.set( size * invAspect, size );
  21009. // calc object screen position
  21010. flare = flares[ i ];
  21011. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21012. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  21013. camera.projectionMatrix.multiplyVector3( tempPosition );
  21014. // setup arrays for gl programs
  21015. screenPosition.copy( tempPosition )
  21016. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21017. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21018. // screen cull
  21019. if ( _lensFlare.hasVertexTexture || (
  21020. screenPositionPixels.x > 0 &&
  21021. screenPositionPixels.x < viewportWidth &&
  21022. screenPositionPixels.y > 0 &&
  21023. screenPositionPixels.y < viewportHeight ) ) {
  21024. // save current RGB to temp texture
  21025. _gl.activeTexture( _gl.TEXTURE1 );
  21026. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21027. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21028. // render pink quad
  21029. _gl.uniform1i( uniforms.renderType, 0 );
  21030. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21031. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21032. _gl.disable( _gl.BLEND );
  21033. _gl.enable( _gl.DEPTH_TEST );
  21034. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21035. // copy result to occlusionMap
  21036. _gl.activeTexture( _gl.TEXTURE0 );
  21037. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21038. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21039. // restore graphics
  21040. _gl.uniform1i( uniforms.renderType, 1 );
  21041. _gl.disable( _gl.DEPTH_TEST );
  21042. _gl.activeTexture( _gl.TEXTURE1 );
  21043. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21044. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21045. // update object positions
  21046. flare.positionScreen.copy( screenPosition )
  21047. if ( flare.customUpdateCallback ) {
  21048. flare.customUpdateCallback( flare );
  21049. } else {
  21050. flare.updateLensFlares();
  21051. }
  21052. // render flares
  21053. _gl.uniform1i( uniforms.renderType, 2 );
  21054. _gl.enable( _gl.BLEND );
  21055. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21056. sprite = flare.lensFlares[ j ];
  21057. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21058. screenPosition.x = sprite.x;
  21059. screenPosition.y = sprite.y;
  21060. screenPosition.z = sprite.z;
  21061. size = sprite.size * sprite.scale / viewportHeight;
  21062. scale.x = size * invAspect;
  21063. scale.y = size;
  21064. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21065. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21066. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21067. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21068. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21069. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21070. _renderer.setTexture( sprite.texture, 1 );
  21071. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21072. }
  21073. }
  21074. }
  21075. }
  21076. // restore gl
  21077. _gl.enable( _gl.CULL_FACE );
  21078. _gl.enable( _gl.DEPTH_TEST );
  21079. _gl.depthMask( true );
  21080. };
  21081. function createProgram ( shader ) {
  21082. var program = _gl.createProgram();
  21083. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21084. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21085. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21086. _gl.shaderSource( vertexShader, shader.vertexShader );
  21087. _gl.compileShader( fragmentShader );
  21088. _gl.compileShader( vertexShader );
  21089. _gl.attachShader( program, fragmentShader );
  21090. _gl.attachShader( program, vertexShader );
  21091. _gl.linkProgram( program );
  21092. return program;
  21093. };
  21094. };/**
  21095. * @author alteredq / http://alteredqualia.com/
  21096. */
  21097. THREE.ShadowMapPlugin = function ( ) {
  21098. var _gl,
  21099. _renderer,
  21100. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21101. _frustum = new THREE.Frustum(),
  21102. _projScreenMatrix = new THREE.Matrix4(),
  21103. _min = new THREE.Vector3(),
  21104. _max = new THREE.Vector3();
  21105. this.init = function ( renderer ) {
  21106. _gl = renderer.context;
  21107. _renderer = renderer;
  21108. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21109. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21110. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21111. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21112. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21113. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21114. _depthMaterial._shadowPass = true;
  21115. _depthMaterialMorph._shadowPass = true;
  21116. _depthMaterialSkin._shadowPass = true;
  21117. _depthMaterialMorphSkin._shadowPass = true;
  21118. };
  21119. this.render = function ( scene, camera ) {
  21120. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21121. this.update( scene, camera );
  21122. };
  21123. this.update = function ( scene, camera ) {
  21124. var i, il, j, jl, n,
  21125. shadowMap, shadowMatrix, shadowCamera,
  21126. program, buffer, material,
  21127. webglObject, object, light,
  21128. renderList,
  21129. lights = [],
  21130. k = 0,
  21131. fog = null;
  21132. // set GL state for depth map
  21133. _gl.clearColor( 1, 1, 1, 1 );
  21134. _gl.disable( _gl.BLEND );
  21135. _gl.enable( _gl.CULL_FACE );
  21136. _gl.frontFace( _gl.CCW );
  21137. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21138. _gl.cullFace( _gl.FRONT );
  21139. } else {
  21140. _gl.cullFace( _gl.BACK );
  21141. }
  21142. _renderer.setDepthTest( true );
  21143. // preprocess lights
  21144. // - skip lights that are not casting shadows
  21145. // - create virtual lights for cascaded shadow maps
  21146. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21147. light = scene.__lights[ i ];
  21148. if ( ! light.castShadow ) continue;
  21149. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21150. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21151. var virtualLight;
  21152. if ( ! light.shadowCascadeArray[ n ] ) {
  21153. virtualLight = createVirtualLight( light, n );
  21154. virtualLight.originalCamera = camera;
  21155. var gyro = new THREE.Gyroscope();
  21156. gyro.position = light.shadowCascadeOffset;
  21157. gyro.add( virtualLight );
  21158. gyro.add( virtualLight.target );
  21159. camera.add( gyro );
  21160. light.shadowCascadeArray[ n ] = virtualLight;
  21161. console.log( "Created virtualLight", virtualLight );
  21162. } else {
  21163. virtualLight = light.shadowCascadeArray[ n ];
  21164. }
  21165. updateVirtualLight( light, n );
  21166. lights[ k ] = virtualLight;
  21167. k ++;
  21168. }
  21169. } else {
  21170. lights[ k ] = light;
  21171. k ++;
  21172. }
  21173. }
  21174. // render depth map
  21175. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21176. light = lights[ i ];
  21177. if ( ! light.shadowMap ) {
  21178. var shadowFilter = THREE.LinearFilter;
  21179. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21180. shadowFilter = THREE.NearestFilter;
  21181. }
  21182. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21183. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21184. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21185. light.shadowMatrix = new THREE.Matrix4();
  21186. }
  21187. if ( ! light.shadowCamera ) {
  21188. if ( light instanceof THREE.SpotLight ) {
  21189. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21190. } else if ( light instanceof THREE.DirectionalLight ) {
  21191. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21192. } else {
  21193. console.error( "Unsupported light type for shadow" );
  21194. continue;
  21195. }
  21196. scene.add( light.shadowCamera );
  21197. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21198. }
  21199. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21200. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21201. light.shadowCamera.add( light.cameraHelper );
  21202. }
  21203. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21204. updateShadowCamera( camera, light );
  21205. }
  21206. shadowMap = light.shadowMap;
  21207. shadowMatrix = light.shadowMatrix;
  21208. shadowCamera = light.shadowCamera;
  21209. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  21210. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  21211. shadowCamera.updateMatrixWorld();
  21212. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21213. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21214. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21215. // compute shadow matrix
  21216. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21217. 0.0, 0.5, 0.0, 0.5,
  21218. 0.0, 0.0, 0.5, 0.5,
  21219. 0.0, 0.0, 0.0, 1.0 );
  21220. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  21221. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  21222. // update camera matrices and frustum
  21223. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21224. _frustum.setFromMatrix( _projScreenMatrix );
  21225. // render shadow map
  21226. _renderer.setRenderTarget( shadowMap );
  21227. _renderer.clear();
  21228. // set object matrices & frustum culling
  21229. renderList = scene.__webglObjects;
  21230. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21231. webglObject = renderList[ j ];
  21232. object = webglObject.object;
  21233. webglObject.render = false;
  21234. if ( object.visible && object.castShadow ) {
  21235. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21236. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21237. webglObject.render = true;
  21238. }
  21239. }
  21240. }
  21241. // render regular objects
  21242. var objectMaterial, useMorphing, useSkinning;
  21243. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21244. webglObject = renderList[ j ];
  21245. if ( webglObject.render ) {
  21246. object = webglObject.object;
  21247. buffer = webglObject.buffer;
  21248. // culling is overriden globally for all objects
  21249. // while rendering depth map
  21250. // need to deal with MeshFaceMaterial somehow
  21251. // in that case just use the first of material.materials for now
  21252. // (proper solution would require to break objects by materials
  21253. // similarly to regular rendering and then set corresponding
  21254. // depth materials per each chunk instead of just once per object)
  21255. objectMaterial = getObjectMaterial( object );
  21256. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21257. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21258. if ( object.customDepthMaterial ) {
  21259. material = object.customDepthMaterial;
  21260. } else if ( useSkinning ) {
  21261. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21262. } else if ( useMorphing ) {
  21263. material = _depthMaterialMorph;
  21264. } else {
  21265. material = _depthMaterial;
  21266. }
  21267. if ( buffer instanceof THREE.BufferGeometry ) {
  21268. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21269. } else {
  21270. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21271. }
  21272. }
  21273. }
  21274. // set matrices and render immediate objects
  21275. renderList = scene.__webglObjectsImmediate;
  21276. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21277. webglObject = renderList[ j ];
  21278. object = webglObject.object;
  21279. if ( object.visible && object.castShadow ) {
  21280. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21281. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21282. }
  21283. }
  21284. }
  21285. // restore GL state
  21286. var clearColor = _renderer.getClearColor(),
  21287. clearAlpha = _renderer.getClearAlpha();
  21288. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21289. _gl.enable( _gl.BLEND );
  21290. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21291. _gl.cullFace( _gl.BACK );
  21292. }
  21293. };
  21294. function createVirtualLight( light, cascade ) {
  21295. var virtualLight = new THREE.DirectionalLight();
  21296. virtualLight.isVirtual = true;
  21297. virtualLight.onlyShadow = true;
  21298. virtualLight.castShadow = true;
  21299. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21300. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21301. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21302. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21303. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21304. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21305. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21306. virtualLight.shadowDarkness = light.shadowDarkness;
  21307. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21308. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21309. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21310. virtualLight.pointsWorld = [];
  21311. virtualLight.pointsFrustum = [];
  21312. var pointsWorld = virtualLight.pointsWorld,
  21313. pointsFrustum = virtualLight.pointsFrustum;
  21314. for ( var i = 0; i < 8; i ++ ) {
  21315. pointsWorld[ i ] = new THREE.Vector3();
  21316. pointsFrustum[ i ] = new THREE.Vector3();
  21317. }
  21318. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21319. var farZ = light.shadowCascadeFarZ[ cascade ];
  21320. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21321. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21322. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21323. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21324. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21325. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21326. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21327. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21328. return virtualLight;
  21329. }
  21330. // Synchronize virtual light with the original light
  21331. function updateVirtualLight( light, cascade ) {
  21332. var virtualLight = light.shadowCascadeArray[ cascade ];
  21333. virtualLight.position.copy( light.position );
  21334. virtualLight.target.position.copy( light.target.position );
  21335. virtualLight.lookAt( virtualLight.target );
  21336. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21337. virtualLight.shadowDarkness = light.shadowDarkness;
  21338. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21339. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21340. var farZ = light.shadowCascadeFarZ[ cascade ];
  21341. var pointsFrustum = virtualLight.pointsFrustum;
  21342. pointsFrustum[ 0 ].z = nearZ;
  21343. pointsFrustum[ 1 ].z = nearZ;
  21344. pointsFrustum[ 2 ].z = nearZ;
  21345. pointsFrustum[ 3 ].z = nearZ;
  21346. pointsFrustum[ 4 ].z = farZ;
  21347. pointsFrustum[ 5 ].z = farZ;
  21348. pointsFrustum[ 6 ].z = farZ;
  21349. pointsFrustum[ 7 ].z = farZ;
  21350. }
  21351. // Fit shadow camera's ortho frustum to camera frustum
  21352. function updateShadowCamera( camera, light ) {
  21353. var shadowCamera = light.shadowCamera,
  21354. pointsFrustum = light.pointsFrustum,
  21355. pointsWorld = light.pointsWorld;
  21356. _min.set( Infinity, Infinity, Infinity );
  21357. _max.set( -Infinity, -Infinity, -Infinity );
  21358. for ( var i = 0; i < 8; i ++ ) {
  21359. var p = pointsWorld[ i ];
  21360. p.copy( pointsFrustum[ i ] );
  21361. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21362. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  21363. if ( p.x < _min.x ) _min.x = p.x;
  21364. if ( p.x > _max.x ) _max.x = p.x;
  21365. if ( p.y < _min.y ) _min.y = p.y;
  21366. if ( p.y > _max.y ) _max.y = p.y;
  21367. if ( p.z < _min.z ) _min.z = p.z;
  21368. if ( p.z > _max.z ) _max.z = p.z;
  21369. }
  21370. shadowCamera.left = _min.x;
  21371. shadowCamera.right = _max.x;
  21372. shadowCamera.top = _max.y;
  21373. shadowCamera.bottom = _min.y;
  21374. // can't really fit near/far
  21375. //shadowCamera.near = _min.z;
  21376. //shadowCamera.far = _max.z;
  21377. shadowCamera.updateProjectionMatrix();
  21378. }
  21379. // For the moment just ignore objects that have multiple materials with different animation methods
  21380. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21381. function getObjectMaterial( object ) {
  21382. return object.material instanceof THREE.MeshFaceMaterial
  21383. ? object.material.materials[ 0 ]
  21384. : object.material;
  21385. };
  21386. };
  21387. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21388. /**
  21389. * @author mikael emtinger / http://gomo.se/
  21390. * @author alteredq / http://alteredqualia.com/
  21391. */
  21392. THREE.SpritePlugin = function ( ) {
  21393. var _gl, _renderer, _sprite = {};
  21394. this.init = function ( renderer ) {
  21395. _gl = renderer.context;
  21396. _renderer = renderer;
  21397. _sprite.vertices = new Float32Array( 8 + 8 );
  21398. _sprite.faces = new Uint16Array( 6 );
  21399. var i = 0;
  21400. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21401. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21402. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21403. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21404. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21405. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21406. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21407. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21408. i = 0;
  21409. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21410. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21411. _sprite.vertexBuffer = _gl.createBuffer();
  21412. _sprite.elementBuffer = _gl.createBuffer();
  21413. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21414. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21415. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21416. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21417. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  21418. _sprite.attributes = {};
  21419. _sprite.uniforms = {};
  21420. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21421. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21422. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21423. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21424. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21425. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21426. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21427. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21428. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21429. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21430. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21431. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21432. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21433. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21434. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21435. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21436. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21437. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21438. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21439. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21440. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21441. };
  21442. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21443. var sprites = scene.__webglSprites,
  21444. nSprites = sprites.length;
  21445. if ( ! nSprites ) return;
  21446. var attributes = _sprite.attributes,
  21447. uniforms = _sprite.uniforms;
  21448. var invAspect = viewportHeight / viewportWidth;
  21449. var halfViewportWidth = viewportWidth * 0.5,
  21450. halfViewportHeight = viewportHeight * 0.5;
  21451. // setup gl
  21452. _gl.useProgram( _sprite.program );
  21453. _gl.enableVertexAttribArray( attributes.position );
  21454. _gl.enableVertexAttribArray( attributes.uv );
  21455. _gl.disable( _gl.CULL_FACE );
  21456. _gl.enable( _gl.BLEND );
  21457. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21458. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21459. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21460. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21461. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21462. _gl.activeTexture( _gl.TEXTURE0 );
  21463. _gl.uniform1i( uniforms.map, 0 );
  21464. var oldFogType = 0;
  21465. var sceneFogType = 0;
  21466. var fog = scene.fog;
  21467. if ( fog ) {
  21468. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21469. if ( fog instanceof THREE.Fog ) {
  21470. _gl.uniform1f( uniforms.fogNear, fog.near );
  21471. _gl.uniform1f( uniforms.fogFar, fog.far );
  21472. _gl.uniform1i( uniforms.fogType, 1 );
  21473. oldFogType = 1;
  21474. sceneFogType = 1;
  21475. } else if ( fog instanceof THREE.FogExp2 ) {
  21476. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21477. _gl.uniform1i( uniforms.fogType, 2 );
  21478. oldFogType = 2;
  21479. sceneFogType = 2;
  21480. }
  21481. } else {
  21482. _gl.uniform1i( uniforms.fogType, 0 );
  21483. oldFogType = 0;
  21484. sceneFogType = 0;
  21485. }
  21486. // update positions and sort
  21487. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21488. for( i = 0; i < nSprites; i ++ ) {
  21489. sprite = sprites[ i ];
  21490. material = sprite.material;
  21491. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21492. if ( ! material.useScreenCoordinates ) {
  21493. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  21494. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21495. } else {
  21496. sprite.z = - sprite.position.z;
  21497. }
  21498. }
  21499. sprites.sort( painterSortStable );
  21500. // render all sprites
  21501. for( i = 0; i < nSprites; i ++ ) {
  21502. sprite = sprites[ i ];
  21503. material = sprite.material;
  21504. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21505. if ( material.map && material.map.image && material.map.image.width ) {
  21506. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21507. if ( material.useScreenCoordinates ) {
  21508. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21509. _gl.uniform3f(
  21510. uniforms.screenPosition,
  21511. ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  21512. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  21513. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21514. );
  21515. } else {
  21516. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21517. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21518. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21519. }
  21520. if ( scene.fog && material.fog ) {
  21521. fogType = sceneFogType;
  21522. } else {
  21523. fogType = 0;
  21524. }
  21525. if ( oldFogType !== fogType ) {
  21526. _gl.uniform1i( uniforms.fogType, fogType );
  21527. oldFogType = fogType;
  21528. }
  21529. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21530. scale[ 0 ] = size * invAspect * sprite.scale.x;
  21531. scale[ 1 ] = size * sprite.scale.y;
  21532. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21533. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21534. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21535. _gl.uniform1f( uniforms.opacity, material.opacity );
  21536. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21537. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21538. _gl.uniform2fv( uniforms.scale, scale );
  21539. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21540. _renderer.setDepthTest( material.depthTest );
  21541. _renderer.setDepthWrite( material.depthWrite );
  21542. _renderer.setTexture( material.map, 0 );
  21543. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21544. }
  21545. }
  21546. // restore gl
  21547. _gl.enable( _gl.CULL_FACE );
  21548. };
  21549. function createProgram ( shader ) {
  21550. var program = _gl.createProgram();
  21551. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21552. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21553. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21554. _gl.shaderSource( vertexShader, shader.vertexShader );
  21555. _gl.compileShader( fragmentShader );
  21556. _gl.compileShader( vertexShader );
  21557. _gl.attachShader( program, fragmentShader );
  21558. _gl.attachShader( program, vertexShader );
  21559. _gl.linkProgram( program );
  21560. return program;
  21561. };
  21562. function painterSortStable ( a, b ) {
  21563. if ( a.z !== b.z ) {
  21564. return b.z - a.z;
  21565. } else {
  21566. return b.id - a.id;
  21567. }
  21568. };
  21569. };/**
  21570. * @author alteredq / http://alteredqualia.com/
  21571. */
  21572. THREE.DepthPassPlugin = function ( ) {
  21573. this.enabled = false;
  21574. this.renderTarget = null;
  21575. var _gl,
  21576. _renderer,
  21577. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21578. _frustum = new THREE.Frustum(),
  21579. _projScreenMatrix = new THREE.Matrix4();
  21580. this.init = function ( renderer ) {
  21581. _gl = renderer.context;
  21582. _renderer = renderer;
  21583. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21584. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21585. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21586. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21587. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21588. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21589. _depthMaterial._shadowPass = true;
  21590. _depthMaterialMorph._shadowPass = true;
  21591. _depthMaterialSkin._shadowPass = true;
  21592. _depthMaterialMorphSkin._shadowPass = true;
  21593. };
  21594. this.render = function ( scene, camera ) {
  21595. if ( ! this.enabled ) return;
  21596. this.update( scene, camera );
  21597. };
  21598. this.update = function ( scene, camera ) {
  21599. var i, il, j, jl, n,
  21600. program, buffer, material,
  21601. webglObject, object, light,
  21602. renderList,
  21603. fog = null;
  21604. // set GL state for depth map
  21605. _gl.clearColor( 1, 1, 1, 1 );
  21606. _gl.disable( _gl.BLEND );
  21607. _renderer.setDepthTest( true );
  21608. // update scene
  21609. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21610. // update camera matrices and frustum
  21611. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21612. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21613. _frustum.setFromMatrix( _projScreenMatrix );
  21614. // render depth map
  21615. _renderer.setRenderTarget( this.renderTarget );
  21616. _renderer.clear();
  21617. // set object matrices & frustum culling
  21618. renderList = scene.__webglObjects;
  21619. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21620. webglObject = renderList[ j ];
  21621. object = webglObject.object;
  21622. webglObject.render = false;
  21623. if ( object.visible ) {
  21624. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21625. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21626. webglObject.render = true;
  21627. }
  21628. }
  21629. }
  21630. // render regular objects
  21631. var objectMaterial, useMorphing, useSkinning;
  21632. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21633. webglObject = renderList[ j ];
  21634. if ( webglObject.render ) {
  21635. object = webglObject.object;
  21636. buffer = webglObject.buffer;
  21637. // todo: create proper depth material for particles
  21638. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21639. objectMaterial = getObjectMaterial( object );
  21640. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21641. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21642. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21643. if ( object.customDepthMaterial ) {
  21644. material = object.customDepthMaterial;
  21645. } else if ( useSkinning ) {
  21646. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21647. } else if ( useMorphing ) {
  21648. material = _depthMaterialMorph;
  21649. } else {
  21650. material = _depthMaterial;
  21651. }
  21652. if ( buffer instanceof THREE.BufferGeometry ) {
  21653. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21654. } else {
  21655. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21656. }
  21657. }
  21658. }
  21659. // set matrices and render immediate objects
  21660. renderList = scene.__webglObjectsImmediate;
  21661. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21662. webglObject = renderList[ j ];
  21663. object = webglObject.object;
  21664. if ( object.visible ) {
  21665. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21666. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21667. }
  21668. }
  21669. // restore GL state
  21670. var clearColor = _renderer.getClearColor(),
  21671. clearAlpha = _renderer.getClearAlpha();
  21672. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21673. _gl.enable( _gl.BLEND );
  21674. };
  21675. // For the moment just ignore objects that have multiple materials with different animation methods
  21676. // Only the first material will be taken into account for deciding which depth material to use
  21677. function getObjectMaterial( object ) {
  21678. return object.material instanceof THREE.MeshFaceMaterial
  21679. ? object.material.materials[ 0 ]
  21680. : object.material;
  21681. };
  21682. };
  21683. /**
  21684. * @author mikael emtinger / http://gomo.se/
  21685. *
  21686. */
  21687. THREE.ShaderFlares = {
  21688. 'lensFlareVertexTexture': {
  21689. vertexShader: [
  21690. "uniform vec3 screenPosition;",
  21691. "uniform vec2 scale;",
  21692. "uniform float rotation;",
  21693. "uniform int renderType;",
  21694. "uniform sampler2D occlusionMap;",
  21695. "attribute vec2 position;",
  21696. "attribute vec2 uv;",
  21697. "varying vec2 vUV;",
  21698. "varying float vVisibility;",
  21699. "void main() {",
  21700. "vUV = uv;",
  21701. "vec2 pos = position;",
  21702. "if( renderType == 2 ) {",
  21703. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21704. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21705. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21706. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21707. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21708. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21709. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21710. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21711. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21712. "vVisibility = ( visibility.r / 9.0 ) *",
  21713. "( 1.0 - visibility.g / 9.0 ) *",
  21714. "( visibility.b / 9.0 ) *",
  21715. "( 1.0 - visibility.a / 9.0 );",
  21716. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21717. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21718. "}",
  21719. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21720. "}"
  21721. ].join( "\n" ),
  21722. fragmentShader: [
  21723. "precision mediump float;",
  21724. "uniform sampler2D map;",
  21725. "uniform float opacity;",
  21726. "uniform int renderType;",
  21727. "uniform vec3 color;",
  21728. "varying vec2 vUV;",
  21729. "varying float vVisibility;",
  21730. "void main() {",
  21731. // pink square
  21732. "if( renderType == 0 ) {",
  21733. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21734. // restore
  21735. "} else if( renderType == 1 ) {",
  21736. "gl_FragColor = texture2D( map, vUV );",
  21737. // flare
  21738. "} else {",
  21739. "vec4 texture = texture2D( map, vUV );",
  21740. "texture.a *= opacity * vVisibility;",
  21741. "gl_FragColor = texture;",
  21742. "gl_FragColor.rgb *= color;",
  21743. "}",
  21744. "}"
  21745. ].join( "\n" )
  21746. },
  21747. 'lensFlare': {
  21748. vertexShader: [
  21749. "uniform vec3 screenPosition;",
  21750. "uniform vec2 scale;",
  21751. "uniform float rotation;",
  21752. "uniform int renderType;",
  21753. "attribute vec2 position;",
  21754. "attribute vec2 uv;",
  21755. "varying vec2 vUV;",
  21756. "void main() {",
  21757. "vUV = uv;",
  21758. "vec2 pos = position;",
  21759. "if( renderType == 2 ) {",
  21760. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21761. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21762. "}",
  21763. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21764. "}"
  21765. ].join( "\n" ),
  21766. fragmentShader: [
  21767. "precision mediump float;",
  21768. "uniform sampler2D map;",
  21769. "uniform sampler2D occlusionMap;",
  21770. "uniform float opacity;",
  21771. "uniform int renderType;",
  21772. "uniform vec3 color;",
  21773. "varying vec2 vUV;",
  21774. "void main() {",
  21775. // pink square
  21776. "if( renderType == 0 ) {",
  21777. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21778. // restore
  21779. "} else if( renderType == 1 ) {",
  21780. "gl_FragColor = texture2D( map, vUV );",
  21781. // flare
  21782. "} else {",
  21783. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21784. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21785. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21786. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21787. "visibility = ( 1.0 - visibility / 4.0 );",
  21788. "vec4 texture = texture2D( map, vUV );",
  21789. "texture.a *= opacity * visibility;",
  21790. "gl_FragColor = texture;",
  21791. "gl_FragColor.rgb *= color;",
  21792. "}",
  21793. "}"
  21794. ].join( "\n" )
  21795. }
  21796. };
  21797. /**
  21798. * @author mikael emtinger / http://gomo.se/
  21799. * @author alteredq / http://alteredqualia.com/
  21800. *
  21801. */
  21802. THREE.ShaderSprite = {
  21803. 'sprite': {
  21804. vertexShader: [
  21805. "uniform int useScreenCoordinates;",
  21806. "uniform int sizeAttenuation;",
  21807. "uniform vec3 screenPosition;",
  21808. "uniform mat4 modelViewMatrix;",
  21809. "uniform mat4 projectionMatrix;",
  21810. "uniform float rotation;",
  21811. "uniform vec2 scale;",
  21812. "uniform vec2 alignment;",
  21813. "uniform vec2 uvOffset;",
  21814. "uniform vec2 uvScale;",
  21815. "attribute vec2 position;",
  21816. "attribute vec2 uv;",
  21817. "varying vec2 vUV;",
  21818. "void main() {",
  21819. "vUV = uvOffset + uv * uvScale;",
  21820. "vec2 alignedPosition = position + alignment;",
  21821. "vec2 rotatedPosition;",
  21822. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21823. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21824. "vec4 finalPosition;",
  21825. "if( useScreenCoordinates != 0 ) {",
  21826. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21827. "} else {",
  21828. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21829. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21830. "}",
  21831. "gl_Position = finalPosition;",
  21832. "}"
  21833. ].join( "\n" ),
  21834. fragmentShader: [
  21835. "precision mediump float;",
  21836. "uniform vec3 color;",
  21837. "uniform sampler2D map;",
  21838. "uniform float opacity;",
  21839. "uniform int fogType;",
  21840. "uniform vec3 fogColor;",
  21841. "uniform float fogDensity;",
  21842. "uniform float fogNear;",
  21843. "uniform float fogFar;",
  21844. "uniform float alphaTest;",
  21845. "varying vec2 vUV;",
  21846. "void main() {",
  21847. "vec4 texture = texture2D( map, vUV );",
  21848. "if ( texture.a < alphaTest ) discard;",
  21849. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21850. "if ( fogType > 0 ) {",
  21851. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21852. "float fogFactor = 0.0;",
  21853. "if ( fogType == 1 ) {",
  21854. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21855. "} else {",
  21856. "const float LOG2 = 1.442695;",
  21857. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21858. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21859. "}",
  21860. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21861. "}",
  21862. "}"
  21863. ].join( "\n" )
  21864. }
  21865. };