three.js 846 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361
  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. // OBJLoader
  6044. if ( loader.addEventListener ) {
  6045. loader.addEventListener( 'load', create_callback_hierachy( objID, parent, material, objJSON ) );
  6046. loader.load( get_url( objJSON.url, data.urlBaseType ) );
  6047. } else {
  6048. // ColladaLoader
  6049. if ( loader.options ) {
  6050. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6051. // UTF8Loader
  6052. } else {
  6053. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6054. }
  6055. }
  6056. }
  6057. } else if ( objJSON.geometry !== undefined ) {
  6058. geometry = result.geometries[ objJSON.geometry ];
  6059. // geometry already loaded
  6060. if ( geometry ) {
  6061. var needsTangents = false;
  6062. material = result.materials[ objJSON.material ];
  6063. needsTangents = material instanceof THREE.ShaderMaterial;
  6064. pos = objJSON.position;
  6065. rot = objJSON.rotation;
  6066. scl = objJSON.scale;
  6067. mat = objJSON.matrix;
  6068. quat = objJSON.quaternion;
  6069. // turn off quaternions, for the moment
  6070. quat = 0;
  6071. // use materials from the model file
  6072. // if there is no material specified in the object
  6073. if ( ! objJSON.material ) {
  6074. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6075. }
  6076. // use materials from the model file
  6077. // if there is just empty face material
  6078. // (must create new material as each model has its own face material)
  6079. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6080. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6081. }
  6082. if ( material instanceof THREE.MeshFaceMaterial ) {
  6083. for ( var i = 0; i < material.materials.length; i ++ ) {
  6084. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6085. }
  6086. }
  6087. if ( needsTangents ) {
  6088. geometry.computeTangents();
  6089. }
  6090. if ( objJSON.skin ) {
  6091. object = new THREE.SkinnedMesh( geometry, material );
  6092. } else if ( objJSON.morph ) {
  6093. object = new THREE.MorphAnimMesh( geometry, material );
  6094. if ( objJSON.duration !== undefined ) {
  6095. object.duration = objJSON.duration;
  6096. }
  6097. if ( objJSON.time !== undefined ) {
  6098. object.time = objJSON.time;
  6099. }
  6100. if ( objJSON.mirroredLoop !== undefined ) {
  6101. object.mirroredLoop = objJSON.mirroredLoop;
  6102. }
  6103. if ( material.morphNormals ) {
  6104. geometry.computeMorphNormals();
  6105. }
  6106. } else {
  6107. object = new THREE.Mesh( geometry, material );
  6108. }
  6109. object.name = objID;
  6110. if ( mat ) {
  6111. object.matrixAutoUpdate = false;
  6112. object.matrix.set(
  6113. mat[0], mat[1], mat[2], mat[3],
  6114. mat[4], mat[5], mat[6], mat[7],
  6115. mat[8], mat[9], mat[10], mat[11],
  6116. mat[12], mat[13], mat[14], mat[15]
  6117. );
  6118. } else {
  6119. object.position.set( pos[0], pos[1], pos[2] );
  6120. if ( quat ) {
  6121. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6122. object.useQuaternion = true;
  6123. } else {
  6124. object.rotation.set( rot[0], rot[1], rot[2] );
  6125. }
  6126. object.scale.set( scl[0], scl[1], scl[2] );
  6127. }
  6128. object.visible = objJSON.visible;
  6129. object.castShadow = objJSON.castShadow;
  6130. object.receiveShadow = objJSON.receiveShadow;
  6131. parent.add( object );
  6132. result.objects[ objID ] = object;
  6133. }
  6134. // lights
  6135. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6136. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6137. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6138. if ( objJSON.type === "DirectionalLight" ) {
  6139. pos = objJSON.direction;
  6140. light = new THREE.DirectionalLight( hex, intensity );
  6141. light.position.set( pos[0], pos[1], pos[2] );
  6142. if ( objJSON.target ) {
  6143. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6144. // kill existing default target
  6145. // otherwise it gets added to scene when parent gets added
  6146. light.target = null;
  6147. }
  6148. } else if ( objJSON.type === "PointLight" ) {
  6149. pos = objJSON.position;
  6150. dst = objJSON.distance;
  6151. light = new THREE.PointLight( hex, intensity, dst );
  6152. light.position.set( pos[0], pos[1], pos[2] );
  6153. } else if ( objJSON.type === "AmbientLight" ) {
  6154. light = new THREE.AmbientLight( hex );
  6155. }
  6156. parent.add( light );
  6157. light.name = objID;
  6158. result.lights[ objID ] = light;
  6159. result.objects[ objID ] = light;
  6160. // cameras
  6161. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6162. if ( objJSON.type === "PerspectiveCamera" ) {
  6163. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6164. } else if ( objJSON.type === "OrthographicCamera" ) {
  6165. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6166. }
  6167. pos = objJSON.position;
  6168. camera.position.set( pos[0], pos[1], pos[2] );
  6169. parent.add( camera );
  6170. camera.name = objID;
  6171. result.cameras[ objID ] = camera;
  6172. result.objects[ objID ] = camera;
  6173. // pure Object3D
  6174. } else {
  6175. pos = objJSON.position;
  6176. rot = objJSON.rotation;
  6177. scl = objJSON.scale;
  6178. quat = objJSON.quaternion;
  6179. // turn off quaternions, for the moment
  6180. quat = 0;
  6181. object = new THREE.Object3D();
  6182. object.name = objID;
  6183. object.position.set( pos[0], pos[1], pos[2] );
  6184. if ( quat ) {
  6185. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6186. object.useQuaternion = true;
  6187. } else {
  6188. object.rotation.set( rot[0], rot[1], rot[2] );
  6189. }
  6190. object.scale.set( scl[0], scl[1], scl[2] );
  6191. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6192. parent.add( object );
  6193. result.objects[ objID ] = object;
  6194. result.empties[ objID ] = object;
  6195. }
  6196. if ( object ) {
  6197. if ( objJSON.properties !== undefined ) {
  6198. for ( var key in objJSON.properties ) {
  6199. var value = objJSON.properties[ key ];
  6200. object.properties[ key ] = value;
  6201. }
  6202. }
  6203. if ( objJSON.children !== undefined ) {
  6204. handle_children( object, objJSON.children );
  6205. }
  6206. }
  6207. }
  6208. }
  6209. };
  6210. function handle_mesh( geo, mat, id ) {
  6211. result.geometries[ id ] = geo;
  6212. result.face_materials[ id ] = mat;
  6213. handle_objects();
  6214. };
  6215. function handle_hierarchy( node, id, parent, material, obj ) {
  6216. var p = obj.position;
  6217. var r = obj.rotation;
  6218. var q = obj.quaternion;
  6219. var s = obj.scale;
  6220. node.position.set( p[0], p[1], p[2] );
  6221. if ( q ) {
  6222. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6223. node.useQuaternion = true;
  6224. } else {
  6225. node.rotation.set( r[0], r[1], r[2] );
  6226. }
  6227. node.scale.set( s[0], s[1], s[2] );
  6228. // override children materials
  6229. // if object material was specified in JSON explicitly
  6230. if ( material ) {
  6231. node.traverse( function ( child ) {
  6232. child.material = material;
  6233. } );
  6234. }
  6235. // override children visibility
  6236. // with root node visibility as specified in JSON
  6237. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6238. node.traverse( function ( child ) {
  6239. child.visible = visible;
  6240. } );
  6241. parent.add( node );
  6242. node.name = id;
  6243. result.objects[ id ] = node;
  6244. handle_objects();
  6245. };
  6246. function create_callback_geometry( id ) {
  6247. return function( geo, mat ) {
  6248. handle_mesh( geo, mat, id );
  6249. counter_models -= 1;
  6250. scope.onLoadComplete();
  6251. async_callback_gate();
  6252. }
  6253. };
  6254. function create_callback_hierachy( id, parent, material, obj ) {
  6255. return function( event ) {
  6256. var result;
  6257. // loaders which use EventDispatcher
  6258. if ( event.content ) {
  6259. result = event.content;
  6260. // ColladaLoader
  6261. } else if ( event.dae ) {
  6262. result = event.scene;
  6263. // UTF8Loader
  6264. } else {
  6265. result = event;
  6266. }
  6267. handle_hierarchy( result, id, parent, material, obj );
  6268. counter_models -= 1;
  6269. scope.onLoadComplete();
  6270. async_callback_gate();
  6271. }
  6272. };
  6273. function create_callback_embed( id ) {
  6274. return function( geo, mat ) {
  6275. result.geometries[ id ] = geo;
  6276. result.face_materials[ id ] = mat;
  6277. }
  6278. };
  6279. function async_callback_gate() {
  6280. var progress = {
  6281. totalModels : total_models,
  6282. totalTextures : total_textures,
  6283. loadedModels : total_models - counter_models,
  6284. loadedTextures : total_textures - counter_textures
  6285. };
  6286. scope.callbackProgress( progress, result );
  6287. scope.onLoadProgress();
  6288. if ( counter_models === 0 && counter_textures === 0 ) {
  6289. finalize();
  6290. callbackFinished( result );
  6291. }
  6292. };
  6293. function finalize() {
  6294. // take care of targets which could be asynchronously loaded objects
  6295. for ( var i = 0; i < target_array.length; i ++ ) {
  6296. var ta = target_array[ i ];
  6297. var target = result.objects[ ta.targetName ];
  6298. if ( target ) {
  6299. ta.object.target = target;
  6300. } else {
  6301. // if there was error and target of specified name doesn't exist in the scene file
  6302. // create instead dummy target
  6303. // (target must be added to scene explicitly as parent is already added)
  6304. ta.object.target = new THREE.Object3D();
  6305. result.scene.add( ta.object.target );
  6306. }
  6307. ta.object.target.properties.targetInverse = ta.object;
  6308. }
  6309. };
  6310. var callbackTexture = function ( count ) {
  6311. counter_textures -= count;
  6312. async_callback_gate();
  6313. scope.onLoadComplete();
  6314. };
  6315. // must use this instead of just directly calling callbackTexture
  6316. // because of closure in the calling context loop
  6317. var generateTextureCallback = function ( count ) {
  6318. return function() {
  6319. callbackTexture( count );
  6320. };
  6321. };
  6322. // first go synchronous elements
  6323. // fogs
  6324. var fogID, fogJSON;
  6325. for ( fogID in data.fogs ) {
  6326. fogJSON = data.fogs[ fogID ];
  6327. if ( fogJSON.type === "linear" ) {
  6328. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6329. } else if ( fogJSON.type === "exp2" ) {
  6330. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6331. }
  6332. color = fogJSON.color;
  6333. fog.color.setRGB( color[0], color[1], color[2] );
  6334. result.fogs[ fogID ] = fog;
  6335. }
  6336. // now come potentially asynchronous elements
  6337. // geometries
  6338. // count how many geometries will be loaded asynchronously
  6339. var geoID, geoJSON;
  6340. for ( geoID in data.geometries ) {
  6341. geoJSON = data.geometries[ geoID ];
  6342. if ( geoJSON.type in this.geometryHandlerMap ) {
  6343. counter_models += 1;
  6344. scope.onLoadStart();
  6345. }
  6346. }
  6347. // count how many hierarchies will be loaded asynchronously
  6348. var objID, objJSON;
  6349. for ( objID in data.objects ) {
  6350. objJSON = data.objects[ objID ];
  6351. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6352. counter_models += 1;
  6353. scope.onLoadStart();
  6354. }
  6355. }
  6356. total_models = counter_models;
  6357. for ( geoID in data.geometries ) {
  6358. geoJSON = data.geometries[ geoID ];
  6359. if ( geoJSON.type === "cube" ) {
  6360. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6361. result.geometries[ geoID ] = geometry;
  6362. } else if ( geoJSON.type === "plane" ) {
  6363. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6364. result.geometries[ geoID ] = geometry;
  6365. } else if ( geoJSON.type === "sphere" ) {
  6366. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6367. result.geometries[ geoID ] = geometry;
  6368. } else if ( geoJSON.type === "cylinder" ) {
  6369. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6370. result.geometries[ geoID ] = geometry;
  6371. } else if ( geoJSON.type === "torus" ) {
  6372. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6373. result.geometries[ geoID ] = geometry;
  6374. } else if ( geoJSON.type === "icosahedron" ) {
  6375. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6376. result.geometries[ geoID ] = geometry;
  6377. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6378. var loaderParameters = {};
  6379. for ( var parType in geoJSON ) {
  6380. if ( parType !== "type" && parType !== "url" ) {
  6381. loaderParameters[ parType ] = geoJSON[ parType ];
  6382. }
  6383. }
  6384. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6385. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6386. } else if ( geoJSON.type === "embedded" ) {
  6387. var modelJson = data.embeds[ geoJSON.id ],
  6388. texture_path = "";
  6389. // pass metadata along to jsonLoader so it knows the format version
  6390. modelJson.metadata = data.metadata;
  6391. if ( modelJson ) {
  6392. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6393. jsonLoader.createModel( modelJson, create_callback_embed( geoID ), texture_path );
  6394. }
  6395. }
  6396. }
  6397. // textures
  6398. // count how many textures will be loaded asynchronously
  6399. var textureID, textureJSON;
  6400. for ( textureID in data.textures ) {
  6401. textureJSON = data.textures[ textureID ];
  6402. if ( textureJSON.url instanceof Array ) {
  6403. counter_textures += textureJSON.url.length;
  6404. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6405. scope.onLoadStart();
  6406. }
  6407. } else {
  6408. counter_textures += 1;
  6409. scope.onLoadStart();
  6410. }
  6411. }
  6412. total_textures = counter_textures;
  6413. for ( textureID in data.textures ) {
  6414. textureJSON = data.textures[ textureID ];
  6415. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6416. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6417. }
  6418. if ( textureJSON.url instanceof Array ) {
  6419. var count = textureJSON.url.length;
  6420. var url_array = [];
  6421. for( var i = 0; i < count; i ++ ) {
  6422. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6423. }
  6424. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  6425. if ( isCompressed ) {
  6426. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6427. } else {
  6428. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6429. }
  6430. } else {
  6431. var isCompressed = textureJSON.url.toLowerCase().endsWith( ".dds" );
  6432. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6433. var textureCallback = generateTextureCallback( 1 );
  6434. if ( isCompressed ) {
  6435. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6436. } else {
  6437. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6438. }
  6439. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6440. texture.minFilter = THREE[ textureJSON.minFilter ];
  6441. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6442. texture.magFilter = THREE[ textureJSON.magFilter ];
  6443. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6444. if ( textureJSON.repeat ) {
  6445. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6446. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6447. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6448. }
  6449. if ( textureJSON.offset ) {
  6450. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6451. }
  6452. // handle wrap after repeat so that default repeat can be overriden
  6453. if ( textureJSON.wrap ) {
  6454. var wrapMap = {
  6455. "repeat" : THREE.RepeatWrapping,
  6456. "mirror" : THREE.MirroredRepeatWrapping
  6457. }
  6458. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6459. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6460. }
  6461. }
  6462. result.textures[ textureID ] = texture;
  6463. }
  6464. // materials
  6465. var matID, matJSON;
  6466. var parID;
  6467. for ( matID in data.materials ) {
  6468. matJSON = data.materials[ matID ];
  6469. for ( parID in matJSON.parameters ) {
  6470. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6471. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6472. } else if ( parID === "shading" ) {
  6473. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6474. } else if ( parID === "side" ) {
  6475. if ( matJSON.parameters[ parID ] == "double" ) {
  6476. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6477. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6478. matJSON.parameters[ parID ] = THREE.BackSide;
  6479. } else {
  6480. matJSON.parameters[ parID ] = THREE.FrontSide;
  6481. }
  6482. } else if ( parID === "blending" ) {
  6483. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6484. } else if ( parID === "combine" ) {
  6485. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  6486. } else if ( parID === "vertexColors" ) {
  6487. if ( matJSON.parameters[ parID ] == "face" ) {
  6488. matJSON.parameters[ parID ] = THREE.FaceColors;
  6489. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6490. } else if ( matJSON.parameters[ parID ] ) {
  6491. matJSON.parameters[ parID ] = THREE.VertexColors;
  6492. }
  6493. } else if ( parID === "wrapRGB" ) {
  6494. var v3 = matJSON.parameters[ parID ];
  6495. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6496. }
  6497. }
  6498. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6499. matJSON.parameters.transparent = true;
  6500. }
  6501. if ( matJSON.parameters.normalMap ) {
  6502. var shader = THREE.ShaderUtils.lib[ "normal" ];
  6503. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6504. var diffuse = matJSON.parameters.color;
  6505. var specular = matJSON.parameters.specular;
  6506. var ambient = matJSON.parameters.ambient;
  6507. var shininess = matJSON.parameters.shininess;
  6508. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6509. if ( matJSON.parameters.normalScale ) {
  6510. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6511. }
  6512. if ( matJSON.parameters.map ) {
  6513. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6514. uniforms[ "enableDiffuse" ].value = true;
  6515. }
  6516. if ( matJSON.parameters.envMap ) {
  6517. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6518. uniforms[ "enableReflection" ].value = true;
  6519. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6520. }
  6521. if ( matJSON.parameters.lightMap ) {
  6522. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6523. uniforms[ "enableAO" ].value = true;
  6524. }
  6525. if ( matJSON.parameters.specularMap ) {
  6526. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6527. uniforms[ "enableSpecular" ].value = true;
  6528. }
  6529. if ( matJSON.parameters.displacementMap ) {
  6530. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6531. uniforms[ "enableDisplacement" ].value = true;
  6532. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6533. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6534. }
  6535. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6536. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6537. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6538. uniforms[ "uShininess" ].value = shininess;
  6539. if ( matJSON.parameters.opacity ) {
  6540. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6541. }
  6542. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6543. material = new THREE.ShaderMaterial( parameters );
  6544. } else {
  6545. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6546. }
  6547. result.materials[ matID ] = material;
  6548. }
  6549. // second pass through all materials to initialize MeshFaceMaterials
  6550. // that could be referring to other materials out of order
  6551. for ( matID in data.materials ) {
  6552. matJSON = data.materials[ matID ];
  6553. if ( matJSON.parameters.materials ) {
  6554. var materialArray = [];
  6555. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6556. var label = matJSON.parameters.materials[ i ];
  6557. materialArray.push( result.materials[ label ] );
  6558. }
  6559. result.materials[ matID ].materials = materialArray;
  6560. }
  6561. }
  6562. // objects ( synchronous init of procedural primitives )
  6563. handle_objects();
  6564. // defaults
  6565. if ( result.cameras && data.defaults.camera ) {
  6566. result.currentCamera = result.cameras[ data.defaults.camera ];
  6567. }
  6568. if ( result.fogs && data.defaults.fog ) {
  6569. result.scene.fog = result.fogs[ data.defaults.fog ];
  6570. }
  6571. color = data.defaults.bgcolor;
  6572. result.bgColor = new THREE.Color();
  6573. result.bgColor.setRGB( color[0], color[1], color[2] );
  6574. result.bgColorAlpha = data.defaults.bgalpha;
  6575. // synchronous callback
  6576. scope.callbackSync( result );
  6577. // just in case there are no async elements
  6578. async_callback_gate();
  6579. };
  6580. /**
  6581. * @author mrdoob / http://mrdoob.com/
  6582. */
  6583. THREE.TextureLoader = function () {
  6584. THREE.EventDispatcher.call( this );
  6585. this.crossOrigin = null;
  6586. };
  6587. THREE.TextureLoader.prototype = {
  6588. constructor: THREE.TextureLoader,
  6589. load: function ( url ) {
  6590. var scope = this;
  6591. var image = new Image();
  6592. image.addEventListener( 'load', function () {
  6593. var texture = new THREE.Texture( image );
  6594. texture.needsUpdate = true;
  6595. scope.dispatchEvent( { type: 'load', content: texture } );
  6596. }, false );
  6597. image.addEventListener( 'error', function () {
  6598. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6599. }, false );
  6600. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6601. image.src = url;
  6602. }
  6603. }
  6604. /**
  6605. * @author mrdoob / http://mrdoob.com/
  6606. * @author alteredq / http://alteredqualia.com/
  6607. */
  6608. THREE.Material = function () {
  6609. THREE.EventDispatcher.call( this );
  6610. this.id = THREE.MaterialIdCount ++;
  6611. this.name = '';
  6612. this.side = THREE.FrontSide;
  6613. this.opacity = 1;
  6614. this.transparent = false;
  6615. this.blending = THREE.NormalBlending;
  6616. this.blendSrc = THREE.SrcAlphaFactor;
  6617. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6618. this.blendEquation = THREE.AddEquation;
  6619. this.depthTest = true;
  6620. this.depthWrite = true;
  6621. this.polygonOffset = false;
  6622. this.polygonOffsetFactor = 0;
  6623. this.polygonOffsetUnits = 0;
  6624. this.alphaTest = 0;
  6625. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6626. this.visible = true;
  6627. this.needsUpdate = true;
  6628. };
  6629. THREE.Material.prototype.setValues = function ( values ) {
  6630. if ( values === undefined ) return;
  6631. for ( var key in values ) {
  6632. var newValue = values[ key ];
  6633. if ( newValue === undefined ) {
  6634. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6635. continue;
  6636. }
  6637. if ( key in this ) {
  6638. var currentValue = this[ key ];
  6639. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  6640. currentValue.copy( newValue );
  6641. } else if ( currentValue instanceof THREE.Color ) {
  6642. currentValue.set( newValue );
  6643. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6644. currentValue.copy( newValue );
  6645. } else {
  6646. this[ key ] = newValue;
  6647. }
  6648. }
  6649. }
  6650. };
  6651. THREE.Material.prototype.clone = function ( material ) {
  6652. if ( material === undefined ) material = new THREE.Material();
  6653. material.name = this.name;
  6654. material.side = this.side;
  6655. material.opacity = this.opacity;
  6656. material.transparent = this.transparent;
  6657. material.blending = this.blending;
  6658. material.blendSrc = this.blendSrc;
  6659. material.blendDst = this.blendDst;
  6660. material.blendEquation = this.blendEquation;
  6661. material.depthTest = this.depthTest;
  6662. material.depthWrite = this.depthWrite;
  6663. material.polygonOffset = this.polygonOffset;
  6664. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6665. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6666. material.alphaTest = this.alphaTest;
  6667. material.overdraw = this.overdraw;
  6668. material.visible = this.visible;
  6669. return material;
  6670. };
  6671. THREE.Material.prototype.dispose = function () {
  6672. this.dispatchEvent( { type: 'dispose' } );
  6673. };
  6674. THREE.MaterialIdCount = 0;
  6675. /**
  6676. * @author mrdoob / http://mrdoob.com/
  6677. * @author alteredq / http://alteredqualia.com/
  6678. *
  6679. * parameters = {
  6680. * color: <hex>,
  6681. * opacity: <float>,
  6682. *
  6683. * blending: THREE.NormalBlending,
  6684. * depthTest: <bool>,
  6685. * depthWrite: <bool>,
  6686. *
  6687. * linewidth: <float>,
  6688. * linecap: "round",
  6689. * linejoin: "round",
  6690. *
  6691. * vertexColors: <bool>
  6692. *
  6693. * fog: <bool>
  6694. * }
  6695. */
  6696. THREE.LineBasicMaterial = function ( parameters ) {
  6697. THREE.Material.call( this );
  6698. this.color = new THREE.Color( 0xffffff );
  6699. this.linewidth = 1;
  6700. this.linecap = 'round';
  6701. this.linejoin = 'round';
  6702. this.vertexColors = false;
  6703. this.fog = true;
  6704. this.setValues( parameters );
  6705. };
  6706. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6707. THREE.LineBasicMaterial.prototype.clone = function () {
  6708. var material = new THREE.LineBasicMaterial();
  6709. THREE.Material.prototype.clone.call( this, material );
  6710. material.color.copy( this.color );
  6711. material.linewidth = this.linewidth;
  6712. material.linecap = this.linecap;
  6713. material.linejoin = this.linejoin;
  6714. material.vertexColors = this.vertexColors;
  6715. material.fog = this.fog;
  6716. return material;
  6717. };
  6718. /**
  6719. * @author alteredq / http://alteredqualia.com/
  6720. *
  6721. * parameters = {
  6722. * color: <hex>,
  6723. * opacity: <float>,
  6724. *
  6725. * blending: THREE.NormalBlending,
  6726. * depthTest: <bool>,
  6727. * depthWrite: <bool>,
  6728. *
  6729. * linewidth: <float>,
  6730. *
  6731. * scale: <float>,
  6732. * dashSize: <float>,
  6733. * gapSize: <float>,
  6734. *
  6735. * vertexColors: <bool>
  6736. *
  6737. * fog: <bool>
  6738. * }
  6739. */
  6740. THREE.LineDashedMaterial = function ( parameters ) {
  6741. THREE.Material.call( this );
  6742. this.color = new THREE.Color( 0xffffff );
  6743. this.linewidth = 1;
  6744. this.scale = 1;
  6745. this.dashSize = 3;
  6746. this.gapSize = 1;
  6747. this.vertexColors = false;
  6748. this.fog = true;
  6749. this.setValues( parameters );
  6750. };
  6751. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6752. THREE.LineDashedMaterial.prototype.clone = function () {
  6753. var material = new THREE.LineDashedMaterial();
  6754. THREE.Material.prototype.clone.call( this, material );
  6755. material.color.copy( this.color );
  6756. material.linewidth = this.linewidth;
  6757. material.scale = this.scale;
  6758. material.dashSize = this.dashSize;
  6759. material.gapSize = this.gapSize;
  6760. material.vertexColors = this.vertexColors;
  6761. material.fog = this.fog;
  6762. return material;
  6763. };
  6764. /**
  6765. * @author mrdoob / http://mrdoob.com/
  6766. * @author alteredq / http://alteredqualia.com/
  6767. *
  6768. * parameters = {
  6769. * color: <hex>,
  6770. * opacity: <float>,
  6771. * map: new THREE.Texture( <Image> ),
  6772. *
  6773. * lightMap: new THREE.Texture( <Image> ),
  6774. *
  6775. * specularMap: new THREE.Texture( <Image> ),
  6776. *
  6777. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6778. * combine: THREE.Multiply,
  6779. * reflectivity: <float>,
  6780. * refractionRatio: <float>,
  6781. *
  6782. * shading: THREE.SmoothShading,
  6783. * blending: THREE.NormalBlending,
  6784. * depthTest: <bool>,
  6785. * depthWrite: <bool>,
  6786. *
  6787. * wireframe: <boolean>,
  6788. * wireframeLinewidth: <float>,
  6789. *
  6790. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6791. *
  6792. * skinning: <bool>,
  6793. * morphTargets: <bool>,
  6794. *
  6795. * fog: <bool>
  6796. * }
  6797. */
  6798. THREE.MeshBasicMaterial = function ( parameters ) {
  6799. THREE.Material.call( this );
  6800. this.color = new THREE.Color( 0xffffff ); // emissive
  6801. this.map = null;
  6802. this.lightMap = null;
  6803. this.specularMap = null;
  6804. this.envMap = null;
  6805. this.combine = THREE.MultiplyOperation;
  6806. this.reflectivity = 1;
  6807. this.refractionRatio = 0.98;
  6808. this.fog = true;
  6809. this.shading = THREE.SmoothShading;
  6810. this.wireframe = false;
  6811. this.wireframeLinewidth = 1;
  6812. this.wireframeLinecap = 'round';
  6813. this.wireframeLinejoin = 'round';
  6814. this.vertexColors = THREE.NoColors;
  6815. this.skinning = false;
  6816. this.morphTargets = false;
  6817. this.setValues( parameters );
  6818. };
  6819. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6820. THREE.MeshBasicMaterial.prototype.clone = function () {
  6821. var material = new THREE.MeshBasicMaterial();
  6822. THREE.Material.prototype.clone.call( this, material );
  6823. material.color.copy( this.color );
  6824. material.map = this.map;
  6825. material.lightMap = this.lightMap;
  6826. material.specularMap = this.specularMap;
  6827. material.envMap = this.envMap;
  6828. material.combine = this.combine;
  6829. material.reflectivity = this.reflectivity;
  6830. material.refractionRatio = this.refractionRatio;
  6831. material.fog = this.fog;
  6832. material.shading = this.shading;
  6833. material.wireframe = this.wireframe;
  6834. material.wireframeLinewidth = this.wireframeLinewidth;
  6835. material.wireframeLinecap = this.wireframeLinecap;
  6836. material.wireframeLinejoin = this.wireframeLinejoin;
  6837. material.vertexColors = this.vertexColors;
  6838. material.skinning = this.skinning;
  6839. material.morphTargets = this.morphTargets;
  6840. return material;
  6841. };
  6842. /**
  6843. * @author mrdoob / http://mrdoob.com/
  6844. * @author alteredq / http://alteredqualia.com/
  6845. *
  6846. * parameters = {
  6847. * color: <hex>,
  6848. * ambient: <hex>,
  6849. * emissive: <hex>,
  6850. * opacity: <float>,
  6851. *
  6852. * map: new THREE.Texture( <Image> ),
  6853. *
  6854. * lightMap: new THREE.Texture( <Image> ),
  6855. *
  6856. * specularMap: new THREE.Texture( <Image> ),
  6857. *
  6858. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6859. * combine: THREE.Multiply,
  6860. * reflectivity: <float>,
  6861. * refractionRatio: <float>,
  6862. *
  6863. * shading: THREE.SmoothShading,
  6864. * blending: THREE.NormalBlending,
  6865. * depthTest: <bool>,
  6866. * depthWrite: <bool>,
  6867. *
  6868. * wireframe: <boolean>,
  6869. * wireframeLinewidth: <float>,
  6870. *
  6871. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6872. *
  6873. * skinning: <bool>,
  6874. * morphTargets: <bool>,
  6875. * morphNormals: <bool>,
  6876. *
  6877. * fog: <bool>
  6878. * }
  6879. */
  6880. THREE.MeshLambertMaterial = function ( parameters ) {
  6881. THREE.Material.call( this );
  6882. this.color = new THREE.Color( 0xffffff ); // diffuse
  6883. this.ambient = new THREE.Color( 0xffffff );
  6884. this.emissive = new THREE.Color( 0x000000 );
  6885. this.wrapAround = false;
  6886. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6887. this.map = null;
  6888. this.lightMap = null;
  6889. this.specularMap = null;
  6890. this.envMap = null;
  6891. this.combine = THREE.MultiplyOperation;
  6892. this.reflectivity = 1;
  6893. this.refractionRatio = 0.98;
  6894. this.fog = true;
  6895. this.shading = THREE.SmoothShading;
  6896. this.wireframe = false;
  6897. this.wireframeLinewidth = 1;
  6898. this.wireframeLinecap = 'round';
  6899. this.wireframeLinejoin = 'round';
  6900. this.vertexColors = THREE.NoColors;
  6901. this.skinning = false;
  6902. this.morphTargets = false;
  6903. this.morphNormals = false;
  6904. this.setValues( parameters );
  6905. };
  6906. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6907. THREE.MeshLambertMaterial.prototype.clone = function () {
  6908. var material = new THREE.MeshLambertMaterial();
  6909. THREE.Material.prototype.clone.call( this, material );
  6910. material.color.copy( this.color );
  6911. material.ambient.copy( this.ambient );
  6912. material.emissive.copy( this.emissive );
  6913. material.wrapAround = this.wrapAround;
  6914. material.wrapRGB.copy( this.wrapRGB );
  6915. material.map = this.map;
  6916. material.lightMap = this.lightMap;
  6917. material.specularMap = this.specularMap;
  6918. material.envMap = this.envMap;
  6919. material.combine = this.combine;
  6920. material.reflectivity = this.reflectivity;
  6921. material.refractionRatio = this.refractionRatio;
  6922. material.fog = this.fog;
  6923. material.shading = this.shading;
  6924. material.wireframe = this.wireframe;
  6925. material.wireframeLinewidth = this.wireframeLinewidth;
  6926. material.wireframeLinecap = this.wireframeLinecap;
  6927. material.wireframeLinejoin = this.wireframeLinejoin;
  6928. material.vertexColors = this.vertexColors;
  6929. material.skinning = this.skinning;
  6930. material.morphTargets = this.morphTargets;
  6931. material.morphNormals = this.morphNormals;
  6932. return material;
  6933. };
  6934. /**
  6935. * @author mrdoob / http://mrdoob.com/
  6936. * @author alteredq / http://alteredqualia.com/
  6937. *
  6938. * parameters = {
  6939. * color: <hex>,
  6940. * ambient: <hex>,
  6941. * emissive: <hex>,
  6942. * specular: <hex>,
  6943. * shininess: <float>,
  6944. * opacity: <float>,
  6945. *
  6946. * map: new THREE.Texture( <Image> ),
  6947. *
  6948. * lightMap: new THREE.Texture( <Image> ),
  6949. *
  6950. * bumpMap: new THREE.Texture( <Image> ),
  6951. * bumpScale: <float>,
  6952. *
  6953. * normalMap: new THREE.Texture( <Image> ),
  6954. * normalScale: <Vector2>,
  6955. *
  6956. * specularMap: new THREE.Texture( <Image> ),
  6957. *
  6958. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6959. * combine: THREE.Multiply,
  6960. * reflectivity: <float>,
  6961. * refractionRatio: <float>,
  6962. *
  6963. * shading: THREE.SmoothShading,
  6964. * blending: THREE.NormalBlending,
  6965. * depthTest: <bool>,
  6966. * depthWrite: <bool>,
  6967. *
  6968. * wireframe: <boolean>,
  6969. * wireframeLinewidth: <float>,
  6970. *
  6971. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6972. *
  6973. * skinning: <bool>,
  6974. * morphTargets: <bool>,
  6975. * morphNormals: <bool>,
  6976. *
  6977. * fog: <bool>
  6978. * }
  6979. */
  6980. THREE.MeshPhongMaterial = function ( parameters ) {
  6981. THREE.Material.call( this );
  6982. this.color = new THREE.Color( 0xffffff ); // diffuse
  6983. this.ambient = new THREE.Color( 0xffffff );
  6984. this.emissive = new THREE.Color( 0x000000 );
  6985. this.specular = new THREE.Color( 0x111111 );
  6986. this.shininess = 30;
  6987. this.metal = false;
  6988. this.perPixel = true;
  6989. this.wrapAround = false;
  6990. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6991. this.map = null;
  6992. this.lightMap = null;
  6993. this.bumpMap = null;
  6994. this.bumpScale = 1;
  6995. this.normalMap = null;
  6996. this.normalScale = new THREE.Vector2( 1, 1 );
  6997. this.specularMap = null;
  6998. this.envMap = null;
  6999. this.combine = THREE.MultiplyOperation;
  7000. this.reflectivity = 1;
  7001. this.refractionRatio = 0.98;
  7002. this.fog = true;
  7003. this.shading = THREE.SmoothShading;
  7004. this.wireframe = false;
  7005. this.wireframeLinewidth = 1;
  7006. this.wireframeLinecap = 'round';
  7007. this.wireframeLinejoin = 'round';
  7008. this.vertexColors = THREE.NoColors;
  7009. this.skinning = false;
  7010. this.morphTargets = false;
  7011. this.morphNormals = false;
  7012. this.setValues( parameters );
  7013. };
  7014. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7015. THREE.MeshPhongMaterial.prototype.clone = function () {
  7016. var material = new THREE.MeshPhongMaterial();
  7017. THREE.Material.prototype.clone.call( this, material );
  7018. material.color.copy( this.color );
  7019. material.ambient.copy( this.ambient );
  7020. material.emissive.copy( this.emissive );
  7021. material.specular.copy( this.specular );
  7022. material.shininess = this.shininess;
  7023. material.metal = this.metal;
  7024. material.perPixel = this.perPixel;
  7025. material.wrapAround = this.wrapAround;
  7026. material.wrapRGB.copy( this.wrapRGB );
  7027. material.map = this.map;
  7028. material.lightMap = this.lightMap;
  7029. material.bumpMap = this.bumpMap;
  7030. material.bumpScale = this.bumpScale;
  7031. material.normalMap = this.normalMap;
  7032. material.normalScale.copy( this.normalScale );
  7033. material.specularMap = this.specularMap;
  7034. material.envMap = this.envMap;
  7035. material.combine = this.combine;
  7036. material.reflectivity = this.reflectivity;
  7037. material.refractionRatio = this.refractionRatio;
  7038. material.fog = this.fog;
  7039. material.shading = this.shading;
  7040. material.wireframe = this.wireframe;
  7041. material.wireframeLinewidth = this.wireframeLinewidth;
  7042. material.wireframeLinecap = this.wireframeLinecap;
  7043. material.wireframeLinejoin = this.wireframeLinejoin;
  7044. material.vertexColors = this.vertexColors;
  7045. material.skinning = this.skinning;
  7046. material.morphTargets = this.morphTargets;
  7047. material.morphNormals = this.morphNormals;
  7048. return material;
  7049. };
  7050. /**
  7051. * @author mrdoob / http://mrdoob.com/
  7052. * @author alteredq / http://alteredqualia.com/
  7053. *
  7054. * parameters = {
  7055. * opacity: <float>,
  7056. *
  7057. * blending: THREE.NormalBlending,
  7058. * depthTest: <bool>,
  7059. * depthWrite: <bool>,
  7060. *
  7061. * wireframe: <boolean>,
  7062. * wireframeLinewidth: <float>
  7063. * }
  7064. */
  7065. THREE.MeshDepthMaterial = function ( parameters ) {
  7066. THREE.Material.call( this );
  7067. this.wireframe = false;
  7068. this.wireframeLinewidth = 1;
  7069. this.setValues( parameters );
  7070. };
  7071. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7072. THREE.MeshDepthMaterial.prototype.clone = function () {
  7073. var material = new THREE.LineBasicMaterial();
  7074. THREE.Material.prototype.clone.call( this, material );
  7075. material.wireframe = this.wireframe;
  7076. material.wireframeLinewidth = this.wireframeLinewidth;
  7077. return material;
  7078. };
  7079. /**
  7080. * @author mrdoob / http://mrdoob.com/
  7081. *
  7082. * parameters = {
  7083. * opacity: <float>,
  7084. *
  7085. * shading: THREE.FlatShading,
  7086. * blending: THREE.NormalBlending,
  7087. * depthTest: <bool>,
  7088. * depthWrite: <bool>,
  7089. *
  7090. * wireframe: <boolean>,
  7091. * wireframeLinewidth: <float>
  7092. * }
  7093. */
  7094. THREE.MeshNormalMaterial = function ( parameters ) {
  7095. THREE.Material.call( this, parameters );
  7096. this.shading = THREE.FlatShading;
  7097. this.wireframe = false;
  7098. this.wireframeLinewidth = 1;
  7099. this.setValues( parameters );
  7100. };
  7101. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7102. THREE.MeshNormalMaterial.prototype.clone = function () {
  7103. var material = new THREE.MeshNormalMaterial();
  7104. THREE.Material.prototype.clone.call( this, material );
  7105. material.shading = this.shading;
  7106. material.wireframe = this.wireframe;
  7107. material.wireframeLinewidth = this.wireframeLinewidth;
  7108. return material;
  7109. };
  7110. /**
  7111. * @author mrdoob / http://mrdoob.com/
  7112. */
  7113. THREE.MeshFaceMaterial = function ( materials ) {
  7114. this.materials = materials instanceof Array ? materials : [];
  7115. };
  7116. THREE.MeshFaceMaterial.prototype.clone = function () {
  7117. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7118. };
  7119. /**
  7120. * @author mrdoob / http://mrdoob.com/
  7121. * @author alteredq / http://alteredqualia.com/
  7122. *
  7123. * parameters = {
  7124. * color: <hex>,
  7125. * opacity: <float>,
  7126. * map: new THREE.Texture( <Image> ),
  7127. *
  7128. * size: <float>,
  7129. *
  7130. * blending: THREE.NormalBlending,
  7131. * depthTest: <bool>,
  7132. * depthWrite: <bool>,
  7133. *
  7134. * vertexColors: <bool>,
  7135. *
  7136. * fog: <bool>
  7137. * }
  7138. */
  7139. THREE.ParticleBasicMaterial = function ( parameters ) {
  7140. THREE.Material.call( this );
  7141. this.color = new THREE.Color( 0xffffff );
  7142. this.map = null;
  7143. this.size = 1;
  7144. this.sizeAttenuation = true;
  7145. this.vertexColors = false;
  7146. this.fog = true;
  7147. this.setValues( parameters );
  7148. };
  7149. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7150. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7151. var material = new THREE.ParticleBasicMaterial();
  7152. THREE.Material.prototype.clone.call( this, material );
  7153. material.color.copy( this.color );
  7154. material.map = this.map;
  7155. material.size = this.size;
  7156. material.sizeAttenuation = this.sizeAttenuation;
  7157. material.vertexColors = this.vertexColors;
  7158. material.fog = this.fog;
  7159. return material;
  7160. };
  7161. /**
  7162. * @author mrdoob / http://mrdoob.com/
  7163. *
  7164. * parameters = {
  7165. * color: <hex>,
  7166. * program: <function>,
  7167. * opacity: <float>,
  7168. * blending: THREE.NormalBlending
  7169. * }
  7170. */
  7171. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7172. THREE.Material.call( this );
  7173. this.color = new THREE.Color( 0xffffff );
  7174. this.program = function ( context, color ) {};
  7175. this.setValues( parameters );
  7176. };
  7177. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7178. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7179. var material = new THREE.ParticleCanvasMaterial();
  7180. THREE.Material.prototype.clone.call( this, material );
  7181. material.color.copy( this.color );
  7182. material.program = this.program;
  7183. return material;
  7184. };
  7185. /**
  7186. * @author mrdoob / http://mrdoob.com/
  7187. */
  7188. THREE.ParticleDOMMaterial = function ( element ) {
  7189. this.element = element;
  7190. };
  7191. THREE.ParticleDOMMaterial.prototype.clone = function(){
  7192. return new THREE.ParticleDOMMaterial( this.element );
  7193. };
  7194. /**
  7195. * @author alteredq / http://alteredqualia.com/
  7196. *
  7197. * parameters = {
  7198. * fragmentShader: <string>,
  7199. * vertexShader: <string>,
  7200. *
  7201. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7202. *
  7203. * defines: { "label" : "value" },
  7204. *
  7205. * shading: THREE.SmoothShading,
  7206. * blending: THREE.NormalBlending,
  7207. * depthTest: <bool>,
  7208. * depthWrite: <bool>,
  7209. *
  7210. * wireframe: <boolean>,
  7211. * wireframeLinewidth: <float>,
  7212. *
  7213. * lights: <bool>,
  7214. *
  7215. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7216. *
  7217. * skinning: <bool>,
  7218. * morphTargets: <bool>,
  7219. * morphNormals: <bool>,
  7220. *
  7221. * fog: <bool>
  7222. * }
  7223. */
  7224. THREE.ShaderMaterial = function ( parameters ) {
  7225. THREE.Material.call( this );
  7226. this.fragmentShader = "void main() {}";
  7227. this.vertexShader = "void main() {}";
  7228. this.uniforms = {};
  7229. this.defines = {};
  7230. this.attributes = null;
  7231. this.shading = THREE.SmoothShading;
  7232. this.wireframe = false;
  7233. this.wireframeLinewidth = 1;
  7234. this.fog = false; // set to use scene fog
  7235. this.lights = false; // set to use scene lights
  7236. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7237. this.skinning = false; // set to use skinning attribute streams
  7238. this.morphTargets = false; // set to use morph targets
  7239. this.morphNormals = false; // set to use morph normals
  7240. this.setValues( parameters );
  7241. };
  7242. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7243. THREE.ShaderMaterial.prototype.clone = function () {
  7244. var material = new THREE.ShaderMaterial();
  7245. THREE.Material.prototype.clone.call( this, material );
  7246. material.fragmentShader = this.fragmentShader;
  7247. material.vertexShader = this.vertexShader;
  7248. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7249. material.attributes = this.attributes;
  7250. material.defines = this.defines;
  7251. material.shading = this.shading;
  7252. material.wireframe = this.wireframe;
  7253. material.wireframeLinewidth = this.wireframeLinewidth;
  7254. material.fog = this.fog;
  7255. material.lights = this.lights;
  7256. material.vertexColors = this.vertexColors;
  7257. material.skinning = this.skinning;
  7258. material.morphTargets = this.morphTargets;
  7259. material.morphNormals = this.morphNormals;
  7260. return material;
  7261. };
  7262. /**
  7263. * @author alteredq / http://alteredqualia.com/
  7264. *
  7265. * parameters = {
  7266. * color: <hex>,
  7267. * opacity: <float>,
  7268. * map: new THREE.Texture( <Image> ),
  7269. *
  7270. * blending: THREE.NormalBlending,
  7271. * depthTest: <bool>,
  7272. * depthWrite: <bool>,
  7273. *
  7274. * useScreenCoordinates: <bool>,
  7275. * sizeAttenuation: <bool>,
  7276. * scaleByViewport: <bool>,
  7277. * alignment: THREE.SpriteAlignment.center,
  7278. *
  7279. * uvOffset: new THREE.Vector2(),
  7280. * uvScale: new THREE.Vector2(),
  7281. *
  7282. * fog: <bool>
  7283. * }
  7284. */
  7285. THREE.SpriteMaterial = function ( parameters ) {
  7286. THREE.Material.call( this );
  7287. // defaults
  7288. this.color = new THREE.Color( 0xffffff );
  7289. this.map = new THREE.Texture();
  7290. this.useScreenCoordinates = true;
  7291. this.depthTest = !this.useScreenCoordinates;
  7292. this.sizeAttenuation = !this.useScreenCoordinates;
  7293. this.scaleByViewport = !this.sizeAttenuation;
  7294. this.alignment = THREE.SpriteAlignment.center.clone();
  7295. this.fog = false;
  7296. this.uvOffset = new THREE.Vector2( 0, 0 );
  7297. this.uvScale = new THREE.Vector2( 1, 1 );
  7298. // set parameters
  7299. this.setValues( parameters );
  7300. // override coupled defaults if not specified explicitly by parameters
  7301. parameters = parameters || {};
  7302. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7303. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7304. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7305. };
  7306. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7307. THREE.SpriteMaterial.prototype.clone = function () {
  7308. var material = new THREE.SpriteMaterial();
  7309. THREE.Material.prototype.clone.call( this, material );
  7310. material.color.copy( this.color );
  7311. material.map = this.map;
  7312. material.useScreenCoordinates = this.useScreenCoordinates;
  7313. material.sizeAttenuation = this.sizeAttenuation;
  7314. material.scaleByViewport = this.scaleByViewport;
  7315. material.alignment.copy( this.alignment );
  7316. material.uvOffset.copy( this.uvOffset );
  7317. material.uvScale.copy( this.uvScale );
  7318. material.fog = this.fog;
  7319. return material;
  7320. };
  7321. // Alignment enums
  7322. THREE.SpriteAlignment = {};
  7323. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7324. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7325. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7326. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7327. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7328. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7329. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7330. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7331. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7332. /**
  7333. * @author mrdoob / http://mrdoob.com/
  7334. * @author alteredq / http://alteredqualia.com/
  7335. * @author szimek / https://github.com/szimek/
  7336. */
  7337. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7338. THREE.EventDispatcher.call( this );
  7339. this.id = THREE.TextureIdCount ++;
  7340. this.name = '';
  7341. this.image = image;
  7342. this.mipmaps = [];
  7343. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7344. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7345. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7346. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7347. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7348. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7349. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7350. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7351. this.offset = new THREE.Vector2( 0, 0 );
  7352. this.repeat = new THREE.Vector2( 1, 1 );
  7353. this.generateMipmaps = true;
  7354. this.premultiplyAlpha = false;
  7355. this.flipY = true;
  7356. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7357. this.needsUpdate = false;
  7358. this.onUpdate = null;
  7359. };
  7360. THREE.Texture.prototype = {
  7361. constructor: THREE.Texture,
  7362. clone: function ( texture ) {
  7363. if ( texture === undefined ) texture = new THREE.Texture();
  7364. texture.image = this.image;
  7365. texture.mipmaps = this.mipmaps.slice(0);
  7366. texture.mapping = this.mapping;
  7367. texture.wrapS = this.wrapS;
  7368. texture.wrapT = this.wrapT;
  7369. texture.magFilter = this.magFilter;
  7370. texture.minFilter = this.minFilter;
  7371. texture.anisotropy = this.anisotropy;
  7372. texture.format = this.format;
  7373. texture.type = this.type;
  7374. texture.offset.copy( this.offset );
  7375. texture.repeat.copy( this.repeat );
  7376. texture.generateMipmaps = this.generateMipmaps;
  7377. texture.premultiplyAlpha = this.premultiplyAlpha;
  7378. texture.flipY = this.flipY;
  7379. texture.unpackAlignment = this.unpackAlignment;
  7380. return texture;
  7381. },
  7382. dispose: function () {
  7383. this.dispatchEvent( { type: 'dispose' } );
  7384. }
  7385. };
  7386. THREE.TextureIdCount = 0;
  7387. /**
  7388. * @author alteredq / http://alteredqualia.com/
  7389. */
  7390. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7391. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7392. this.image = { width: width, height: height };
  7393. this.mipmaps = mipmaps;
  7394. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7395. };
  7396. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7397. THREE.CompressedTexture.prototype.clone = function () {
  7398. var texture = new THREE.CompressedTexture();
  7399. THREE.Texture.prototype.clone.call( this, texture );
  7400. return texture;
  7401. };
  7402. /**
  7403. * @author alteredq / http://alteredqualia.com/
  7404. */
  7405. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7406. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7407. this.image = { data: data, width: width, height: height };
  7408. };
  7409. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7410. THREE.DataTexture.prototype.clone = function () {
  7411. var texture = new THREE.DataTexture();
  7412. THREE.Texture.prototype.clone.call( this, texture );
  7413. return texture;
  7414. };
  7415. /**
  7416. * @author mrdoob / http://mrdoob.com/
  7417. */
  7418. THREE.Particle = function ( material ) {
  7419. THREE.Object3D.call( this );
  7420. this.material = material;
  7421. };
  7422. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7423. THREE.Particle.prototype.clone = function ( object ) {
  7424. if ( object === undefined ) object = new THREE.Particle( this.material );
  7425. THREE.Object3D.prototype.clone.call( this, object );
  7426. return object;
  7427. };
  7428. /**
  7429. * @author alteredq / http://alteredqualia.com/
  7430. */
  7431. THREE.ParticleSystem = function ( geometry, material ) {
  7432. THREE.Object3D.call( this );
  7433. this.geometry = geometry;
  7434. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7435. this.sortParticles = false;
  7436. if ( this.geometry ) {
  7437. // calc bound radius
  7438. if( this.geometry.boundingSphere === null ) {
  7439. this.geometry.computeBoundingSphere();
  7440. }
  7441. }
  7442. this.frustumCulled = false;
  7443. };
  7444. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7445. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7446. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7447. object.sortParticles = this.sortParticles;
  7448. THREE.Object3D.prototype.clone.call( this, object );
  7449. return object;
  7450. };
  7451. /**
  7452. * @author mrdoob / http://mrdoob.com/
  7453. */
  7454. THREE.Line = function ( geometry, material, type ) {
  7455. THREE.Object3D.call( this );
  7456. this.geometry = geometry;
  7457. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7458. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7459. if ( this.geometry ) {
  7460. if ( ! this.geometry.boundingSphere ) {
  7461. this.geometry.computeBoundingSphere();
  7462. }
  7463. }
  7464. };
  7465. THREE.LineStrip = 0;
  7466. THREE.LinePieces = 1;
  7467. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7468. THREE.Line.prototype.clone = function ( object ) {
  7469. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7470. THREE.Object3D.prototype.clone.call( this, object );
  7471. return object;
  7472. };
  7473. /**
  7474. * @author mrdoob / http://mrdoob.com/
  7475. * @author alteredq / http://alteredqualia.com/
  7476. * @author mikael emtinger / http://gomo.se/
  7477. */
  7478. THREE.Mesh = function ( geometry, material ) {
  7479. THREE.Object3D.call( this );
  7480. this.geometry = geometry;
  7481. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7482. if ( this.geometry ) {
  7483. // calc bound radius
  7484. if ( this.geometry.boundingSphere === null ) {
  7485. this.geometry.computeBoundingSphere();
  7486. }
  7487. // setup morph targets
  7488. if ( this.geometry.morphTargets.length ) {
  7489. this.morphTargetBase = -1;
  7490. this.morphTargetForcedOrder = [];
  7491. this.morphTargetInfluences = [];
  7492. this.morphTargetDictionary = {};
  7493. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  7494. this.morphTargetInfluences.push( 0 );
  7495. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7496. }
  7497. }
  7498. }
  7499. }
  7500. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7501. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7502. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7503. return this.morphTargetDictionary[ name ];
  7504. }
  7505. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7506. return 0;
  7507. };
  7508. THREE.Mesh.prototype.clone = function ( object ) {
  7509. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7510. THREE.Object3D.prototype.clone.call( this, object );
  7511. return object;
  7512. };
  7513. /**
  7514. * @author mikael emtinger / http://gomo.se/
  7515. * @author alteredq / http://alteredqualia.com/
  7516. */
  7517. THREE.Bone = function( belongsToSkin ) {
  7518. THREE.Object3D.call( this );
  7519. this.skin = belongsToSkin;
  7520. this.skinMatrix = new THREE.Matrix4();
  7521. };
  7522. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7523. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  7524. // update local
  7525. if ( this.matrixAutoUpdate ) {
  7526. forceUpdate |= this.updateMatrix();
  7527. }
  7528. // update skin matrix
  7529. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7530. if( parentSkinMatrix ) {
  7531. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  7532. } else {
  7533. this.skinMatrix.copy( this.matrix );
  7534. }
  7535. this.matrixWorldNeedsUpdate = false;
  7536. forceUpdate = true;
  7537. }
  7538. // update children
  7539. var child, i, l = this.children.length;
  7540. for ( i = 0; i < l; i ++ ) {
  7541. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7542. }
  7543. };
  7544. /**
  7545. * @author mikael emtinger / http://gomo.se/
  7546. * @author alteredq / http://alteredqualia.com/
  7547. */
  7548. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7549. THREE.Mesh.call( this, geometry, material );
  7550. //
  7551. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7552. // init bones
  7553. this.identityMatrix = new THREE.Matrix4();
  7554. this.bones = [];
  7555. this.boneMatrices = [];
  7556. var b, bone, gbone, p, q, s;
  7557. if ( this.geometry && this.geometry.bones !== undefined ) {
  7558. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7559. gbone = this.geometry.bones[ b ];
  7560. p = gbone.pos;
  7561. q = gbone.rotq;
  7562. s = gbone.scl;
  7563. bone = this.addBone();
  7564. bone.name = gbone.name;
  7565. bone.position.set( p[0], p[1], p[2] );
  7566. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7567. bone.useQuaternion = true;
  7568. if ( s !== undefined ) {
  7569. bone.scale.set( s[0], s[1], s[2] );
  7570. } else {
  7571. bone.scale.set( 1, 1, 1 );
  7572. }
  7573. }
  7574. for ( b = 0; b < this.bones.length; b ++ ) {
  7575. gbone = this.geometry.bones[ b ];
  7576. bone = this.bones[ b ];
  7577. if ( gbone.parent === -1 ) {
  7578. this.add( bone );
  7579. } else {
  7580. this.bones[ gbone.parent ].add( bone );
  7581. }
  7582. }
  7583. //
  7584. var nBones = this.bones.length;
  7585. if ( this.useVertexTexture ) {
  7586. // layout (1 matrix = 4 pixels)
  7587. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7588. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7589. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7590. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7591. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7592. var size;
  7593. if ( nBones > 256 )
  7594. size = 64;
  7595. else if ( nBones > 64 )
  7596. size = 32;
  7597. else if ( nBones > 16 )
  7598. size = 16;
  7599. else
  7600. size = 8;
  7601. this.boneTextureWidth = size;
  7602. this.boneTextureHeight = size;
  7603. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7604. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7605. this.boneTexture.minFilter = THREE.NearestFilter;
  7606. this.boneTexture.magFilter = THREE.NearestFilter;
  7607. this.boneTexture.generateMipmaps = false;
  7608. this.boneTexture.flipY = false;
  7609. } else {
  7610. this.boneMatrices = new Float32Array( 16 * nBones );
  7611. }
  7612. this.pose();
  7613. }
  7614. };
  7615. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7616. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7617. if ( bone === undefined ) {
  7618. bone = new THREE.Bone( this );
  7619. }
  7620. this.bones.push( bone );
  7621. return bone;
  7622. };
  7623. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7624. this.matrixAutoUpdate && this.updateMatrix();
  7625. // update matrixWorld
  7626. if ( this.matrixWorldNeedsUpdate || force ) {
  7627. if ( this.parent ) {
  7628. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  7629. } else {
  7630. this.matrixWorld.copy( this.matrix );
  7631. }
  7632. this.matrixWorldNeedsUpdate = false;
  7633. force = true;
  7634. }
  7635. // update children
  7636. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7637. var child = this.children[ i ];
  7638. if ( child instanceof THREE.Bone ) {
  7639. child.update( this.identityMatrix, false );
  7640. } else {
  7641. child.updateMatrixWorld( true );
  7642. }
  7643. }
  7644. // make a snapshot of the bones' rest position
  7645. if ( this.boneInverses == undefined ) {
  7646. this.boneInverses = [];
  7647. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7648. var inverse = new THREE.Matrix4();
  7649. inverse.getInverse( this.bones[ b ].skinMatrix );
  7650. this.boneInverses.push( inverse );
  7651. }
  7652. }
  7653. // flatten bone matrices to array
  7654. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7655. // compute the offset between the current and the original transform;
  7656. //TODO: we could get rid of this multiplication step if the skinMatrix
  7657. // was already representing the offset; however, this requires some
  7658. // major changes to the animation system
  7659. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7660. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7661. }
  7662. if ( this.useVertexTexture ) {
  7663. this.boneTexture.needsUpdate = true;
  7664. }
  7665. };
  7666. THREE.SkinnedMesh.prototype.pose = function() {
  7667. this.updateMatrixWorld( true );
  7668. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7669. // normalize weights
  7670. var sw = this.geometry.skinWeights[ i ];
  7671. var scale = 1.0 / sw.lengthManhattan();
  7672. if ( scale !== Infinity ) {
  7673. sw.multiplyScalar( scale );
  7674. } else {
  7675. sw.set( 1 ); // this will be normalized by the shader anyway
  7676. }
  7677. }
  7678. };
  7679. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7680. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7681. THREE.Mesh.prototype.clone.call( this, object );
  7682. return object;
  7683. };
  7684. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7685. /**
  7686. * @author alteredq / http://alteredqualia.com/
  7687. */
  7688. THREE.MorphAnimMesh = function ( geometry, material ) {
  7689. THREE.Mesh.call( this, geometry, material );
  7690. // API
  7691. this.duration = 1000; // milliseconds
  7692. this.mirroredLoop = false;
  7693. this.time = 0;
  7694. // internals
  7695. this.lastKeyframe = 0;
  7696. this.currentKeyframe = 0;
  7697. this.direction = 1;
  7698. this.directionBackwards = false;
  7699. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7700. };
  7701. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7702. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7703. this.startKeyframe = start;
  7704. this.endKeyframe = end;
  7705. this.length = this.endKeyframe - this.startKeyframe + 1;
  7706. };
  7707. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7708. this.direction = 1;
  7709. this.directionBackwards = false;
  7710. };
  7711. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7712. this.direction = -1;
  7713. this.directionBackwards = true;
  7714. };
  7715. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7716. var geometry = this.geometry;
  7717. if ( ! geometry.animations ) geometry.animations = {};
  7718. var firstAnimation, animations = geometry.animations;
  7719. var pattern = /([a-z]+)(\d+)/;
  7720. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7721. var morph = geometry.morphTargets[ i ];
  7722. var parts = morph.name.match( pattern );
  7723. if ( parts && parts.length > 1 ) {
  7724. var label = parts[ 1 ];
  7725. var num = parts[ 2 ];
  7726. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7727. var animation = animations[ label ];
  7728. if ( i < animation.start ) animation.start = i;
  7729. if ( i > animation.end ) animation.end = i;
  7730. if ( ! firstAnimation ) firstAnimation = label;
  7731. }
  7732. }
  7733. geometry.firstAnimation = firstAnimation;
  7734. };
  7735. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7736. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7737. this.geometry.animations[ label ] = { start: start, end: end };
  7738. };
  7739. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7740. var animation = this.geometry.animations[ label ];
  7741. if ( animation ) {
  7742. this.setFrameRange( animation.start, animation.end );
  7743. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7744. this.time = 0;
  7745. } else {
  7746. console.warn( "animation[" + label + "] undefined" );
  7747. }
  7748. };
  7749. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7750. var frameTime = this.duration / this.length;
  7751. this.time += this.direction * delta;
  7752. if ( this.mirroredLoop ) {
  7753. if ( this.time > this.duration || this.time < 0 ) {
  7754. this.direction *= -1;
  7755. if ( this.time > this.duration ) {
  7756. this.time = this.duration;
  7757. this.directionBackwards = true;
  7758. }
  7759. if ( this.time < 0 ) {
  7760. this.time = 0;
  7761. this.directionBackwards = false;
  7762. }
  7763. }
  7764. } else {
  7765. this.time = this.time % this.duration;
  7766. if ( this.time < 0 ) this.time += this.duration;
  7767. }
  7768. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7769. if ( keyframe !== this.currentKeyframe ) {
  7770. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7771. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7772. this.morphTargetInfluences[ keyframe ] = 0;
  7773. this.lastKeyframe = this.currentKeyframe;
  7774. this.currentKeyframe = keyframe;
  7775. }
  7776. var mix = ( this.time % frameTime ) / frameTime;
  7777. if ( this.directionBackwards ) {
  7778. mix = 1 - mix;
  7779. }
  7780. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7781. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7782. };
  7783. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7784. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7785. object.duration = this.duration;
  7786. object.mirroredLoop = this.mirroredLoop;
  7787. object.time = this.time;
  7788. object.lastKeyframe = this.lastKeyframe;
  7789. object.currentKeyframe = this.currentKeyframe;
  7790. object.direction = this.direction;
  7791. object.directionBackwards = this.directionBackwards;
  7792. THREE.Mesh.prototype.clone.call( this, object );
  7793. return object;
  7794. };
  7795. /**
  7796. * @author alteredq / http://alteredqualia.com/
  7797. */
  7798. THREE.Ribbon = function ( geometry, material ) {
  7799. THREE.Object3D.call( this );
  7800. this.geometry = geometry;
  7801. this.material = material;
  7802. };
  7803. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7804. THREE.Ribbon.prototype.clone = function ( object ) {
  7805. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7806. THREE.Object3D.prototype.clone.call( this, object );
  7807. return object;
  7808. };
  7809. /**
  7810. * @author mikael emtinger / http://gomo.se/
  7811. * @author alteredq / http://alteredqualia.com/
  7812. * @author mrdoob / http://mrdoob.com/
  7813. */
  7814. THREE.LOD = function () {
  7815. THREE.Object3D.call( this );
  7816. this.LODs = [];
  7817. };
  7818. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7819. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7820. if ( visibleAtDistance === undefined ) {
  7821. visibleAtDistance = 0;
  7822. }
  7823. visibleAtDistance = Math.abs( visibleAtDistance );
  7824. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7825. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7826. break;
  7827. }
  7828. }
  7829. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7830. this.add( object3D );
  7831. };
  7832. THREE.LOD.prototype.update = function ( camera ) {
  7833. if ( this.LODs.length > 1 ) {
  7834. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7835. var inverse = camera.matrixWorldInverse;
  7836. 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] );
  7837. this.LODs[ 0 ].object3D.visible = true;
  7838. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7839. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7840. this.LODs[ l - 1 ].object3D.visible = false;
  7841. this.LODs[ l ].object3D.visible = true;
  7842. } else {
  7843. break;
  7844. }
  7845. }
  7846. for( ; l < this.LODs.length; l ++ ) {
  7847. this.LODs[ l ].object3D.visible = false;
  7848. }
  7849. }
  7850. };
  7851. THREE.LOD.prototype.clone = function () {
  7852. // TODO
  7853. };
  7854. /**
  7855. * @author mikael emtinger / http://gomo.se/
  7856. * @author alteredq / http://alteredqualia.com/
  7857. */
  7858. THREE.Sprite = function ( material ) {
  7859. THREE.Object3D.call( this );
  7860. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7861. this.rotation3d = this.rotation;
  7862. this.rotation = 0;
  7863. };
  7864. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7865. /*
  7866. * Custom update matrix
  7867. */
  7868. THREE.Sprite.prototype.updateMatrix = function () {
  7869. this.matrix.setPosition( this.position );
  7870. this.rotation3d.set( 0, 0, this.rotation );
  7871. this.matrix.setRotationFromEuler( this.rotation3d );
  7872. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7873. this.matrix.scale( this.scale );
  7874. }
  7875. this.matrixWorldNeedsUpdate = true;
  7876. };
  7877. THREE.Sprite.prototype.clone = function ( object ) {
  7878. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7879. THREE.Object3D.prototype.clone.call( this, object );
  7880. return object;
  7881. };
  7882. /**
  7883. * @author mrdoob / http://mrdoob.com/
  7884. */
  7885. THREE.Scene = function () {
  7886. THREE.Object3D.call( this );
  7887. this.fog = null;
  7888. this.overrideMaterial = null;
  7889. this.matrixAutoUpdate = false;
  7890. this.__objects = [];
  7891. this.__lights = [];
  7892. this.__objectsAdded = [];
  7893. this.__objectsRemoved = [];
  7894. };
  7895. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7896. THREE.Scene.prototype.__addObject = function ( object ) {
  7897. if ( object instanceof THREE.Light ) {
  7898. if ( this.__lights.indexOf( object ) === - 1 ) {
  7899. this.__lights.push( object );
  7900. }
  7901. if ( object.target && object.target.parent === undefined ) {
  7902. this.add( object.target );
  7903. }
  7904. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7905. if ( this.__objects.indexOf( object ) === - 1 ) {
  7906. this.__objects.push( object );
  7907. this.__objectsAdded.push( object );
  7908. // check if previously removed
  7909. var i = this.__objectsRemoved.indexOf( object );
  7910. if ( i !== -1 ) {
  7911. this.__objectsRemoved.splice( i, 1 );
  7912. }
  7913. }
  7914. }
  7915. for ( var c = 0; c < object.children.length; c ++ ) {
  7916. this.__addObject( object.children[ c ] );
  7917. }
  7918. };
  7919. THREE.Scene.prototype.__removeObject = function ( object ) {
  7920. if ( object instanceof THREE.Light ) {
  7921. var i = this.__lights.indexOf( object );
  7922. if ( i !== -1 ) {
  7923. this.__lights.splice( i, 1 );
  7924. }
  7925. } else if ( !( object instanceof THREE.Camera ) ) {
  7926. var i = this.__objects.indexOf( object );
  7927. if( i !== -1 ) {
  7928. this.__objects.splice( i, 1 );
  7929. this.__objectsRemoved.push( object );
  7930. // check if previously added
  7931. var ai = this.__objectsAdded.indexOf( object );
  7932. if ( ai !== -1 ) {
  7933. this.__objectsAdded.splice( ai, 1 );
  7934. }
  7935. }
  7936. }
  7937. for ( var c = 0; c < object.children.length; c ++ ) {
  7938. this.__removeObject( object.children[ c ] );
  7939. }
  7940. };
  7941. /**
  7942. * @author mrdoob / http://mrdoob.com/
  7943. * @author alteredq / http://alteredqualia.com/
  7944. */
  7945. THREE.Fog = function ( hex, near, far ) {
  7946. this.name = '';
  7947. this.color = new THREE.Color( hex );
  7948. this.near = ( near !== undefined ) ? near : 1;
  7949. this.far = ( far !== undefined ) ? far : 1000;
  7950. };
  7951. THREE.Fog.prototype.clone = function () {
  7952. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7953. };
  7954. /**
  7955. * @author mrdoob / http://mrdoob.com/
  7956. * @author alteredq / http://alteredqualia.com/
  7957. */
  7958. THREE.FogExp2 = function ( hex, density ) {
  7959. this.name = '';
  7960. this.color = new THREE.Color( hex );
  7961. this.density = ( density !== undefined ) ? density : 0.00025;
  7962. };
  7963. THREE.FogExp2.prototype.clone = function () {
  7964. return new THREE.FogExp2( this.color.getHex(), this.density );
  7965. };
  7966. /**
  7967. * @author mrdoob / http://mrdoob.com/
  7968. */
  7969. THREE.CanvasRenderer = function ( parameters ) {
  7970. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7971. parameters = parameters || {};
  7972. var _this = this,
  7973. _renderData, _elements, _lights,
  7974. _projector = new THREE.Projector(),
  7975. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  7976. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7977. _context = _canvas.getContext( '2d' ),
  7978. _clearColor = new THREE.Color( 0x000000 ),
  7979. _clearOpacity = 0,
  7980. _contextGlobalAlpha = 1,
  7981. _contextGlobalCompositeOperation = 0,
  7982. _contextStrokeStyle = null,
  7983. _contextFillStyle = null,
  7984. _contextLineWidth = null,
  7985. _contextLineCap = null,
  7986. _contextLineJoin = null,
  7987. _v1, _v2, _v3, _v4,
  7988. _v5 = new THREE.RenderableVertex(),
  7989. _v6 = new THREE.RenderableVertex(),
  7990. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7991. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7992. _color = new THREE.Color(),
  7993. _color1 = new THREE.Color(),
  7994. _color2 = new THREE.Color(),
  7995. _color3 = new THREE.Color(),
  7996. _color4 = new THREE.Color(),
  7997. _diffuseColor = new THREE.Color(),
  7998. _emissiveColor = new THREE.Color(),
  7999. _patterns = {}, _imagedatas = {},
  8000. _near, _far,
  8001. _image, _uvs,
  8002. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  8003. _clipBox = new THREE.Box2(),
  8004. _clearBox = new THREE.Box2(),
  8005. _elemBox = new THREE.Box2(),
  8006. _enableLighting = false,
  8007. _ambientLight = new THREE.Color(),
  8008. _directionalLights = new THREE.Color(),
  8009. _pointLights = new THREE.Color(),
  8010. _pi2 = Math.PI * 2,
  8011. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8012. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8013. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8014. _pixelMap = document.createElement( 'canvas' );
  8015. _pixelMap.width = _pixelMap.height = 2;
  8016. _pixelMapContext = _pixelMap.getContext( '2d' );
  8017. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8018. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8019. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8020. _pixelMapData = _pixelMapImage.data;
  8021. _gradientMap = document.createElement( 'canvas' );
  8022. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8023. _gradientMapContext = _gradientMap.getContext( '2d' );
  8024. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8025. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8026. _gradientMapQuality --; // Fix UVs
  8027. this.domElement = _canvas;
  8028. this.autoClear = true;
  8029. this.sortObjects = true;
  8030. this.sortElements = true;
  8031. this.info = {
  8032. render: {
  8033. vertices: 0,
  8034. faces: 0
  8035. }
  8036. }
  8037. this.setSize = function ( width, height ) {
  8038. _canvasWidth = width;
  8039. _canvasHeight = height;
  8040. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8041. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8042. _canvas.width = _canvasWidth;
  8043. _canvas.height = _canvasHeight;
  8044. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8045. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8046. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8047. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8048. _contextGlobalAlpha = 1;
  8049. _contextGlobalCompositeOperation = 0;
  8050. _contextStrokeStyle = null;
  8051. _contextFillStyle = null;
  8052. _contextLineWidth = null;
  8053. _contextLineCap = null;
  8054. _contextLineJoin = null;
  8055. };
  8056. this.setClearColor = function ( color, opacity ) {
  8057. _clearColor.copy( color );
  8058. _clearOpacity = opacity !== undefined ? opacity : 1;
  8059. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8060. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8061. };
  8062. this.setClearColorHex = function ( hex, opacity ) {
  8063. _clearColor.setHex( hex );
  8064. _clearOpacity = opacity !== undefined ? opacity : 1;
  8065. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8066. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8067. };
  8068. this.getMaxAnisotropy = function () {
  8069. return 0;
  8070. };
  8071. this.clear = function () {
  8072. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8073. if ( _clearBox.empty() === false ) {
  8074. _clearBox.intersect( _clipBox );
  8075. _clearBox.expandByScalar( 2 );
  8076. if ( _clearOpacity < 1 ) {
  8077. _context.clearRect( _clearBox.min.x | 0, _clearBox.min.y | 0, ( _clearBox.max.x - _clearBox.min.x ) | 0, ( _clearBox.max.y - _clearBox.min.y ) | 0 );
  8078. }
  8079. if ( _clearOpacity > 0 ) {
  8080. setBlending( THREE.NormalBlending );
  8081. setOpacity( 1 );
  8082. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  8083. _context.fillRect( _clearBox.min.x | 0, _clearBox.min.y | 0, ( _clearBox.max.x - _clearBox.min.x ) | 0, ( _clearBox.max.y - _clearBox.min.y ) | 0 );
  8084. }
  8085. _clearBox.makeEmpty();
  8086. }
  8087. };
  8088. this.render = function ( scene, camera ) {
  8089. if ( camera instanceof THREE.Camera === false ) {
  8090. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8091. return;
  8092. }
  8093. var e, el, element, material;
  8094. this.autoClear === true
  8095. ? this.clear()
  8096. : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8097. _this.info.render.vertices = 0;
  8098. _this.info.render.faces = 0;
  8099. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8100. _elements = _renderData.elements;
  8101. _lights = _renderData.lights;
  8102. /* DEBUG
  8103. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  8104. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8105. */
  8106. _enableLighting = _lights.length > 0;
  8107. if ( _enableLighting === true ) {
  8108. calculateLights();
  8109. }
  8110. for ( e = 0, el = _elements.length; e < el; e++ ) {
  8111. element = _elements[ e ];
  8112. material = element.material;
  8113. if ( material === undefined || material.visible === false ) continue;
  8114. _elemBox.makeEmpty();
  8115. if ( element instanceof THREE.RenderableParticle ) {
  8116. _v1 = element;
  8117. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8118. renderParticle( _v1, element, material, scene );
  8119. } else if ( element instanceof THREE.RenderableLine ) {
  8120. _v1 = element.v1; _v2 = element.v2;
  8121. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8122. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8123. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] );
  8124. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8125. renderLine( _v1, _v2, element, material, scene );
  8126. }
  8127. } else if ( element instanceof THREE.RenderableFace3 ) {
  8128. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8129. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8130. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8131. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8132. if ( material.overdraw === true ) {
  8133. expand( _v1.positionScreen, _v2.positionScreen );
  8134. expand( _v2.positionScreen, _v3.positionScreen );
  8135. expand( _v3.positionScreen, _v1.positionScreen );
  8136. }
  8137. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen ] );
  8138. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8139. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  8140. }
  8141. } else if ( element instanceof THREE.RenderableFace4 ) {
  8142. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8143. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8144. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8145. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8146. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8147. _v5.positionScreen.copy( _v2.positionScreen );
  8148. _v6.positionScreen.copy( _v4.positionScreen );
  8149. if ( material.overdraw === true ) {
  8150. expand( _v1.positionScreen, _v2.positionScreen );
  8151. expand( _v2.positionScreen, _v4.positionScreen );
  8152. expand( _v4.positionScreen, _v1.positionScreen );
  8153. expand( _v3.positionScreen, _v5.positionScreen );
  8154. expand( _v3.positionScreen, _v6.positionScreen );
  8155. }
  8156. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen, _v4.positionScreen ] );
  8157. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8158. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  8159. }
  8160. }
  8161. /* DEBUG
  8162. _context.lineWidth = 1;
  8163. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  8164. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8165. */
  8166. _clearBox.union( _elemBox );
  8167. }
  8168. /* DEBUG
  8169. _context.lineWidth = 1;
  8170. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  8171. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8172. */
  8173. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8174. //
  8175. function calculateLights() {
  8176. _ambientLight.setRGB( 0, 0, 0 );
  8177. _directionalLights.setRGB( 0, 0, 0 );
  8178. _pointLights.setRGB( 0, 0, 0 );
  8179. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8180. var light = _lights[ l ];
  8181. var lightColor = light.color;
  8182. if ( light instanceof THREE.AmbientLight ) {
  8183. _ambientLight.r += lightColor.r;
  8184. _ambientLight.g += lightColor.g;
  8185. _ambientLight.b += lightColor.b;
  8186. } else if ( light instanceof THREE.DirectionalLight ) {
  8187. // for particles
  8188. _directionalLights.r += lightColor.r;
  8189. _directionalLights.g += lightColor.g;
  8190. _directionalLights.b += lightColor.b;
  8191. } else if ( light instanceof THREE.PointLight ) {
  8192. // for particles
  8193. _pointLights.r += lightColor.r;
  8194. _pointLights.g += lightColor.g;
  8195. _pointLights.b += lightColor.b;
  8196. }
  8197. }
  8198. }
  8199. function calculateLight( position, normal, color ) {
  8200. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8201. var light = _lights[ l ];
  8202. var lightColor = light.color;
  8203. if ( light instanceof THREE.DirectionalLight ) {
  8204. var lightPosition = light.matrixWorld.getPosition().normalize();
  8205. var amount = normal.dot( lightPosition );
  8206. if ( amount <= 0 ) continue;
  8207. amount *= light.intensity;
  8208. color.r += lightColor.r * amount;
  8209. color.g += lightColor.g * amount;
  8210. color.b += lightColor.b * amount;
  8211. } else if ( light instanceof THREE.PointLight ) {
  8212. var lightPosition = light.matrixWorld.getPosition();
  8213. var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  8214. if ( amount <= 0 ) continue;
  8215. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8216. if ( amount == 0 ) continue;
  8217. amount *= light.intensity;
  8218. color.r += lightColor.r * amount;
  8219. color.g += lightColor.g * amount;
  8220. color.b += lightColor.b * amount;
  8221. }
  8222. }
  8223. }
  8224. function renderParticle( v1, element, material, scene ) {
  8225. setOpacity( material.opacity );
  8226. setBlending( material.blending );
  8227. var width, height, scaleX, scaleY,
  8228. bitmap, bitmapWidth, bitmapHeight;
  8229. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8230. if ( material.map === null ) {
  8231. scaleX = element.object.scale.x;
  8232. scaleY = element.object.scale.y;
  8233. // TODO: Be able to disable this
  8234. scaleX *= element.scale.x * _canvasWidthHalf;
  8235. scaleY *= element.scale.y * _canvasHeightHalf;
  8236. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8237. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8238. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8239. return;
  8240. }
  8241. setFillStyle( material.color.getStyle() );
  8242. _context.save();
  8243. _context.translate( v1.x, v1.y );
  8244. _context.rotate( - element.rotation );
  8245. _context.scale( scaleX, scaleY );
  8246. _context.fillRect( -1, -1, 2, 2 );
  8247. _context.restore();
  8248. } else {
  8249. bitmap = material.map.image;
  8250. bitmapWidth = bitmap.width >> 1;
  8251. bitmapHeight = bitmap.height >> 1;
  8252. scaleX = element.scale.x * _canvasWidthHalf;
  8253. scaleY = element.scale.y * _canvasHeightHalf;
  8254. width = scaleX * bitmapWidth;
  8255. height = scaleY * bitmapHeight;
  8256. // TODO: Rotations break this...
  8257. _elemBox.min.set( v1.x - width, v1.y - height );
  8258. _elemBox.max.set( v1.x + width, v1.y + height );
  8259. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8260. return;
  8261. }
  8262. _context.save();
  8263. _context.translate( v1.x, v1.y );
  8264. _context.rotate( - element.rotation );
  8265. _context.scale( scaleX, - scaleY );
  8266. _context.translate( - bitmapWidth, - bitmapHeight );
  8267. _context.drawImage( bitmap, 0, 0 );
  8268. _context.restore();
  8269. }
  8270. /* DEBUG
  8271. setStrokeStyle( 'rgb(255,255,0)' );
  8272. _context.beginPath();
  8273. _context.moveTo( v1.x - 10, v1.y );
  8274. _context.lineTo( v1.x + 10, v1.y );
  8275. _context.moveTo( v1.x, v1.y - 10 );
  8276. _context.lineTo( v1.x, v1.y + 10 );
  8277. _context.stroke();
  8278. */
  8279. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8280. width = element.scale.x * _canvasWidthHalf;
  8281. height = element.scale.y * _canvasHeightHalf;
  8282. _elemBox.min.set( v1.x - width, v1.y - height );
  8283. _elemBox.max.set( v1.x + width, v1.y + height );
  8284. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8285. return;
  8286. }
  8287. setStrokeStyle( material.color.getStyle() );
  8288. setFillStyle( material.color.getStyle() );
  8289. _context.save();
  8290. _context.translate( v1.x, v1.y );
  8291. _context.rotate( - element.rotation );
  8292. _context.scale( width, height );
  8293. material.program( _context );
  8294. _context.restore();
  8295. }
  8296. }
  8297. function renderLine( v1, v2, element, material, scene ) {
  8298. setOpacity( material.opacity );
  8299. setBlending( material.blending );
  8300. _context.beginPath();
  8301. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8302. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8303. if ( material instanceof THREE.LineBasicMaterial ) {
  8304. setLineWidth( material.linewidth );
  8305. setLineCap( material.linecap );
  8306. setLineJoin( material.linejoin );
  8307. setStrokeStyle( material.color.getStyle() );
  8308. _context.stroke();
  8309. _elemBox.expandByScalar( material.linewidth * 2 );
  8310. }
  8311. }
  8312. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  8313. _this.info.render.vertices += 3;
  8314. _this.info.render.faces ++;
  8315. setOpacity( material.opacity );
  8316. setBlending( material.blending );
  8317. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8318. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8319. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8320. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8321. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  8322. _diffuseColor.copy( material.color );
  8323. _emissiveColor.copy( material.emissive );
  8324. if ( material.vertexColors === THREE.FaceColors ) {
  8325. _diffuseColor.r *= element.color.r;
  8326. _diffuseColor.g *= element.color.g;
  8327. _diffuseColor.b *= element.color.b;
  8328. }
  8329. if ( _enableLighting === true ) {
  8330. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8331. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  8332. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  8333. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  8334. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  8335. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  8336. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  8337. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  8338. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  8339. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  8340. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  8341. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  8342. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  8343. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  8344. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  8345. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  8346. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  8347. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  8348. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  8349. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8350. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8351. } else {
  8352. _color.r = _ambientLight.r;
  8353. _color.g = _ambientLight.g;
  8354. _color.b = _ambientLight.b;
  8355. calculateLight( element.centroidWorld, element.normalWorld, _color );
  8356. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  8357. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  8358. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  8359. material.wireframe === true
  8360. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8361. : fillPath( _color );
  8362. }
  8363. } else {
  8364. material.wireframe === true
  8365. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8366. : fillPath( material.color );
  8367. }
  8368. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8369. if ( material.map !== null ) {
  8370. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8371. _uvs = element.uvs[ 0 ];
  8372. 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 );
  8373. }
  8374. } else if ( material.envMap !== null ) {
  8375. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8376. var cameraMatrix = camera.matrixWorldInverse;
  8377. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  8378. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  8379. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  8380. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  8381. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  8382. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  8383. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  8384. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  8385. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  8386. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8387. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8388. }*/
  8389. } else {
  8390. _color.copy( material.color );
  8391. if ( material.vertexColors === THREE.FaceColors ) {
  8392. _color.r *= element.color.r;
  8393. _color.g *= element.color.g;
  8394. _color.b *= element.color.b;
  8395. }
  8396. material.wireframe === true
  8397. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8398. : fillPath( _color );
  8399. }
  8400. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8401. _near = camera.near;
  8402. _far = camera.far;
  8403. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8404. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  8405. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8406. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  8407. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  8408. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  8409. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8410. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8411. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8412. _color.r = normalToComponent( element.normalWorld.x );
  8413. _color.g = normalToComponent( element.normalWorld.y );
  8414. _color.b = normalToComponent( element.normalWorld.z );
  8415. material.wireframe === true
  8416. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8417. : fillPath( _color );
  8418. }
  8419. }
  8420. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  8421. _this.info.render.vertices += 4;
  8422. _this.info.render.faces ++;
  8423. setOpacity( material.opacity );
  8424. setBlending( material.blending );
  8425. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8426. // Let renderFace3() handle this
  8427. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  8428. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  8429. return;
  8430. }
  8431. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8432. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8433. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8434. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8435. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8436. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8437. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8438. _diffuseColor.copy( material.color );
  8439. _emissiveColor.copy( material.emissive );
  8440. if ( material.vertexColors === THREE.FaceColors ) {
  8441. _diffuseColor.r *= element.color.r;
  8442. _diffuseColor.g *= element.color.g;
  8443. _diffuseColor.b *= element.color.b;
  8444. }
  8445. if ( _enableLighting === true ) {
  8446. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8447. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  8448. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  8449. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  8450. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  8451. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  8452. calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  8453. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  8454. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  8455. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  8456. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  8457. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  8458. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  8459. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  8460. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  8461. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  8462. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  8463. _color4.r = _color4.r * _diffuseColor.r + _emissiveColor.r;
  8464. _color4.g = _color4.g * _diffuseColor.g + _emissiveColor.g;
  8465. _color4.b = _color4.b * _diffuseColor.b + _emissiveColor.b;
  8466. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8467. // TODO: UVs are incorrect, v4->v3?
  8468. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8469. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8470. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8471. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8472. } else {
  8473. _color.r = _ambientLight.r;
  8474. _color.g = _ambientLight.g;
  8475. _color.b = _ambientLight.b;
  8476. calculateLight( element.centroidWorld, element.normalWorld, _color );
  8477. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  8478. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  8479. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  8480. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8481. material.wireframe === true
  8482. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8483. : fillPath( _color );
  8484. }
  8485. } else {
  8486. _color.r = _diffuseColor.r + _emissiveColor.r;
  8487. _color.g = _diffuseColor.g + _emissiveColor.g;
  8488. _color.b = _diffuseColor.b + _emissiveColor.b;
  8489. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8490. material.wireframe === true
  8491. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8492. : fillPath( _color );
  8493. }
  8494. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8495. _color.copy( material.color );
  8496. if ( material.vertexColors === THREE.FaceColors ) {
  8497. _color.r *= element.color.r;
  8498. _color.g *= element.color.g;
  8499. _color.b *= element.color.b;
  8500. }
  8501. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8502. material.wireframe === true
  8503. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8504. : fillPath( _color );
  8505. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8506. _color.r = normalToComponent( element.normalWorld.x );
  8507. _color.g = normalToComponent( element.normalWorld.y );
  8508. _color.b = normalToComponent( element.normalWorld.z );
  8509. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8510. material.wireframe === true
  8511. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8512. : fillPath( _color );
  8513. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8514. _near = camera.near;
  8515. _far = camera.far;
  8516. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8517. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  8518. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  8519. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8520. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8521. // TODO: UVs are incorrect, v4->v3?
  8522. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8523. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8524. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8525. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8526. }
  8527. }
  8528. //
  8529. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8530. _context.beginPath();
  8531. _context.moveTo( x0, y0 );
  8532. _context.lineTo( x1, y1 );
  8533. _context.lineTo( x2, y2 );
  8534. _context.closePath();
  8535. }
  8536. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8537. _context.beginPath();
  8538. _context.moveTo( x0, y0 );
  8539. _context.lineTo( x1, y1 );
  8540. _context.lineTo( x2, y2 );
  8541. _context.lineTo( x3, y3 );
  8542. _context.closePath();
  8543. }
  8544. function strokePath( color, linewidth, linecap, linejoin ) {
  8545. setLineWidth( linewidth );
  8546. setLineCap( linecap );
  8547. setLineJoin( linejoin );
  8548. setStrokeStyle( color.getStyle() );
  8549. _context.stroke();
  8550. _elemBox.expandByScalar( linewidth * 2 );
  8551. }
  8552. function fillPath( color ) {
  8553. setFillStyle( color.getStyle() );
  8554. _context.fill();
  8555. }
  8556. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8557. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8558. if ( texture.needsUpdate === true ) {
  8559. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8560. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8561. _patterns[ texture.id ] = _context.createPattern(
  8562. texture.image, repeatX === true && repeatY === true
  8563. ? 'repeat'
  8564. : repeatX === true && repeatY === false
  8565. ? 'repeat-x'
  8566. : repeatX === false && repeatY === true
  8567. ? 'repeat-y'
  8568. : 'no-repeat'
  8569. );
  8570. texture.needsUpdate = false;
  8571. }
  8572. _patterns[ texture.id ] === undefined
  8573. ? setFillStyle( 'rgba(0,0,0,1)' )
  8574. : setFillStyle( _patterns[ texture.id ] );
  8575. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8576. var a, b, c, d, e, f, det, idet,
  8577. offsetX = texture.offset.x / texture.repeat.x,
  8578. offsetY = texture.offset.y / texture.repeat.y,
  8579. width = texture.image.width * texture.repeat.x,
  8580. height = texture.image.height * texture.repeat.y;
  8581. u0 = ( u0 + offsetX ) * width;
  8582. v0 = ( 1.0 - v0 + offsetY ) * height;
  8583. u1 = ( u1 + offsetX ) * width;
  8584. v1 = ( 1.0 - v1 + offsetY ) * height;
  8585. u2 = ( u2 + offsetX ) * width;
  8586. v2 = ( 1.0 - v2 + offsetY ) * height;
  8587. x1 -= x0; y1 -= y0;
  8588. x2 -= x0; y2 -= y0;
  8589. u1 -= u0; v1 -= v0;
  8590. u2 -= u0; v2 -= v0;
  8591. det = u1 * v2 - u2 * v1;
  8592. if ( det === 0 ) {
  8593. if ( _imagedatas[ texture.id ] === undefined ) {
  8594. var canvas = document.createElement( 'canvas' )
  8595. canvas.width = texture.image.width;
  8596. canvas.height = texture.image.height;
  8597. var context = canvas.getContext( '2d' );
  8598. context.drawImage( texture.image, 0, 0 );
  8599. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8600. }
  8601. var data = _imagedatas[ texture.id ];
  8602. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8603. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8604. fillPath( _color );
  8605. return;
  8606. }
  8607. idet = 1 / det;
  8608. a = ( v2 * x1 - v1 * x2 ) * idet;
  8609. b = ( v2 * y1 - v1 * y2 ) * idet;
  8610. c = ( u1 * x2 - u2 * x1 ) * idet;
  8611. d = ( u1 * y2 - u2 * y1 ) * idet;
  8612. e = x0 - a * u0 - c * v0;
  8613. f = y0 - b * u0 - d * v0;
  8614. _context.save();
  8615. _context.transform( a, b, c, d, e, f );
  8616. _context.fill();
  8617. _context.restore();
  8618. }
  8619. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8620. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8621. var a, b, c, d, e, f, det, idet,
  8622. width = image.width - 1,
  8623. height = image.height - 1;
  8624. u0 *= width; v0 *= height;
  8625. u1 *= width; v1 *= height;
  8626. u2 *= width; v2 *= height;
  8627. x1 -= x0; y1 -= y0;
  8628. x2 -= x0; y2 -= y0;
  8629. u1 -= u0; v1 -= v0;
  8630. u2 -= u0; v2 -= v0;
  8631. det = u1 * v2 - u2 * v1;
  8632. idet = 1 / det;
  8633. a = ( v2 * x1 - v1 * x2 ) * idet;
  8634. b = ( v2 * y1 - v1 * y2 ) * idet;
  8635. c = ( u1 * x2 - u2 * x1 ) * idet;
  8636. d = ( u1 * y2 - u2 * y1 ) * idet;
  8637. e = x0 - a * u0 - c * v0;
  8638. f = y0 - b * u0 - d * v0;
  8639. _context.save();
  8640. _context.transform( a, b, c, d, e, f );
  8641. _context.clip();
  8642. _context.drawImage( image, 0, 0 );
  8643. _context.restore();
  8644. }
  8645. function getGradientTexture( color1, color2, color3, color4 ) {
  8646. // http://mrdoob.com/blog/post/710
  8647. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  8648. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  8649. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  8650. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  8651. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  8652. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  8653. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  8654. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  8655. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  8656. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  8657. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  8658. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  8659. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  8660. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  8661. return _gradientMap;
  8662. }
  8663. function smoothstep( value, min, max ) {
  8664. var x = ( value - min ) / ( max - min );
  8665. return x * x * ( 3 - 2 * x );
  8666. }
  8667. function normalToComponent( normal ) {
  8668. var component = ( normal + 1 ) * 0.5;
  8669. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  8670. }
  8671. // Hide anti-alias gaps
  8672. function expand( v1, v2 ) {
  8673. var x = v2.x - v1.x, y = v2.y - v1.y,
  8674. det = x * x + y * y, idet;
  8675. if ( det === 0 ) return;
  8676. idet = 1 / Math.sqrt( det );
  8677. x *= idet; y *= idet;
  8678. v2.x += x; v2.y += y;
  8679. v1.x -= x; v1.y -= y;
  8680. }
  8681. };
  8682. // Context cached methods.
  8683. function setOpacity( value ) {
  8684. if ( _contextGlobalAlpha !== value ) {
  8685. _context.globalAlpha = value;
  8686. _contextGlobalAlpha = value;
  8687. }
  8688. }
  8689. function setBlending( value ) {
  8690. if ( _contextGlobalCompositeOperation !== value ) {
  8691. if ( value === THREE.NormalBlending ) {
  8692. _context.globalCompositeOperation = 'source-over';
  8693. } else if ( value === THREE.AdditiveBlending ) {
  8694. _context.globalCompositeOperation = 'lighter';
  8695. } else if ( value === THREE.SubtractiveBlending ) {
  8696. _context.globalCompositeOperation = 'darker';
  8697. }
  8698. _contextGlobalCompositeOperation = value;
  8699. }
  8700. }
  8701. function setLineWidth( value ) {
  8702. if ( _contextLineWidth !== value ) {
  8703. _context.lineWidth = value;
  8704. _contextLineWidth = value;
  8705. }
  8706. }
  8707. function setLineCap( value ) {
  8708. // "butt", "round", "square"
  8709. if ( _contextLineCap !== value ) {
  8710. _context.lineCap = value;
  8711. _contextLineCap = value;
  8712. }
  8713. }
  8714. function setLineJoin( value ) {
  8715. // "round", "bevel", "miter"
  8716. if ( _contextLineJoin !== value ) {
  8717. _context.lineJoin = value;
  8718. _contextLineJoin = value;
  8719. }
  8720. }
  8721. function setStrokeStyle( value ) {
  8722. if ( _contextStrokeStyle !== value ) {
  8723. _context.strokeStyle = value;
  8724. _contextStrokeStyle = value;
  8725. }
  8726. }
  8727. function setFillStyle( value ) {
  8728. if ( _contextFillStyle !== value ) {
  8729. _context.fillStyle = value;
  8730. _contextFillStyle = value;
  8731. }
  8732. }
  8733. };
  8734. /**
  8735. * @author alteredq / http://alteredqualia.com/
  8736. * @author mrdoob / http://mrdoob.com/
  8737. * @author mikael emtinger / http://gomo.se/
  8738. */
  8739. THREE.ShaderChunk = {
  8740. // FOG
  8741. fog_pars_fragment: [
  8742. "#ifdef USE_FOG",
  8743. "uniform vec3 fogColor;",
  8744. "#ifdef FOG_EXP2",
  8745. "uniform float fogDensity;",
  8746. "#else",
  8747. "uniform float fogNear;",
  8748. "uniform float fogFar;",
  8749. "#endif",
  8750. "#endif"
  8751. ].join("\n"),
  8752. fog_fragment: [
  8753. "#ifdef USE_FOG",
  8754. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8755. "#ifdef FOG_EXP2",
  8756. "const float LOG2 = 1.442695;",
  8757. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8758. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8759. "#else",
  8760. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8761. "#endif",
  8762. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8763. "#endif"
  8764. ].join("\n"),
  8765. // ENVIRONMENT MAP
  8766. envmap_pars_fragment: [
  8767. "#ifdef USE_ENVMAP",
  8768. "uniform float reflectivity;",
  8769. "uniform samplerCube envMap;",
  8770. "uniform float flipEnvMap;",
  8771. "uniform int combine;",
  8772. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8773. "uniform bool useRefract;",
  8774. "uniform float refractionRatio;",
  8775. "#else",
  8776. "varying vec3 vReflect;",
  8777. "#endif",
  8778. "#endif"
  8779. ].join("\n"),
  8780. envmap_fragment: [
  8781. "#ifdef USE_ENVMAP",
  8782. "vec3 reflectVec;",
  8783. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8784. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8785. "if ( useRefract ) {",
  8786. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8787. "} else { ",
  8788. "reflectVec = reflect( cameraToVertex, normal );",
  8789. "}",
  8790. "#else",
  8791. "reflectVec = vReflect;",
  8792. "#endif",
  8793. "#ifdef DOUBLE_SIDED",
  8794. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8795. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8796. "#else",
  8797. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8798. "#endif",
  8799. "#ifdef GAMMA_INPUT",
  8800. "cubeColor.xyz *= cubeColor.xyz;",
  8801. "#endif",
  8802. "if ( combine == 1 ) {",
  8803. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8804. "} else if ( combine == 2 ) {",
  8805. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8806. "} else {",
  8807. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8808. "}",
  8809. "#endif"
  8810. ].join("\n"),
  8811. envmap_pars_vertex: [
  8812. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8813. "varying vec3 vReflect;",
  8814. "uniform float refractionRatio;",
  8815. "uniform bool useRefract;",
  8816. "#endif"
  8817. ].join("\n"),
  8818. worldpos_vertex : [
  8819. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8820. "#ifdef USE_SKINNING",
  8821. "vec4 worldPosition = modelMatrix * skinned;",
  8822. "#endif",
  8823. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8824. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8825. "#endif",
  8826. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8827. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8828. "#endif",
  8829. "#endif"
  8830. ].join("\n"),
  8831. envmap_vertex : [
  8832. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8833. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8834. "worldNormal = normalize( worldNormal );",
  8835. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8836. "if ( useRefract ) {",
  8837. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8838. "} else {",
  8839. "vReflect = reflect( cameraToVertex, worldNormal );",
  8840. "}",
  8841. "#endif"
  8842. ].join("\n"),
  8843. // COLOR MAP (particles)
  8844. map_particle_pars_fragment: [
  8845. "#ifdef USE_MAP",
  8846. "uniform sampler2D map;",
  8847. "#endif"
  8848. ].join("\n"),
  8849. map_particle_fragment: [
  8850. "#ifdef USE_MAP",
  8851. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8852. "#endif"
  8853. ].join("\n"),
  8854. // COLOR MAP (triangles)
  8855. map_pars_vertex: [
  8856. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8857. "varying vec2 vUv;",
  8858. "uniform vec4 offsetRepeat;",
  8859. "#endif"
  8860. ].join("\n"),
  8861. map_pars_fragment: [
  8862. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8863. "varying vec2 vUv;",
  8864. "#endif",
  8865. "#ifdef USE_MAP",
  8866. "uniform sampler2D map;",
  8867. "#endif"
  8868. ].join("\n"),
  8869. map_vertex: [
  8870. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8871. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8872. "#endif"
  8873. ].join("\n"),
  8874. map_fragment: [
  8875. "#ifdef USE_MAP",
  8876. "vec4 texelColor = texture2D( map, vUv );",
  8877. "#ifdef GAMMA_INPUT",
  8878. "texelColor.xyz *= texelColor.xyz;",
  8879. "#endif",
  8880. "gl_FragColor = gl_FragColor * texelColor;",
  8881. "#endif"
  8882. ].join("\n"),
  8883. // LIGHT MAP
  8884. lightmap_pars_fragment: [
  8885. "#ifdef USE_LIGHTMAP",
  8886. "varying vec2 vUv2;",
  8887. "uniform sampler2D lightMap;",
  8888. "#endif"
  8889. ].join("\n"),
  8890. lightmap_pars_vertex: [
  8891. "#ifdef USE_LIGHTMAP",
  8892. "varying vec2 vUv2;",
  8893. "#endif"
  8894. ].join("\n"),
  8895. lightmap_fragment: [
  8896. "#ifdef USE_LIGHTMAP",
  8897. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8898. "#endif"
  8899. ].join("\n"),
  8900. lightmap_vertex: [
  8901. "#ifdef USE_LIGHTMAP",
  8902. "vUv2 = uv2;",
  8903. "#endif"
  8904. ].join("\n"),
  8905. // BUMP MAP
  8906. bumpmap_pars_fragment: [
  8907. "#ifdef USE_BUMPMAP",
  8908. "uniform sampler2D bumpMap;",
  8909. "uniform float bumpScale;",
  8910. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8911. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8912. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8913. "vec2 dHdxy_fwd() {",
  8914. "vec2 dSTdx = dFdx( vUv );",
  8915. "vec2 dSTdy = dFdy( vUv );",
  8916. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8917. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8918. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8919. "return vec2( dBx, dBy );",
  8920. "}",
  8921. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8922. "vec3 vSigmaX = dFdx( surf_pos );",
  8923. "vec3 vSigmaY = dFdy( surf_pos );",
  8924. "vec3 vN = surf_norm;", // normalized
  8925. "vec3 R1 = cross( vSigmaY, vN );",
  8926. "vec3 R2 = cross( vN, vSigmaX );",
  8927. "float fDet = dot( vSigmaX, R1 );",
  8928. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8929. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8930. "}",
  8931. "#endif"
  8932. ].join("\n"),
  8933. // NORMAL MAP
  8934. normalmap_pars_fragment: [
  8935. "#ifdef USE_NORMALMAP",
  8936. "uniform sampler2D normalMap;",
  8937. "uniform vec2 normalScale;",
  8938. // Per-Pixel Tangent Space Normal Mapping
  8939. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8940. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8941. "vec3 q0 = dFdx( eye_pos.xyz );",
  8942. "vec3 q1 = dFdy( eye_pos.xyz );",
  8943. "vec2 st0 = dFdx( vUv.st );",
  8944. "vec2 st1 = dFdy( vUv.st );",
  8945. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8946. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8947. "vec3 N = normalize( surf_norm );",
  8948. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8949. "mapN.xy = normalScale * mapN.xy;",
  8950. "mat3 tsn = mat3( S, T, N );",
  8951. "return normalize( tsn * mapN );",
  8952. "}",
  8953. "#endif"
  8954. ].join("\n"),
  8955. // SPECULAR MAP
  8956. specularmap_pars_fragment: [
  8957. "#ifdef USE_SPECULARMAP",
  8958. "uniform sampler2D specularMap;",
  8959. "#endif"
  8960. ].join("\n"),
  8961. specularmap_fragment: [
  8962. "float specularStrength;",
  8963. "#ifdef USE_SPECULARMAP",
  8964. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8965. "specularStrength = texelSpecular.r;",
  8966. "#else",
  8967. "specularStrength = 1.0;",
  8968. "#endif"
  8969. ].join("\n"),
  8970. // LIGHTS LAMBERT
  8971. lights_lambert_pars_vertex: [
  8972. "uniform vec3 ambient;",
  8973. "uniform vec3 diffuse;",
  8974. "uniform vec3 emissive;",
  8975. "uniform vec3 ambientLightColor;",
  8976. "#if MAX_DIR_LIGHTS > 0",
  8977. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8978. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8979. "#endif",
  8980. "#if MAX_HEMI_LIGHTS > 0",
  8981. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8982. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8983. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8984. "#endif",
  8985. "#if MAX_POINT_LIGHTS > 0",
  8986. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8987. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8988. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8989. "#endif",
  8990. "#if MAX_SPOT_LIGHTS > 0",
  8991. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8992. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8993. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8994. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8995. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8996. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8997. "#endif",
  8998. "#ifdef WRAP_AROUND",
  8999. "uniform vec3 wrapRGB;",
  9000. "#endif"
  9001. ].join("\n"),
  9002. lights_lambert_vertex: [
  9003. "vLightFront = vec3( 0.0 );",
  9004. "#ifdef DOUBLE_SIDED",
  9005. "vLightBack = vec3( 0.0 );",
  9006. "#endif",
  9007. "transformedNormal = normalize( transformedNormal );",
  9008. "#if MAX_DIR_LIGHTS > 0",
  9009. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9010. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9011. "vec3 dirVector = normalize( lDirection.xyz );",
  9012. "float dotProduct = dot( transformedNormal, dirVector );",
  9013. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9014. "#ifdef DOUBLE_SIDED",
  9015. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9016. "#ifdef WRAP_AROUND",
  9017. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9018. "#endif",
  9019. "#endif",
  9020. "#ifdef WRAP_AROUND",
  9021. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9022. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9023. "#ifdef DOUBLE_SIDED",
  9024. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9025. "#endif",
  9026. "#endif",
  9027. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9028. "#ifdef DOUBLE_SIDED",
  9029. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9030. "#endif",
  9031. "}",
  9032. "#endif",
  9033. "#if MAX_POINT_LIGHTS > 0",
  9034. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9035. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9036. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9037. "float lDistance = 1.0;",
  9038. "if ( pointLightDistance[ i ] > 0.0 )",
  9039. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9040. "lVector = normalize( lVector );",
  9041. "float dotProduct = dot( transformedNormal, lVector );",
  9042. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9043. "#ifdef DOUBLE_SIDED",
  9044. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9045. "#ifdef WRAP_AROUND",
  9046. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9047. "#endif",
  9048. "#endif",
  9049. "#ifdef WRAP_AROUND",
  9050. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9051. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9052. "#ifdef DOUBLE_SIDED",
  9053. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9054. "#endif",
  9055. "#endif",
  9056. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9057. "#ifdef DOUBLE_SIDED",
  9058. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9059. "#endif",
  9060. "}",
  9061. "#endif",
  9062. "#if MAX_SPOT_LIGHTS > 0",
  9063. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9064. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9065. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9066. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9067. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9068. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9069. "float lDistance = 1.0;",
  9070. "if ( spotLightDistance[ i ] > 0.0 )",
  9071. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9072. "lVector = normalize( lVector );",
  9073. "float dotProduct = dot( transformedNormal, lVector );",
  9074. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9075. "#ifdef DOUBLE_SIDED",
  9076. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9077. "#ifdef WRAP_AROUND",
  9078. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9079. "#endif",
  9080. "#endif",
  9081. "#ifdef WRAP_AROUND",
  9082. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9083. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9084. "#ifdef DOUBLE_SIDED",
  9085. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9086. "#endif",
  9087. "#endif",
  9088. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9089. "#ifdef DOUBLE_SIDED",
  9090. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9091. "#endif",
  9092. "}",
  9093. "}",
  9094. "#endif",
  9095. "#if MAX_HEMI_LIGHTS > 0",
  9096. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9097. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9098. "vec3 lVector = normalize( lDirection.xyz );",
  9099. "float dotProduct = dot( transformedNormal, lVector );",
  9100. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9101. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9102. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9103. "#ifdef DOUBLE_SIDED",
  9104. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9105. "#endif",
  9106. "}",
  9107. "#endif",
  9108. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9109. "#ifdef DOUBLE_SIDED",
  9110. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9111. "#endif"
  9112. ].join("\n"),
  9113. // LIGHTS PHONG
  9114. lights_phong_pars_vertex: [
  9115. "#ifndef PHONG_PER_PIXEL",
  9116. "#if MAX_POINT_LIGHTS > 0",
  9117. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9118. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9119. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9120. "#endif",
  9121. "#if MAX_SPOT_LIGHTS > 0",
  9122. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9123. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9124. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9125. "#endif",
  9126. "#endif",
  9127. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9128. "varying vec3 vWorldPosition;",
  9129. "#endif"
  9130. ].join("\n"),
  9131. lights_phong_vertex: [
  9132. "#ifndef PHONG_PER_PIXEL",
  9133. "#if MAX_POINT_LIGHTS > 0",
  9134. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9135. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9136. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9137. "float lDistance = 1.0;",
  9138. "if ( pointLightDistance[ i ] > 0.0 )",
  9139. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9140. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9141. "}",
  9142. "#endif",
  9143. "#if MAX_SPOT_LIGHTS > 0",
  9144. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9145. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9146. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9147. "float lDistance = 1.0;",
  9148. "if ( spotLightDistance[ i ] > 0.0 )",
  9149. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9150. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9151. "}",
  9152. "#endif",
  9153. "#endif",
  9154. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9155. "vWorldPosition = worldPosition.xyz;",
  9156. "#endif"
  9157. ].join("\n"),
  9158. lights_phong_pars_fragment: [
  9159. "uniform vec3 ambientLightColor;",
  9160. "#if MAX_DIR_LIGHTS > 0",
  9161. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9162. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9163. "#endif",
  9164. "#if MAX_HEMI_LIGHTS > 0",
  9165. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9166. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9167. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9168. "#endif",
  9169. "#if MAX_POINT_LIGHTS > 0",
  9170. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9171. "#ifdef PHONG_PER_PIXEL",
  9172. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9173. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9174. "#else",
  9175. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9176. "#endif",
  9177. "#endif",
  9178. "#if MAX_SPOT_LIGHTS > 0",
  9179. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9180. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9181. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9182. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9183. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9184. "#ifdef PHONG_PER_PIXEL",
  9185. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9186. "#else",
  9187. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9188. "#endif",
  9189. "#endif",
  9190. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9191. "varying vec3 vWorldPosition;",
  9192. "#endif",
  9193. "#ifdef WRAP_AROUND",
  9194. "uniform vec3 wrapRGB;",
  9195. "#endif",
  9196. "varying vec3 vViewPosition;",
  9197. "varying vec3 vNormal;"
  9198. ].join("\n"),
  9199. lights_phong_fragment: [
  9200. "vec3 normal = normalize( vNormal );",
  9201. "vec3 viewPosition = normalize( vViewPosition );",
  9202. "#ifdef DOUBLE_SIDED",
  9203. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9204. "#endif",
  9205. "#ifdef USE_NORMALMAP",
  9206. "normal = perturbNormal2Arb( -viewPosition, normal );",
  9207. "#elif defined( USE_BUMPMAP )",
  9208. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9209. "#endif",
  9210. "#if MAX_POINT_LIGHTS > 0",
  9211. "vec3 pointDiffuse = vec3( 0.0 );",
  9212. "vec3 pointSpecular = vec3( 0.0 );",
  9213. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9214. "#ifdef PHONG_PER_PIXEL",
  9215. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9216. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9217. "float lDistance = 1.0;",
  9218. "if ( pointLightDistance[ i ] > 0.0 )",
  9219. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9220. "lVector = normalize( lVector );",
  9221. "#else",
  9222. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9223. "float lDistance = vPointLight[ i ].w;",
  9224. "#endif",
  9225. // diffuse
  9226. "float dotProduct = dot( normal, lVector );",
  9227. "#ifdef WRAP_AROUND",
  9228. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9229. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9230. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9231. "#else",
  9232. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9233. "#endif",
  9234. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9235. // specular
  9236. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9237. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9238. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9239. "#ifdef PHYSICALLY_BASED_SHADING",
  9240. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9241. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9242. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9243. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9244. "#else",
  9245. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9246. "#endif",
  9247. "}",
  9248. "#endif",
  9249. "#if MAX_SPOT_LIGHTS > 0",
  9250. "vec3 spotDiffuse = vec3( 0.0 );",
  9251. "vec3 spotSpecular = vec3( 0.0 );",
  9252. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9253. "#ifdef PHONG_PER_PIXEL",
  9254. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9255. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9256. "float lDistance = 1.0;",
  9257. "if ( spotLightDistance[ i ] > 0.0 )",
  9258. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9259. "lVector = normalize( lVector );",
  9260. "#else",
  9261. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9262. "float lDistance = vSpotLight[ i ].w;",
  9263. "#endif",
  9264. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9265. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9266. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9267. // diffuse
  9268. "float dotProduct = dot( normal, lVector );",
  9269. "#ifdef WRAP_AROUND",
  9270. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9271. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9272. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9273. "#else",
  9274. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9275. "#endif",
  9276. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9277. // specular
  9278. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9279. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9280. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9281. "#ifdef PHYSICALLY_BASED_SHADING",
  9282. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9283. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9284. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9285. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9286. "#else",
  9287. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9288. "#endif",
  9289. "}",
  9290. "}",
  9291. "#endif",
  9292. "#if MAX_DIR_LIGHTS > 0",
  9293. "vec3 dirDiffuse = vec3( 0.0 );",
  9294. "vec3 dirSpecular = vec3( 0.0 );" ,
  9295. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9296. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9297. "vec3 dirVector = normalize( lDirection.xyz );",
  9298. // diffuse
  9299. "float dotProduct = dot( normal, dirVector );",
  9300. "#ifdef WRAP_AROUND",
  9301. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9302. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9303. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9304. "#else",
  9305. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9306. "#endif",
  9307. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9308. // specular
  9309. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9310. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9311. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9312. "#ifdef PHYSICALLY_BASED_SHADING",
  9313. /*
  9314. // fresnel term from skin shader
  9315. "const float F0 = 0.128;",
  9316. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9317. "float exponential = pow( base, 5.0 );",
  9318. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9319. */
  9320. /*
  9321. // fresnel term from fresnel shader
  9322. "const float mFresnelBias = 0.08;",
  9323. "const float mFresnelScale = 0.3;",
  9324. "const float mFresnelPower = 5.0;",
  9325. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9326. */
  9327. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9328. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9329. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9330. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9331. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9332. "#else",
  9333. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9334. "#endif",
  9335. "}",
  9336. "#endif",
  9337. "#if MAX_HEMI_LIGHTS > 0",
  9338. "vec3 hemiDiffuse = vec3( 0.0 );",
  9339. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9340. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9341. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9342. "vec3 lVector = normalize( lDirection.xyz );",
  9343. // diffuse
  9344. "float dotProduct = dot( normal, lVector );",
  9345. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9346. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9347. "hemiDiffuse += diffuse * hemiColor;",
  9348. // specular (sky light)
  9349. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9350. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9351. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9352. // specular (ground light)
  9353. "vec3 lVectorGround = -lVector;",
  9354. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9355. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9356. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9357. "#ifdef PHYSICALLY_BASED_SHADING",
  9358. "float dotProductGround = dot( normal, lVectorGround );",
  9359. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9360. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9361. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9362. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9363. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9364. "#else",
  9365. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9366. "#endif",
  9367. "}",
  9368. "#endif",
  9369. "vec3 totalDiffuse = vec3( 0.0 );",
  9370. "vec3 totalSpecular = vec3( 0.0 );",
  9371. "#if MAX_DIR_LIGHTS > 0",
  9372. "totalDiffuse += dirDiffuse;",
  9373. "totalSpecular += dirSpecular;",
  9374. "#endif",
  9375. "#if MAX_HEMI_LIGHTS > 0",
  9376. "totalDiffuse += hemiDiffuse;",
  9377. "totalSpecular += hemiSpecular;",
  9378. "#endif",
  9379. "#if MAX_POINT_LIGHTS > 0",
  9380. "totalDiffuse += pointDiffuse;",
  9381. "totalSpecular += pointSpecular;",
  9382. "#endif",
  9383. "#if MAX_SPOT_LIGHTS > 0",
  9384. "totalDiffuse += spotDiffuse;",
  9385. "totalSpecular += spotSpecular;",
  9386. "#endif",
  9387. "#ifdef METAL",
  9388. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9389. "#else",
  9390. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9391. "#endif"
  9392. ].join("\n"),
  9393. // VERTEX COLORS
  9394. color_pars_fragment: [
  9395. "#ifdef USE_COLOR",
  9396. "varying vec3 vColor;",
  9397. "#endif"
  9398. ].join("\n"),
  9399. color_fragment: [
  9400. "#ifdef USE_COLOR",
  9401. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9402. "#endif"
  9403. ].join("\n"),
  9404. color_pars_vertex: [
  9405. "#ifdef USE_COLOR",
  9406. "varying vec3 vColor;",
  9407. "#endif"
  9408. ].join("\n"),
  9409. color_vertex: [
  9410. "#ifdef USE_COLOR",
  9411. "#ifdef GAMMA_INPUT",
  9412. "vColor = color * color;",
  9413. "#else",
  9414. "vColor = color;",
  9415. "#endif",
  9416. "#endif"
  9417. ].join("\n"),
  9418. // SKINNING
  9419. skinning_pars_vertex: [
  9420. "#ifdef USE_SKINNING",
  9421. "#ifdef BONE_TEXTURE",
  9422. "uniform sampler2D boneTexture;",
  9423. "mat4 getBoneMatrix( const in float i ) {",
  9424. "float j = i * 4.0;",
  9425. "float x = mod( j, N_BONE_PIXEL_X );",
  9426. "float y = floor( j / N_BONE_PIXEL_X );",
  9427. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9428. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9429. "y = dy * ( y + 0.5 );",
  9430. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9431. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9432. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9433. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9434. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9435. "return bone;",
  9436. "}",
  9437. "#else",
  9438. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9439. "mat4 getBoneMatrix( const in float i ) {",
  9440. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9441. "return bone;",
  9442. "}",
  9443. "#endif",
  9444. "#endif"
  9445. ].join("\n"),
  9446. skinbase_vertex: [
  9447. "#ifdef USE_SKINNING",
  9448. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9449. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9450. "#endif"
  9451. ].join("\n"),
  9452. skinning_vertex: [
  9453. "#ifdef USE_SKINNING",
  9454. "#ifdef USE_MORPHTARGETS",
  9455. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9456. "#else",
  9457. "vec4 skinVertex = vec4( position, 1.0 );",
  9458. "#endif",
  9459. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9460. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9461. "#endif"
  9462. ].join("\n"),
  9463. // MORPHING
  9464. morphtarget_pars_vertex: [
  9465. "#ifdef USE_MORPHTARGETS",
  9466. "#ifndef USE_MORPHNORMALS",
  9467. "uniform float morphTargetInfluences[ 8 ];",
  9468. "#else",
  9469. "uniform float morphTargetInfluences[ 4 ];",
  9470. "#endif",
  9471. "#endif"
  9472. ].join("\n"),
  9473. morphtarget_vertex: [
  9474. "#ifdef USE_MORPHTARGETS",
  9475. "vec3 morphed = vec3( 0.0 );",
  9476. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9477. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9478. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9479. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9480. "#ifndef USE_MORPHNORMALS",
  9481. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9482. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9483. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9484. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9485. "#endif",
  9486. "morphed += position;",
  9487. "#endif"
  9488. ].join("\n"),
  9489. default_vertex : [
  9490. "vec4 mvPosition;",
  9491. "#ifdef USE_SKINNING",
  9492. "mvPosition = modelViewMatrix * skinned;",
  9493. "#endif",
  9494. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9495. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9496. "#endif",
  9497. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9498. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9499. "#endif",
  9500. "gl_Position = projectionMatrix * mvPosition;"
  9501. ].join("\n"),
  9502. morphnormal_vertex: [
  9503. "#ifdef USE_MORPHNORMALS",
  9504. "vec3 morphedNormal = vec3( 0.0 );",
  9505. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9506. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9507. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9508. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9509. "morphedNormal += normal;",
  9510. "#endif"
  9511. ].join("\n"),
  9512. skinnormal_vertex: [
  9513. "#ifdef USE_SKINNING",
  9514. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9515. "skinMatrix += skinWeight.y * boneMatY;",
  9516. "#ifdef USE_MORPHNORMALS",
  9517. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9518. "#else",
  9519. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9520. "#endif",
  9521. "#endif"
  9522. ].join("\n"),
  9523. defaultnormal_vertex: [
  9524. "vec3 objectNormal;",
  9525. "#ifdef USE_SKINNING",
  9526. "objectNormal = skinnedNormal.xyz;",
  9527. "#endif",
  9528. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9529. "objectNormal = morphedNormal;",
  9530. "#endif",
  9531. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9532. "objectNormal = normal;",
  9533. "#endif",
  9534. "#ifdef FLIP_SIDED",
  9535. "objectNormal = -objectNormal;",
  9536. "#endif",
  9537. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9538. ].join("\n"),
  9539. // SHADOW MAP
  9540. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9541. // http://spidergl.org/example.php?id=6
  9542. // http://fabiensanglard.net/shadowmapping
  9543. shadowmap_pars_fragment: [
  9544. "#ifdef USE_SHADOWMAP",
  9545. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9546. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9547. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9548. "uniform float shadowBias[ MAX_SHADOWS ];",
  9549. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9550. "float unpackDepth( const in vec4 rgba_depth ) {",
  9551. "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 );",
  9552. "float depth = dot( rgba_depth, bit_shift );",
  9553. "return depth;",
  9554. "}",
  9555. "#endif"
  9556. ].join("\n"),
  9557. shadowmap_fragment: [
  9558. "#ifdef USE_SHADOWMAP",
  9559. "#ifdef SHADOWMAP_DEBUG",
  9560. "vec3 frustumColors[3];",
  9561. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9562. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9563. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9564. "#endif",
  9565. "#ifdef SHADOWMAP_CASCADE",
  9566. "int inFrustumCount = 0;",
  9567. "#endif",
  9568. "float fDepth;",
  9569. "vec3 shadowColor = vec3( 1.0 );",
  9570. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9571. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9572. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9573. // "if ( all( something, something ) )" using this instead
  9574. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9575. "bool inFrustum = all( inFrustumVec );",
  9576. // don't shadow pixels outside of light frustum
  9577. // use just first frustum (for cascades)
  9578. // don't shadow pixels behind far plane of light frustum
  9579. "#ifdef SHADOWMAP_CASCADE",
  9580. "inFrustumCount += int( inFrustum );",
  9581. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9582. "#else",
  9583. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9584. "#endif",
  9585. "bool frustumTest = all( frustumTestVec );",
  9586. "if ( frustumTest ) {",
  9587. "shadowCoord.z += shadowBias[ i ];",
  9588. "#if defined( SHADOWMAP_TYPE_PCF )",
  9589. // Percentage-close filtering
  9590. // (9 pixel kernel)
  9591. // http://fabiensanglard.net/shadowmappingPCF/
  9592. "float shadow = 0.0;",
  9593. /*
  9594. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9595. // must enroll loop manually
  9596. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9597. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9598. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9599. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9600. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9601. "float fDepth = unpackDepth( rgbaDepth );",
  9602. "if ( fDepth < shadowCoord.z )",
  9603. "shadow += 1.0;",
  9604. "}",
  9605. "shadow /= 9.0;",
  9606. */
  9607. "const float shadowDelta = 1.0 / 9.0;",
  9608. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9609. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9610. "float dx0 = -1.25 * xPixelOffset;",
  9611. "float dy0 = -1.25 * yPixelOffset;",
  9612. "float dx1 = 1.25 * xPixelOffset;",
  9613. "float dy1 = 1.25 * yPixelOffset;",
  9614. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9615. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9616. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9617. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9618. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9619. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9620. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9621. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9622. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9623. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9624. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9625. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9626. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9627. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9628. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9629. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9630. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9631. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9632. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9633. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  9634. // Percentage-close filtering
  9635. // (9 pixel kernel)
  9636. // http://fabiensanglard.net/shadowmappingPCF/
  9637. "float shadow = 0.0;",
  9638. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9639. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9640. "float dx0 = -1.0 * xPixelOffset;",
  9641. "float dy0 = -1.0 * yPixelOffset;",
  9642. "float dx1 = 1.0 * xPixelOffset;",
  9643. "float dy1 = 1.0 * yPixelOffset;",
  9644. "mat3 shadowKernel;",
  9645. "mat3 depthKernel;",
  9646. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9647. "if ( depthKernel[0][0] < shadowCoord.z ) shadowKernel[0][0] = 0.25;",
  9648. "else shadowKernel[0][0] = 0.0;",
  9649. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9650. "if ( depthKernel[0][1] < shadowCoord.z ) shadowKernel[0][1] = 0.25;",
  9651. "else shadowKernel[0][1] = 0.0;",
  9652. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9653. "if ( depthKernel[0][2] < shadowCoord.z ) shadowKernel[0][2] = 0.25;",
  9654. "else shadowKernel[0][2] = 0.0;",
  9655. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9656. "if ( depthKernel[1][0] < shadowCoord.z ) shadowKernel[1][0] = 0.25;",
  9657. "else shadowKernel[1][0] = 0.0;",
  9658. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9659. "if ( depthKernel[1][1] < shadowCoord.z ) shadowKernel[1][1] = 0.25;",
  9660. "else shadowKernel[1][1] = 0.0;",
  9661. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9662. "if ( depthKernel[1][2] < shadowCoord.z ) shadowKernel[1][2] = 0.25;",
  9663. "else shadowKernel[1][2] = 0.0;",
  9664. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9665. "if ( depthKernel[2][0] < shadowCoord.z ) shadowKernel[2][0] = 0.25;",
  9666. "else shadowKernel[2][0] = 0.0;",
  9667. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9668. "if ( depthKernel[2][1] < shadowCoord.z ) shadowKernel[2][1] = 0.25;",
  9669. "else shadowKernel[2][1] = 0.0;",
  9670. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9671. "if ( depthKernel[2][2] < shadowCoord.z ) shadowKernel[2][2] = 0.25;",
  9672. "else shadowKernel[2][2] = 0.0;",
  9673. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  9674. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  9675. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  9676. "vec4 shadowValues;",
  9677. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  9678. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  9679. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  9680. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  9681. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  9682. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9683. "#else",
  9684. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  9685. "float fDepth = unpackDepth( rgbaDepth );",
  9686. "if ( fDepth < shadowCoord.z )",
  9687. // spot with multiple shadows is darker
  9688. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  9689. // spot with multiple shadows has the same color as single shadow spot
  9690. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  9691. "#endif",
  9692. "}",
  9693. "#ifdef SHADOWMAP_DEBUG",
  9694. "#ifdef SHADOWMAP_CASCADE",
  9695. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  9696. "#else",
  9697. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  9698. "#endif",
  9699. "#endif",
  9700. "}",
  9701. "#ifdef GAMMA_OUTPUT",
  9702. "shadowColor *= shadowColor;",
  9703. "#endif",
  9704. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  9705. "#endif"
  9706. ].join("\n"),
  9707. shadowmap_pars_vertex: [
  9708. "#ifdef USE_SHADOWMAP",
  9709. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9710. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  9711. "#endif"
  9712. ].join("\n"),
  9713. shadowmap_vertex: [
  9714. "#ifdef USE_SHADOWMAP",
  9715. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9716. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  9717. "}",
  9718. "#endif"
  9719. ].join("\n"),
  9720. // ALPHATEST
  9721. alphatest_fragment: [
  9722. "#ifdef ALPHATEST",
  9723. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  9724. "#endif"
  9725. ].join("\n"),
  9726. // LINEAR SPACE
  9727. linear_to_gamma_fragment: [
  9728. "#ifdef GAMMA_OUTPUT",
  9729. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9730. "#endif"
  9731. ].join("\n")
  9732. };
  9733. THREE.UniformsUtils = {
  9734. merge: function ( uniforms ) {
  9735. var u, p, tmp, merged = {};
  9736. for ( u = 0; u < uniforms.length; u ++ ) {
  9737. tmp = this.clone( uniforms[ u ] );
  9738. for ( p in tmp ) {
  9739. merged[ p ] = tmp[ p ];
  9740. }
  9741. }
  9742. return merged;
  9743. },
  9744. clone: function ( uniforms_src ) {
  9745. var u, p, parameter, parameter_src, uniforms_dst = {};
  9746. for ( u in uniforms_src ) {
  9747. uniforms_dst[ u ] = {};
  9748. for ( p in uniforms_src[ u ] ) {
  9749. parameter_src = uniforms_src[ u ][ p ];
  9750. if ( parameter_src instanceof THREE.Color ||
  9751. parameter_src instanceof THREE.Vector2 ||
  9752. parameter_src instanceof THREE.Vector3 ||
  9753. parameter_src instanceof THREE.Vector4 ||
  9754. parameter_src instanceof THREE.Matrix4 ||
  9755. parameter_src instanceof THREE.Texture ) {
  9756. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9757. } else if ( parameter_src instanceof Array ) {
  9758. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9759. } else {
  9760. uniforms_dst[ u ][ p ] = parameter_src;
  9761. }
  9762. }
  9763. }
  9764. return uniforms_dst;
  9765. }
  9766. };
  9767. THREE.UniformsLib = {
  9768. common: {
  9769. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9770. "opacity" : { type: "f", value: 1.0 },
  9771. "map" : { type: "t", value: null },
  9772. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9773. "lightMap" : { type: "t", value: null },
  9774. "specularMap" : { type: "t", value: null },
  9775. "envMap" : { type: "t", value: null },
  9776. "flipEnvMap" : { type: "f", value: -1 },
  9777. "useRefract" : { type: "i", value: 0 },
  9778. "reflectivity" : { type: "f", value: 1.0 },
  9779. "refractionRatio" : { type: "f", value: 0.98 },
  9780. "combine" : { type: "i", value: 0 },
  9781. "morphTargetInfluences" : { type: "f", value: 0 }
  9782. },
  9783. bump: {
  9784. "bumpMap" : { type: "t", value: null },
  9785. "bumpScale" : { type: "f", value: 1 }
  9786. },
  9787. normalmap: {
  9788. "normalMap" : { type: "t", value: null },
  9789. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9790. },
  9791. fog : {
  9792. "fogDensity" : { type: "f", value: 0.00025 },
  9793. "fogNear" : { type: "f", value: 1 },
  9794. "fogFar" : { type: "f", value: 2000 },
  9795. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9796. },
  9797. lights: {
  9798. "ambientLightColor" : { type: "fv", value: [] },
  9799. "directionalLightDirection" : { type: "fv", value: [] },
  9800. "directionalLightColor" : { type: "fv", value: [] },
  9801. "hemisphereLightDirection" : { type: "fv", value: [] },
  9802. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9803. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9804. "pointLightColor" : { type: "fv", value: [] },
  9805. "pointLightPosition" : { type: "fv", value: [] },
  9806. "pointLightDistance" : { type: "fv1", value: [] },
  9807. "spotLightColor" : { type: "fv", value: [] },
  9808. "spotLightPosition" : { type: "fv", value: [] },
  9809. "spotLightDirection" : { type: "fv", value: [] },
  9810. "spotLightDistance" : { type: "fv1", value: [] },
  9811. "spotLightAngleCos" : { type: "fv1", value: [] },
  9812. "spotLightExponent" : { type: "fv1", value: [] }
  9813. },
  9814. particle: {
  9815. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9816. "opacity" : { type: "f", value: 1.0 },
  9817. "size" : { type: "f", value: 1.0 },
  9818. "scale" : { type: "f", value: 1.0 },
  9819. "map" : { type: "t", value: null },
  9820. "fogDensity" : { type: "f", value: 0.00025 },
  9821. "fogNear" : { type: "f", value: 1 },
  9822. "fogFar" : { type: "f", value: 2000 },
  9823. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9824. },
  9825. shadowmap: {
  9826. "shadowMap": { type: "tv", value: [] },
  9827. "shadowMapSize": { type: "v2v", value: [] },
  9828. "shadowBias" : { type: "fv1", value: [] },
  9829. "shadowDarkness": { type: "fv1", value: [] },
  9830. "shadowMatrix" : { type: "m4v", value: [] }
  9831. }
  9832. };
  9833. THREE.ShaderLib = {
  9834. 'depth': {
  9835. uniforms: {
  9836. "mNear": { type: "f", value: 1.0 },
  9837. "mFar" : { type: "f", value: 2000.0 },
  9838. "opacity" : { type: "f", value: 1.0 }
  9839. },
  9840. vertexShader: [
  9841. "void main() {",
  9842. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  9843. "}"
  9844. ].join("\n"),
  9845. fragmentShader: [
  9846. "uniform float mNear;",
  9847. "uniform float mFar;",
  9848. "uniform float opacity;",
  9849. "void main() {",
  9850. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9851. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  9852. "gl_FragColor = vec4( vec3( color ), opacity );",
  9853. "}"
  9854. ].join("\n")
  9855. },
  9856. 'normal': {
  9857. uniforms: {
  9858. "opacity" : { type: "f", value: 1.0 }
  9859. },
  9860. vertexShader: [
  9861. "varying vec3 vNormal;",
  9862. "void main() {",
  9863. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9864. "vNormal = normalize( normalMatrix * normal );",
  9865. "gl_Position = projectionMatrix * mvPosition;",
  9866. "}"
  9867. ].join("\n"),
  9868. fragmentShader: [
  9869. "uniform float opacity;",
  9870. "varying vec3 vNormal;",
  9871. "void main() {",
  9872. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  9873. "}"
  9874. ].join("\n")
  9875. },
  9876. 'basic': {
  9877. uniforms: THREE.UniformsUtils.merge( [
  9878. THREE.UniformsLib[ "common" ],
  9879. THREE.UniformsLib[ "fog" ],
  9880. THREE.UniformsLib[ "shadowmap" ]
  9881. ] ),
  9882. vertexShader: [
  9883. THREE.ShaderChunk[ "map_pars_vertex" ],
  9884. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9885. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9886. THREE.ShaderChunk[ "color_pars_vertex" ],
  9887. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9888. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9889. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9890. "void main() {",
  9891. THREE.ShaderChunk[ "map_vertex" ],
  9892. THREE.ShaderChunk[ "lightmap_vertex" ],
  9893. THREE.ShaderChunk[ "color_vertex" ],
  9894. THREE.ShaderChunk[ "skinbase_vertex" ],
  9895. "#ifdef USE_ENVMAP",
  9896. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9897. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9898. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9899. "#endif",
  9900. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9901. THREE.ShaderChunk[ "skinning_vertex" ],
  9902. THREE.ShaderChunk[ "default_vertex" ],
  9903. THREE.ShaderChunk[ "worldpos_vertex" ],
  9904. THREE.ShaderChunk[ "envmap_vertex" ],
  9905. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9906. "}"
  9907. ].join("\n"),
  9908. fragmentShader: [
  9909. "uniform vec3 diffuse;",
  9910. "uniform float opacity;",
  9911. THREE.ShaderChunk[ "color_pars_fragment" ],
  9912. THREE.ShaderChunk[ "map_pars_fragment" ],
  9913. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9914. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9915. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9916. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9917. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9918. "void main() {",
  9919. "gl_FragColor = vec4( diffuse, opacity );",
  9920. THREE.ShaderChunk[ "map_fragment" ],
  9921. THREE.ShaderChunk[ "alphatest_fragment" ],
  9922. THREE.ShaderChunk[ "specularmap_fragment" ],
  9923. THREE.ShaderChunk[ "lightmap_fragment" ],
  9924. THREE.ShaderChunk[ "color_fragment" ],
  9925. THREE.ShaderChunk[ "envmap_fragment" ],
  9926. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9927. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9928. THREE.ShaderChunk[ "fog_fragment" ],
  9929. "}"
  9930. ].join("\n")
  9931. },
  9932. 'lambert': {
  9933. uniforms: THREE.UniformsUtils.merge( [
  9934. THREE.UniformsLib[ "common" ],
  9935. THREE.UniformsLib[ "fog" ],
  9936. THREE.UniformsLib[ "lights" ],
  9937. THREE.UniformsLib[ "shadowmap" ],
  9938. {
  9939. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9940. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9941. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9942. }
  9943. ] ),
  9944. vertexShader: [
  9945. "#define LAMBERT",
  9946. "varying vec3 vLightFront;",
  9947. "#ifdef DOUBLE_SIDED",
  9948. "varying vec3 vLightBack;",
  9949. "#endif",
  9950. THREE.ShaderChunk[ "map_pars_vertex" ],
  9951. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9952. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9953. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9954. THREE.ShaderChunk[ "color_pars_vertex" ],
  9955. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9956. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9957. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9958. "void main() {",
  9959. THREE.ShaderChunk[ "map_vertex" ],
  9960. THREE.ShaderChunk[ "lightmap_vertex" ],
  9961. THREE.ShaderChunk[ "color_vertex" ],
  9962. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9963. THREE.ShaderChunk[ "skinbase_vertex" ],
  9964. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9965. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9966. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9967. THREE.ShaderChunk[ "skinning_vertex" ],
  9968. THREE.ShaderChunk[ "default_vertex" ],
  9969. THREE.ShaderChunk[ "worldpos_vertex" ],
  9970. THREE.ShaderChunk[ "envmap_vertex" ],
  9971. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9972. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9973. "}"
  9974. ].join("\n"),
  9975. fragmentShader: [
  9976. "uniform float opacity;",
  9977. "varying vec3 vLightFront;",
  9978. "#ifdef DOUBLE_SIDED",
  9979. "varying vec3 vLightBack;",
  9980. "#endif",
  9981. THREE.ShaderChunk[ "color_pars_fragment" ],
  9982. THREE.ShaderChunk[ "map_pars_fragment" ],
  9983. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9984. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9985. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9986. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9987. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9988. "void main() {",
  9989. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9990. THREE.ShaderChunk[ "map_fragment" ],
  9991. THREE.ShaderChunk[ "alphatest_fragment" ],
  9992. THREE.ShaderChunk[ "specularmap_fragment" ],
  9993. "#ifdef DOUBLE_SIDED",
  9994. //"float isFront = float( gl_FrontFacing );",
  9995. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9996. "if ( gl_FrontFacing )",
  9997. "gl_FragColor.xyz *= vLightFront;",
  9998. "else",
  9999. "gl_FragColor.xyz *= vLightBack;",
  10000. "#else",
  10001. "gl_FragColor.xyz *= vLightFront;",
  10002. "#endif",
  10003. THREE.ShaderChunk[ "lightmap_fragment" ],
  10004. THREE.ShaderChunk[ "color_fragment" ],
  10005. THREE.ShaderChunk[ "envmap_fragment" ],
  10006. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10007. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10008. THREE.ShaderChunk[ "fog_fragment" ],
  10009. "}"
  10010. ].join("\n")
  10011. },
  10012. 'phong': {
  10013. uniforms: THREE.UniformsUtils.merge( [
  10014. THREE.UniformsLib[ "common" ],
  10015. THREE.UniformsLib[ "bump" ],
  10016. THREE.UniformsLib[ "normalmap" ],
  10017. THREE.UniformsLib[ "fog" ],
  10018. THREE.UniformsLib[ "lights" ],
  10019. THREE.UniformsLib[ "shadowmap" ],
  10020. {
  10021. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10022. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10023. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10024. "shininess": { type: "f", value: 30 },
  10025. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10026. }
  10027. ] ),
  10028. vertexShader: [
  10029. "#define PHONG",
  10030. "varying vec3 vViewPosition;",
  10031. "varying vec3 vNormal;",
  10032. THREE.ShaderChunk[ "map_pars_vertex" ],
  10033. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10034. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10035. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10036. THREE.ShaderChunk[ "color_pars_vertex" ],
  10037. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10038. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10039. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10040. "void main() {",
  10041. THREE.ShaderChunk[ "map_vertex" ],
  10042. THREE.ShaderChunk[ "lightmap_vertex" ],
  10043. THREE.ShaderChunk[ "color_vertex" ],
  10044. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10045. THREE.ShaderChunk[ "skinbase_vertex" ],
  10046. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10047. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10048. "vNormal = normalize( transformedNormal );",
  10049. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10050. THREE.ShaderChunk[ "skinning_vertex" ],
  10051. THREE.ShaderChunk[ "default_vertex" ],
  10052. "vViewPosition = -mvPosition.xyz;",
  10053. THREE.ShaderChunk[ "worldpos_vertex" ],
  10054. THREE.ShaderChunk[ "envmap_vertex" ],
  10055. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10056. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10057. "}"
  10058. ].join("\n"),
  10059. fragmentShader: [
  10060. "uniform vec3 diffuse;",
  10061. "uniform float opacity;",
  10062. "uniform vec3 ambient;",
  10063. "uniform vec3 emissive;",
  10064. "uniform vec3 specular;",
  10065. "uniform float shininess;",
  10066. THREE.ShaderChunk[ "color_pars_fragment" ],
  10067. THREE.ShaderChunk[ "map_pars_fragment" ],
  10068. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10069. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10070. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10071. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10072. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10073. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10074. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10075. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10076. "void main() {",
  10077. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10078. THREE.ShaderChunk[ "map_fragment" ],
  10079. THREE.ShaderChunk[ "alphatest_fragment" ],
  10080. THREE.ShaderChunk[ "specularmap_fragment" ],
  10081. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10082. THREE.ShaderChunk[ "lightmap_fragment" ],
  10083. THREE.ShaderChunk[ "color_fragment" ],
  10084. THREE.ShaderChunk[ "envmap_fragment" ],
  10085. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10086. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10087. THREE.ShaderChunk[ "fog_fragment" ],
  10088. "}"
  10089. ].join("\n")
  10090. },
  10091. 'particle_basic': {
  10092. uniforms: THREE.UniformsUtils.merge( [
  10093. THREE.UniformsLib[ "particle" ],
  10094. THREE.UniformsLib[ "shadowmap" ]
  10095. ] ),
  10096. vertexShader: [
  10097. "uniform float size;",
  10098. "uniform float scale;",
  10099. THREE.ShaderChunk[ "color_pars_vertex" ],
  10100. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10101. "void main() {",
  10102. THREE.ShaderChunk[ "color_vertex" ],
  10103. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10104. "#ifdef USE_SIZEATTENUATION",
  10105. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10106. "#else",
  10107. "gl_PointSize = size;",
  10108. "#endif",
  10109. "gl_Position = projectionMatrix * mvPosition;",
  10110. THREE.ShaderChunk[ "worldpos_vertex" ],
  10111. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10112. "}"
  10113. ].join("\n"),
  10114. fragmentShader: [
  10115. "uniform vec3 psColor;",
  10116. "uniform float opacity;",
  10117. THREE.ShaderChunk[ "color_pars_fragment" ],
  10118. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10119. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10120. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10121. "void main() {",
  10122. "gl_FragColor = vec4( psColor, opacity );",
  10123. THREE.ShaderChunk[ "map_particle_fragment" ],
  10124. THREE.ShaderChunk[ "alphatest_fragment" ],
  10125. THREE.ShaderChunk[ "color_fragment" ],
  10126. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10127. THREE.ShaderChunk[ "fog_fragment" ],
  10128. "}"
  10129. ].join("\n")
  10130. },
  10131. 'dashed': {
  10132. uniforms: THREE.UniformsUtils.merge( [
  10133. THREE.UniformsLib[ "common" ],
  10134. THREE.UniformsLib[ "fog" ],
  10135. {
  10136. "scale": { type: "f", value: 1 },
  10137. "dashSize": { type: "f", value: 1 },
  10138. "totalSize": { type: "f", value: 2 }
  10139. }
  10140. ] ),
  10141. vertexShader: [
  10142. "uniform float scale;",
  10143. "attribute float lineDistance;",
  10144. "varying float vLineDistance;",
  10145. THREE.ShaderChunk[ "color_pars_vertex" ],
  10146. "void main() {",
  10147. THREE.ShaderChunk[ "color_vertex" ],
  10148. "vLineDistance = scale * lineDistance;",
  10149. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10150. "gl_Position = projectionMatrix * mvPosition;",
  10151. "}"
  10152. ].join("\n"),
  10153. fragmentShader: [
  10154. "uniform vec3 diffuse;",
  10155. "uniform float opacity;",
  10156. "uniform float dashSize;",
  10157. "uniform float totalSize;",
  10158. "varying float vLineDistance;",
  10159. THREE.ShaderChunk[ "color_pars_fragment" ],
  10160. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10161. "void main() {",
  10162. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10163. "discard;",
  10164. "}",
  10165. "gl_FragColor = vec4( diffuse, opacity );",
  10166. THREE.ShaderChunk[ "color_fragment" ],
  10167. THREE.ShaderChunk[ "fog_fragment" ],
  10168. "}"
  10169. ].join("\n")
  10170. },
  10171. // Depth encoding into RGBA texture
  10172. // based on SpiderGL shadow map example
  10173. // http://spidergl.org/example.php?id=6
  10174. // originally from
  10175. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10176. // see also here:
  10177. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10178. 'depthRGBA': {
  10179. uniforms: {},
  10180. vertexShader: [
  10181. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10182. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10183. "void main() {",
  10184. THREE.ShaderChunk[ "skinbase_vertex" ],
  10185. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10186. THREE.ShaderChunk[ "skinning_vertex" ],
  10187. THREE.ShaderChunk[ "default_vertex" ],
  10188. "}"
  10189. ].join("\n"),
  10190. fragmentShader: [
  10191. "vec4 pack_depth( const in float depth ) {",
  10192. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10193. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10194. "vec4 res = fract( depth * bit_shift );",
  10195. "res -= res.xxyz * bit_mask;",
  10196. "return res;",
  10197. "}",
  10198. "void main() {",
  10199. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10200. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10201. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10202. //"gl_FragData[ 0 ] = pack_depth( z );",
  10203. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10204. "}"
  10205. ].join("\n")
  10206. }
  10207. };
  10208. /**
  10209. * @author supereggbert / http://www.paulbrunt.co.uk/
  10210. * @author mrdoob / http://mrdoob.com/
  10211. * @author alteredq / http://alteredqualia.com/
  10212. * @author szimek / https://github.com/szimek/
  10213. */
  10214. THREE.WebGLRenderer = function ( parameters ) {
  10215. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10216. parameters = parameters || {};
  10217. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10218. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10219. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  10220. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10221. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10222. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10223. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10224. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  10225. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  10226. // public properties
  10227. this.domElement = _canvas;
  10228. this.context = null;
  10229. // clearing
  10230. this.autoClear = true;
  10231. this.autoClearColor = true;
  10232. this.autoClearDepth = true;
  10233. this.autoClearStencil = true;
  10234. // scene graph
  10235. this.sortObjects = true;
  10236. this.autoUpdateObjects = true;
  10237. this.autoUpdateScene = true;
  10238. // physically based shading
  10239. this.gammaInput = false;
  10240. this.gammaOutput = false;
  10241. this.physicallyBasedShading = false;
  10242. // shadow map
  10243. this.shadowMapEnabled = false;
  10244. this.shadowMapAutoUpdate = true;
  10245. this.shadowMapType = THREE.PCFShadowMap;
  10246. this.shadowMapCullFace = THREE.CullFaceFront;
  10247. this.shadowMapDebug = false;
  10248. this.shadowMapCascade = false;
  10249. // morphs
  10250. this.maxMorphTargets = 8;
  10251. this.maxMorphNormals = 4;
  10252. // flags
  10253. this.autoScaleCubemaps = true;
  10254. // custom render plugins
  10255. this.renderPluginsPre = [];
  10256. this.renderPluginsPost = [];
  10257. // info
  10258. this.info = {
  10259. memory: {
  10260. programs: 0,
  10261. geometries: 0,
  10262. textures: 0
  10263. },
  10264. render: {
  10265. calls: 0,
  10266. vertices: 0,
  10267. faces: 0,
  10268. points: 0
  10269. }
  10270. };
  10271. // internal properties
  10272. var _this = this,
  10273. _programs = [],
  10274. _programs_counter = 0,
  10275. // internal state cache
  10276. _currentProgram = null,
  10277. _currentFramebuffer = null,
  10278. _currentMaterialId = -1,
  10279. _currentGeometryGroupHash = null,
  10280. _currentCamera = null,
  10281. _geometryGroupCounter = 0,
  10282. _usedTextureUnits = 0,
  10283. // GL state cache
  10284. _oldDoubleSided = -1,
  10285. _oldFlipSided = -1,
  10286. _oldBlending = -1,
  10287. _oldBlendEquation = -1,
  10288. _oldBlendSrc = -1,
  10289. _oldBlendDst = -1,
  10290. _oldDepthTest = -1,
  10291. _oldDepthWrite = -1,
  10292. _oldPolygonOffset = null,
  10293. _oldPolygonOffsetFactor = null,
  10294. _oldPolygonOffsetUnits = null,
  10295. _oldLineWidth = null,
  10296. _viewportX = 0,
  10297. _viewportY = 0,
  10298. _viewportWidth = 0,
  10299. _viewportHeight = 0,
  10300. _currentWidth = 0,
  10301. _currentHeight = 0,
  10302. _enabledAttributes = {},
  10303. // frustum
  10304. _frustum = new THREE.Frustum(),
  10305. // camera matrices cache
  10306. _projScreenMatrix = new THREE.Matrix4(),
  10307. _projScreenMatrixPS = new THREE.Matrix4(),
  10308. _vector3 = new THREE.Vector3(),
  10309. // light arrays cache
  10310. _direction = new THREE.Vector3(),
  10311. _lightsNeedUpdate = true,
  10312. _lights = {
  10313. ambient: [ 0, 0, 0 ],
  10314. directional: { length: 0, colors: new Array(), positions: new Array() },
  10315. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  10316. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  10317. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  10318. };
  10319. // initialize
  10320. var _gl;
  10321. var _glExtensionTextureFloat;
  10322. var _glExtensionStandardDerivatives;
  10323. var _glExtensionTextureFilterAnisotropic;
  10324. var _glExtensionCompressedTextureS3TC;
  10325. initGL();
  10326. setDefaultGLState();
  10327. this.context = _gl;
  10328. // GPU capabilities
  10329. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10330. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10331. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10332. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10333. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10334. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  10335. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  10336. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  10337. //
  10338. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  10339. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  10340. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  10341. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  10342. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  10343. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  10344. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  10345. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  10346. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  10347. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  10348. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  10349. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  10350. // clamp precision to maximum available
  10351. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  10352. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  10353. if ( _precision === "highp" && ! highpAvailable ) {
  10354. if ( mediumpAvailable ) {
  10355. _precision = "mediump";
  10356. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  10357. } else {
  10358. _precision = "lowp";
  10359. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  10360. }
  10361. }
  10362. if ( _precision === "mediump" && ! mediumpAvailable ) {
  10363. _precision = "lowp";
  10364. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  10365. }
  10366. // API
  10367. this.getContext = function () {
  10368. return _gl;
  10369. };
  10370. this.supportsVertexTextures = function () {
  10371. return _supportsVertexTextures;
  10372. };
  10373. this.getMaxAnisotropy = function () {
  10374. return _maxAnisotropy;
  10375. };
  10376. this.setSize = function ( width, height ) {
  10377. _canvas.width = width;
  10378. _canvas.height = height;
  10379. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  10380. };
  10381. this.setViewport = function ( x, y, width, height ) {
  10382. _viewportX = x !== undefined ? x : 0;
  10383. _viewportY = y !== undefined ? y : 0;
  10384. _viewportWidth = width !== undefined ? width : _canvas.width;
  10385. _viewportHeight = height !== undefined ? height : _canvas.height;
  10386. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10387. };
  10388. this.setScissor = function ( x, y, width, height ) {
  10389. _gl.scissor( x, y, width, height );
  10390. };
  10391. this.enableScissorTest = function ( enable ) {
  10392. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  10393. };
  10394. // Clearing
  10395. this.setClearColorHex = function ( hex, alpha ) {
  10396. _clearColor.setHex( hex );
  10397. _clearAlpha = alpha;
  10398. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10399. };
  10400. this.setClearColor = function ( color, alpha ) {
  10401. _clearColor.copy( color );
  10402. _clearAlpha = alpha;
  10403. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10404. };
  10405. this.getClearColor = function () {
  10406. return _clearColor;
  10407. };
  10408. this.getClearAlpha = function () {
  10409. return _clearAlpha;
  10410. };
  10411. this.clear = function ( color, depth, stencil ) {
  10412. var bits = 0;
  10413. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  10414. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  10415. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  10416. _gl.clear( bits );
  10417. };
  10418. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  10419. this.setRenderTarget( renderTarget );
  10420. this.clear( color, depth, stencil );
  10421. };
  10422. // Plugins
  10423. this.addPostPlugin = function ( plugin ) {
  10424. plugin.init( this );
  10425. this.renderPluginsPost.push( plugin );
  10426. };
  10427. this.addPrePlugin = function ( plugin ) {
  10428. plugin.init( this );
  10429. this.renderPluginsPre.push( plugin );
  10430. };
  10431. // Rendering
  10432. this.updateShadowMap = function ( scene, camera ) {
  10433. _currentProgram = null;
  10434. _oldBlending = -1;
  10435. _oldDepthTest = -1;
  10436. _oldDepthWrite = -1;
  10437. _currentGeometryGroupHash = -1;
  10438. _currentMaterialId = -1;
  10439. _lightsNeedUpdate = true;
  10440. _oldDoubleSided = -1;
  10441. _oldFlipSided = -1;
  10442. this.shadowMapPlugin.update( scene, camera );
  10443. };
  10444. // Internal functions
  10445. // Buffer allocation
  10446. function createParticleBuffers ( geometry ) {
  10447. geometry.__webglVertexBuffer = _gl.createBuffer();
  10448. geometry.__webglColorBuffer = _gl.createBuffer();
  10449. _this.info.memory.geometries ++;
  10450. };
  10451. function createLineBuffers ( geometry ) {
  10452. geometry.__webglVertexBuffer = _gl.createBuffer();
  10453. geometry.__webglColorBuffer = _gl.createBuffer();
  10454. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  10455. _this.info.memory.geometries ++;
  10456. };
  10457. function createRibbonBuffers ( geometry ) {
  10458. geometry.__webglVertexBuffer = _gl.createBuffer();
  10459. geometry.__webglColorBuffer = _gl.createBuffer();
  10460. geometry.__webglNormalBuffer = _gl.createBuffer();
  10461. _this.info.memory.geometries ++;
  10462. };
  10463. function createMeshBuffers ( geometryGroup ) {
  10464. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  10465. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  10466. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  10467. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  10468. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  10469. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  10470. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  10471. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  10472. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  10473. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  10474. var m, ml;
  10475. if ( geometryGroup.numMorphTargets ) {
  10476. geometryGroup.__webglMorphTargetsBuffers = [];
  10477. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10478. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  10479. }
  10480. }
  10481. if ( geometryGroup.numMorphNormals ) {
  10482. geometryGroup.__webglMorphNormalsBuffers = [];
  10483. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10484. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  10485. }
  10486. }
  10487. _this.info.memory.geometries ++;
  10488. };
  10489. // Events
  10490. var onGeometryDispose = function ( event ) {
  10491. var geometry = event.target;
  10492. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10493. deallocateGeometry( geometry );
  10494. _this.info.memory.geometries --;
  10495. };
  10496. var onTextureDispose = function ( event ) {
  10497. var texture = event.target;
  10498. texture.removeEventListener( 'dispose', onTextureDispose );
  10499. deallocateTexture( texture );
  10500. _this.info.memory.textures --;
  10501. };
  10502. var onRenderTargetDispose = function ( event ) {
  10503. var renderTarget = event.target;
  10504. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10505. deallocateRenderTarget( renderTarget );
  10506. _this.info.memory.textures --;
  10507. };
  10508. var onMaterialDispose = function ( event ) {
  10509. var material = event.target;
  10510. material.removeEventListener( 'dispose', onMaterialDispose );
  10511. deallocateMaterial( material );
  10512. };
  10513. // Buffer deallocation
  10514. var deallocateGeometry = function ( geometry ) {
  10515. geometry.__webglInit = undefined;
  10516. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10517. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10518. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  10519. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  10520. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  10521. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  10522. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  10523. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  10524. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  10525. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  10526. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10527. // geometry groups
  10528. if ( geometry.geometryGroups !== undefined ) {
  10529. for ( var g in geometry.geometryGroups ) {
  10530. var geometryGroup = geometry.geometryGroups[ g ];
  10531. if ( geometryGroup.numMorphTargets !== undefined ) {
  10532. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10533. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10534. }
  10535. }
  10536. if ( geometryGroup.numMorphNormals !== undefined ) {
  10537. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10538. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10539. }
  10540. }
  10541. deleteCustomAttributesBuffers( geometryGroup );
  10542. }
  10543. }
  10544. deleteCustomAttributesBuffers( geometry );
  10545. };
  10546. var deallocateTexture = function ( texture ) {
  10547. if ( texture.image && texture.image.__webglTextureCube ) {
  10548. // cube texture
  10549. _gl.deleteTexture( texture.image.__webglTextureCube );
  10550. } else {
  10551. // 2D texture
  10552. if ( ! texture.__webglInit ) return;
  10553. texture.__webglInit = false;
  10554. _gl.deleteTexture( texture.__webglTexture );
  10555. }
  10556. };
  10557. var deallocateRenderTarget = function ( renderTarget ) {
  10558. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  10559. _gl.deleteTexture( renderTarget.__webglTexture );
  10560. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  10561. for ( var i = 0; i < 6; i ++ ) {
  10562. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  10563. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  10564. }
  10565. } else {
  10566. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  10567. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  10568. }
  10569. };
  10570. var deallocateMaterial = function ( material ) {
  10571. var program = material.program;
  10572. if ( program === undefined ) return;
  10573. material.program = undefined;
  10574. // only deallocate GL program if this was the last use of shared program
  10575. // assumed there is only single copy of any program in the _programs list
  10576. // (that's how it's constructed)
  10577. var i, il, programInfo;
  10578. var deleteProgram = false;
  10579. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10580. programInfo = _programs[ i ];
  10581. if ( programInfo.program === program ) {
  10582. programInfo.usedTimes --;
  10583. if ( programInfo.usedTimes === 0 ) {
  10584. deleteProgram = true;
  10585. }
  10586. break;
  10587. }
  10588. }
  10589. if ( deleteProgram === true ) {
  10590. // avoid using array.splice, this is costlier than creating new array from scratch
  10591. var newPrograms = [];
  10592. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10593. programInfo = _programs[ i ];
  10594. if ( programInfo.program !== program ) {
  10595. newPrograms.push( programInfo );
  10596. }
  10597. }
  10598. _programs = newPrograms;
  10599. _gl.deleteProgram( program );
  10600. _this.info.memory.programs --;
  10601. }
  10602. };
  10603. //
  10604. /*
  10605. function deleteParticleBuffers ( geometry ) {
  10606. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10607. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10608. deleteCustomAttributesBuffers( geometry );
  10609. _this.info.memory.geometries --;
  10610. };
  10611. function deleteLineBuffers ( geometry ) {
  10612. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10613. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10614. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10615. deleteCustomAttributesBuffers( geometry );
  10616. _this.info.memory.geometries --;
  10617. };
  10618. function deleteRibbonBuffers ( geometry ) {
  10619. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10620. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10621. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10622. deleteCustomAttributesBuffers( geometry );
  10623. _this.info.memory.geometries --;
  10624. };
  10625. function deleteMeshBuffers ( geometryGroup ) {
  10626. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  10627. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  10628. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  10629. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  10630. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  10631. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  10632. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  10633. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  10634. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  10635. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  10636. var m, ml;
  10637. if ( geometryGroup.numMorphTargets ) {
  10638. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10639. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10640. }
  10641. }
  10642. if ( geometryGroup.numMorphNormals ) {
  10643. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10644. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10645. }
  10646. }
  10647. deleteCustomAttributesBuffers( geometryGroup );
  10648. _this.info.memory.geometries --;
  10649. };
  10650. */
  10651. function deleteCustomAttributesBuffers( geometry ) {
  10652. if ( geometry.__webglCustomAttributesList ) {
  10653. for ( var id in geometry.__webglCustomAttributesList ) {
  10654. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  10655. }
  10656. }
  10657. };
  10658. // Buffer initialization
  10659. function initCustomAttributes ( geometry, object ) {
  10660. var nvertices = geometry.vertices.length;
  10661. var material = object.material;
  10662. if ( material.attributes ) {
  10663. if ( geometry.__webglCustomAttributesList === undefined ) {
  10664. geometry.__webglCustomAttributesList = [];
  10665. }
  10666. for ( var a in material.attributes ) {
  10667. var attribute = material.attributes[ a ];
  10668. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10669. attribute.__webglInitialized = true;
  10670. var size = 1; // "f" and "i"
  10671. if ( attribute.type === "v2" ) size = 2;
  10672. else if ( attribute.type === "v3" ) size = 3;
  10673. else if ( attribute.type === "v4" ) size = 4;
  10674. else if ( attribute.type === "c" ) size = 3;
  10675. attribute.size = size;
  10676. attribute.array = new Float32Array( nvertices * size );
  10677. attribute.buffer = _gl.createBuffer();
  10678. attribute.buffer.belongsToAttribute = a;
  10679. attribute.needsUpdate = true;
  10680. }
  10681. geometry.__webglCustomAttributesList.push( attribute );
  10682. }
  10683. }
  10684. };
  10685. function initParticleBuffers ( geometry, object ) {
  10686. var nvertices = geometry.vertices.length;
  10687. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10688. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10689. geometry.__sortArray = [];
  10690. geometry.__webglParticleCount = nvertices;
  10691. initCustomAttributes ( geometry, object );
  10692. };
  10693. function initLineBuffers ( geometry, object ) {
  10694. var nvertices = geometry.vertices.length;
  10695. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10696. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10697. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  10698. geometry.__webglLineCount = nvertices;
  10699. initCustomAttributes ( geometry, object );
  10700. };
  10701. function initRibbonBuffers ( geometry, object ) {
  10702. var nvertices = geometry.vertices.length;
  10703. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10704. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10705. geometry.__normalArray = new Float32Array( nvertices * 3 );
  10706. geometry.__webglVertexCount = nvertices;
  10707. initCustomAttributes ( geometry, object );
  10708. };
  10709. function initMeshBuffers ( geometryGroup, object ) {
  10710. var geometry = object.geometry,
  10711. faces3 = geometryGroup.faces3,
  10712. faces4 = geometryGroup.faces4,
  10713. nvertices = faces3.length * 3 + faces4.length * 4,
  10714. ntris = faces3.length * 1 + faces4.length * 2,
  10715. nlines = faces3.length * 3 + faces4.length * 4,
  10716. material = getBufferMaterial( object, geometryGroup ),
  10717. uvType = bufferGuessUVType( material ),
  10718. normalType = bufferGuessNormalType( material ),
  10719. vertexColorType = bufferGuessVertexColorType( material );
  10720. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  10721. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  10722. if ( normalType ) {
  10723. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  10724. }
  10725. if ( geometry.hasTangents ) {
  10726. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  10727. }
  10728. if ( vertexColorType ) {
  10729. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  10730. }
  10731. if ( uvType ) {
  10732. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  10733. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  10734. }
  10735. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  10736. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  10737. }
  10738. }
  10739. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  10740. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  10741. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  10742. }
  10743. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  10744. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  10745. var m, ml;
  10746. if ( geometryGroup.numMorphTargets ) {
  10747. geometryGroup.__morphTargetsArrays = [];
  10748. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10749. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  10750. }
  10751. }
  10752. if ( geometryGroup.numMorphNormals ) {
  10753. geometryGroup.__morphNormalsArrays = [];
  10754. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10755. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  10756. }
  10757. }
  10758. geometryGroup.__webglFaceCount = ntris * 3;
  10759. geometryGroup.__webglLineCount = nlines * 2;
  10760. // custom attributes
  10761. if ( material.attributes ) {
  10762. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  10763. geometryGroup.__webglCustomAttributesList = [];
  10764. }
  10765. for ( var a in material.attributes ) {
  10766. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  10767. // attribute buffers which are correctly indexed in the setMeshBuffers function
  10768. var originalAttribute = material.attributes[ a ];
  10769. var attribute = {};
  10770. for ( var property in originalAttribute ) {
  10771. attribute[ property ] = originalAttribute[ property ];
  10772. }
  10773. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10774. attribute.__webglInitialized = true;
  10775. var size = 1; // "f" and "i"
  10776. if( attribute.type === "v2" ) size = 2;
  10777. else if( attribute.type === "v3" ) size = 3;
  10778. else if( attribute.type === "v4" ) size = 4;
  10779. else if( attribute.type === "c" ) size = 3;
  10780. attribute.size = size;
  10781. attribute.array = new Float32Array( nvertices * size );
  10782. attribute.buffer = _gl.createBuffer();
  10783. attribute.buffer.belongsToAttribute = a;
  10784. originalAttribute.needsUpdate = true;
  10785. attribute.__original = originalAttribute;
  10786. }
  10787. geometryGroup.__webglCustomAttributesList.push( attribute );
  10788. }
  10789. }
  10790. geometryGroup.__inittedArrays = true;
  10791. };
  10792. function getBufferMaterial( object, geometryGroup ) {
  10793. return object.material instanceof THREE.MeshFaceMaterial
  10794. ? object.material.materials[ geometryGroup.materialIndex ]
  10795. : object.material;
  10796. };
  10797. function materialNeedsSmoothNormals ( material ) {
  10798. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  10799. };
  10800. function bufferGuessNormalType ( material ) {
  10801. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  10802. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  10803. return false;
  10804. }
  10805. if ( materialNeedsSmoothNormals( material ) ) {
  10806. return THREE.SmoothShading;
  10807. } else {
  10808. return THREE.FlatShading;
  10809. }
  10810. };
  10811. function bufferGuessVertexColorType ( material ) {
  10812. if ( material.vertexColors ) {
  10813. return material.vertexColors;
  10814. }
  10815. return false;
  10816. };
  10817. function bufferGuessUVType ( material ) {
  10818. // material must use some texture to require uvs
  10819. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  10820. return true;
  10821. }
  10822. return false;
  10823. };
  10824. //
  10825. function initDirectBuffers( geometry ) {
  10826. var a, attribute, type;
  10827. for ( a in geometry.attributes ) {
  10828. if ( a === "index" ) {
  10829. type = _gl.ELEMENT_ARRAY_BUFFER;
  10830. } else {
  10831. type = _gl.ARRAY_BUFFER;
  10832. }
  10833. attribute = geometry.attributes[ a ];
  10834. attribute.buffer = _gl.createBuffer();
  10835. _gl.bindBuffer( type, attribute.buffer );
  10836. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  10837. }
  10838. };
  10839. // Buffer setting
  10840. function setParticleBuffers ( geometry, hint, object ) {
  10841. var v, c, vertex, offset, index, color,
  10842. vertices = geometry.vertices,
  10843. vl = vertices.length,
  10844. colors = geometry.colors,
  10845. cl = colors.length,
  10846. vertexArray = geometry.__vertexArray,
  10847. colorArray = geometry.__colorArray,
  10848. sortArray = geometry.__sortArray,
  10849. dirtyVertices = geometry.verticesNeedUpdate,
  10850. dirtyElements = geometry.elementsNeedUpdate,
  10851. dirtyColors = geometry.colorsNeedUpdate,
  10852. customAttributes = geometry.__webglCustomAttributesList,
  10853. i, il,
  10854. a, ca, cal, value,
  10855. customAttribute;
  10856. if ( object.sortParticles ) {
  10857. _projScreenMatrixPS.copy( _projScreenMatrix );
  10858. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  10859. for ( v = 0; v < vl; v ++ ) {
  10860. vertex = vertices[ v ];
  10861. _vector3.copy( vertex );
  10862. _projScreenMatrixPS.multiplyVector3( _vector3 );
  10863. sortArray[ v ] = [ _vector3.z, v ];
  10864. }
  10865. sortArray.sort( numericalSort );
  10866. for ( v = 0; v < vl; v ++ ) {
  10867. vertex = vertices[ sortArray[v][1] ];
  10868. offset = v * 3;
  10869. vertexArray[ offset ] = vertex.x;
  10870. vertexArray[ offset + 1 ] = vertex.y;
  10871. vertexArray[ offset + 2 ] = vertex.z;
  10872. }
  10873. for ( c = 0; c < cl; c ++ ) {
  10874. offset = c * 3;
  10875. color = colors[ sortArray[c][1] ];
  10876. colorArray[ offset ] = color.r;
  10877. colorArray[ offset + 1 ] = color.g;
  10878. colorArray[ offset + 2 ] = color.b;
  10879. }
  10880. if ( customAttributes ) {
  10881. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10882. customAttribute = customAttributes[ i ];
  10883. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  10884. offset = 0;
  10885. cal = customAttribute.value.length;
  10886. if ( customAttribute.size === 1 ) {
  10887. for ( ca = 0; ca < cal; ca ++ ) {
  10888. index = sortArray[ ca ][ 1 ];
  10889. customAttribute.array[ ca ] = customAttribute.value[ index ];
  10890. }
  10891. } else if ( customAttribute.size === 2 ) {
  10892. for ( ca = 0; ca < cal; ca ++ ) {
  10893. index = sortArray[ ca ][ 1 ];
  10894. value = customAttribute.value[ index ];
  10895. customAttribute.array[ offset ] = value.x;
  10896. customAttribute.array[ offset + 1 ] = value.y;
  10897. offset += 2;
  10898. }
  10899. } else if ( customAttribute.size === 3 ) {
  10900. if ( customAttribute.type === "c" ) {
  10901. for ( ca = 0; ca < cal; ca ++ ) {
  10902. index = sortArray[ ca ][ 1 ];
  10903. value = customAttribute.value[ index ];
  10904. customAttribute.array[ offset ] = value.r;
  10905. customAttribute.array[ offset + 1 ] = value.g;
  10906. customAttribute.array[ offset + 2 ] = value.b;
  10907. offset += 3;
  10908. }
  10909. } else {
  10910. for ( ca = 0; ca < cal; ca ++ ) {
  10911. index = sortArray[ ca ][ 1 ];
  10912. value = customAttribute.value[ index ];
  10913. customAttribute.array[ offset ] = value.x;
  10914. customAttribute.array[ offset + 1 ] = value.y;
  10915. customAttribute.array[ offset + 2 ] = value.z;
  10916. offset += 3;
  10917. }
  10918. }
  10919. } else if ( customAttribute.size === 4 ) {
  10920. for ( ca = 0; ca < cal; ca ++ ) {
  10921. index = sortArray[ ca ][ 1 ];
  10922. value = customAttribute.value[ index ];
  10923. customAttribute.array[ offset ] = value.x;
  10924. customAttribute.array[ offset + 1 ] = value.y;
  10925. customAttribute.array[ offset + 2 ] = value.z;
  10926. customAttribute.array[ offset + 3 ] = value.w;
  10927. offset += 4;
  10928. }
  10929. }
  10930. }
  10931. }
  10932. } else {
  10933. if ( dirtyVertices ) {
  10934. for ( v = 0; v < vl; v ++ ) {
  10935. vertex = vertices[ v ];
  10936. offset = v * 3;
  10937. vertexArray[ offset ] = vertex.x;
  10938. vertexArray[ offset + 1 ] = vertex.y;
  10939. vertexArray[ offset + 2 ] = vertex.z;
  10940. }
  10941. }
  10942. if ( dirtyColors ) {
  10943. for ( c = 0; c < cl; c ++ ) {
  10944. color = colors[ c ];
  10945. offset = c * 3;
  10946. colorArray[ offset ] = color.r;
  10947. colorArray[ offset + 1 ] = color.g;
  10948. colorArray[ offset + 2 ] = color.b;
  10949. }
  10950. }
  10951. if ( customAttributes ) {
  10952. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10953. customAttribute = customAttributes[ i ];
  10954. if ( customAttribute.needsUpdate &&
  10955. ( customAttribute.boundTo === undefined ||
  10956. customAttribute.boundTo === "vertices") ) {
  10957. cal = customAttribute.value.length;
  10958. offset = 0;
  10959. if ( customAttribute.size === 1 ) {
  10960. for ( ca = 0; ca < cal; ca ++ ) {
  10961. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10962. }
  10963. } else if ( customAttribute.size === 2 ) {
  10964. for ( ca = 0; ca < cal; ca ++ ) {
  10965. value = customAttribute.value[ ca ];
  10966. customAttribute.array[ offset ] = value.x;
  10967. customAttribute.array[ offset + 1 ] = value.y;
  10968. offset += 2;
  10969. }
  10970. } else if ( customAttribute.size === 3 ) {
  10971. if ( customAttribute.type === "c" ) {
  10972. for ( ca = 0; ca < cal; ca ++ ) {
  10973. value = customAttribute.value[ ca ];
  10974. customAttribute.array[ offset ] = value.r;
  10975. customAttribute.array[ offset + 1 ] = value.g;
  10976. customAttribute.array[ offset + 2 ] = value.b;
  10977. offset += 3;
  10978. }
  10979. } else {
  10980. for ( ca = 0; ca < cal; ca ++ ) {
  10981. value = customAttribute.value[ ca ];
  10982. customAttribute.array[ offset ] = value.x;
  10983. customAttribute.array[ offset + 1 ] = value.y;
  10984. customAttribute.array[ offset + 2 ] = value.z;
  10985. offset += 3;
  10986. }
  10987. }
  10988. } else if ( customAttribute.size === 4 ) {
  10989. for ( ca = 0; ca < cal; ca ++ ) {
  10990. value = customAttribute.value[ ca ];
  10991. customAttribute.array[ offset ] = value.x;
  10992. customAttribute.array[ offset + 1 ] = value.y;
  10993. customAttribute.array[ offset + 2 ] = value.z;
  10994. customAttribute.array[ offset + 3 ] = value.w;
  10995. offset += 4;
  10996. }
  10997. }
  10998. }
  10999. }
  11000. }
  11001. }
  11002. if ( dirtyVertices || object.sortParticles ) {
  11003. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11004. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11005. }
  11006. if ( dirtyColors || object.sortParticles ) {
  11007. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11008. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11009. }
  11010. if ( customAttributes ) {
  11011. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11012. customAttribute = customAttributes[ i ];
  11013. if ( customAttribute.needsUpdate || object.sortParticles ) {
  11014. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11015. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11016. }
  11017. }
  11018. }
  11019. };
  11020. function setLineBuffers ( geometry, hint ) {
  11021. var v, c, d, vertex, offset, color,
  11022. vertices = geometry.vertices,
  11023. colors = geometry.colors,
  11024. lineDistances = geometry.lineDistances,
  11025. vl = vertices.length,
  11026. cl = colors.length,
  11027. dl = lineDistances.length,
  11028. vertexArray = geometry.__vertexArray,
  11029. colorArray = geometry.__colorArray,
  11030. lineDistanceArray = geometry.__lineDistanceArray,
  11031. dirtyVertices = geometry.verticesNeedUpdate,
  11032. dirtyColors = geometry.colorsNeedUpdate,
  11033. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  11034. customAttributes = geometry.__webglCustomAttributesList,
  11035. i, il,
  11036. a, ca, cal, value,
  11037. customAttribute;
  11038. if ( dirtyVertices ) {
  11039. for ( v = 0; v < vl; v ++ ) {
  11040. vertex = vertices[ v ];
  11041. offset = v * 3;
  11042. vertexArray[ offset ] = vertex.x;
  11043. vertexArray[ offset + 1 ] = vertex.y;
  11044. vertexArray[ offset + 2 ] = vertex.z;
  11045. }
  11046. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11047. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11048. }
  11049. if ( dirtyColors ) {
  11050. for ( c = 0; c < cl; c ++ ) {
  11051. color = colors[ c ];
  11052. offset = c * 3;
  11053. colorArray[ offset ] = color.r;
  11054. colorArray[ offset + 1 ] = color.g;
  11055. colorArray[ offset + 2 ] = color.b;
  11056. }
  11057. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11058. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11059. }
  11060. if ( dirtyLineDistances ) {
  11061. for ( d = 0; d < dl; d ++ ) {
  11062. lineDistanceArray[ d ] = lineDistances[ d ];
  11063. }
  11064. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  11065. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  11066. }
  11067. if ( customAttributes ) {
  11068. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11069. customAttribute = customAttributes[ i ];
  11070. if ( customAttribute.needsUpdate &&
  11071. ( customAttribute.boundTo === undefined ||
  11072. customAttribute.boundTo === "vertices" ) ) {
  11073. offset = 0;
  11074. cal = customAttribute.value.length;
  11075. if ( customAttribute.size === 1 ) {
  11076. for ( ca = 0; ca < cal; ca ++ ) {
  11077. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11078. }
  11079. } else if ( customAttribute.size === 2 ) {
  11080. for ( ca = 0; ca < cal; ca ++ ) {
  11081. value = customAttribute.value[ ca ];
  11082. customAttribute.array[ offset ] = value.x;
  11083. customAttribute.array[ offset + 1 ] = value.y;
  11084. offset += 2;
  11085. }
  11086. } else if ( customAttribute.size === 3 ) {
  11087. if ( customAttribute.type === "c" ) {
  11088. for ( ca = 0; ca < cal; ca ++ ) {
  11089. value = customAttribute.value[ ca ];
  11090. customAttribute.array[ offset ] = value.r;
  11091. customAttribute.array[ offset + 1 ] = value.g;
  11092. customAttribute.array[ offset + 2 ] = value.b;
  11093. offset += 3;
  11094. }
  11095. } else {
  11096. for ( ca = 0; ca < cal; ca ++ ) {
  11097. value = customAttribute.value[ ca ];
  11098. customAttribute.array[ offset ] = value.x;
  11099. customAttribute.array[ offset + 1 ] = value.y;
  11100. customAttribute.array[ offset + 2 ] = value.z;
  11101. offset += 3;
  11102. }
  11103. }
  11104. } else if ( customAttribute.size === 4 ) {
  11105. for ( ca = 0; ca < cal; ca ++ ) {
  11106. value = customAttribute.value[ ca ];
  11107. customAttribute.array[ offset ] = value.x;
  11108. customAttribute.array[ offset + 1 ] = value.y;
  11109. customAttribute.array[ offset + 2 ] = value.z;
  11110. customAttribute.array[ offset + 3 ] = value.w;
  11111. offset += 4;
  11112. }
  11113. }
  11114. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11115. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11116. }
  11117. }
  11118. }
  11119. };
  11120. function setRibbonBuffers ( geometry, hint ) {
  11121. var v, c, n, vertex, offset, color, normal,
  11122. i, il, ca, cal, customAttribute, value,
  11123. vertices = geometry.vertices,
  11124. colors = geometry.colors,
  11125. normals = geometry.normals,
  11126. vl = vertices.length,
  11127. cl = colors.length,
  11128. nl = normals.length,
  11129. vertexArray = geometry.__vertexArray,
  11130. colorArray = geometry.__colorArray,
  11131. normalArray = geometry.__normalArray,
  11132. dirtyVertices = geometry.verticesNeedUpdate,
  11133. dirtyColors = geometry.colorsNeedUpdate,
  11134. dirtyNormals = geometry.normalsNeedUpdate,
  11135. customAttributes = geometry.__webglCustomAttributesList;
  11136. if ( dirtyVertices ) {
  11137. for ( v = 0; v < vl; v ++ ) {
  11138. vertex = vertices[ v ];
  11139. offset = v * 3;
  11140. vertexArray[ offset ] = vertex.x;
  11141. vertexArray[ offset + 1 ] = vertex.y;
  11142. vertexArray[ offset + 2 ] = vertex.z;
  11143. }
  11144. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11145. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11146. }
  11147. if ( dirtyColors ) {
  11148. for ( c = 0; c < cl; c ++ ) {
  11149. color = colors[ c ];
  11150. offset = c * 3;
  11151. colorArray[ offset ] = color.r;
  11152. colorArray[ offset + 1 ] = color.g;
  11153. colorArray[ offset + 2 ] = color.b;
  11154. }
  11155. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11156. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11157. }
  11158. if ( dirtyNormals ) {
  11159. for ( n = 0; n < nl; n ++ ) {
  11160. normal = normals[ n ];
  11161. offset = n * 3;
  11162. normalArray[ offset ] = normal.x;
  11163. normalArray[ offset + 1 ] = normal.y;
  11164. normalArray[ offset + 2 ] = normal.z;
  11165. }
  11166. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  11167. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11168. }
  11169. if ( customAttributes ) {
  11170. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11171. customAttribute = customAttributes[ i ];
  11172. if ( customAttribute.needsUpdate &&
  11173. ( customAttribute.boundTo === undefined ||
  11174. customAttribute.boundTo === "vertices" ) ) {
  11175. offset = 0;
  11176. cal = customAttribute.value.length;
  11177. if ( customAttribute.size === 1 ) {
  11178. for ( ca = 0; ca < cal; ca ++ ) {
  11179. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11180. }
  11181. } else if ( customAttribute.size === 2 ) {
  11182. for ( ca = 0; ca < cal; ca ++ ) {
  11183. value = customAttribute.value[ ca ];
  11184. customAttribute.array[ offset ] = value.x;
  11185. customAttribute.array[ offset + 1 ] = value.y;
  11186. offset += 2;
  11187. }
  11188. } else if ( customAttribute.size === 3 ) {
  11189. if ( customAttribute.type === "c" ) {
  11190. for ( ca = 0; ca < cal; ca ++ ) {
  11191. value = customAttribute.value[ ca ];
  11192. customAttribute.array[ offset ] = value.r;
  11193. customAttribute.array[ offset + 1 ] = value.g;
  11194. customAttribute.array[ offset + 2 ] = value.b;
  11195. offset += 3;
  11196. }
  11197. } else {
  11198. for ( ca = 0; ca < cal; ca ++ ) {
  11199. value = customAttribute.value[ ca ];
  11200. customAttribute.array[ offset ] = value.x;
  11201. customAttribute.array[ offset + 1 ] = value.y;
  11202. customAttribute.array[ offset + 2 ] = value.z;
  11203. offset += 3;
  11204. }
  11205. }
  11206. } else if ( customAttribute.size === 4 ) {
  11207. for ( ca = 0; ca < cal; ca ++ ) {
  11208. value = customAttribute.value[ ca ];
  11209. customAttribute.array[ offset ] = value.x;
  11210. customAttribute.array[ offset + 1 ] = value.y;
  11211. customAttribute.array[ offset + 2 ] = value.z;
  11212. customAttribute.array[ offset + 3 ] = value.w;
  11213. offset += 4;
  11214. }
  11215. }
  11216. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11217. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11218. }
  11219. }
  11220. }
  11221. };
  11222. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  11223. if ( ! geometryGroup.__inittedArrays ) {
  11224. return;
  11225. }
  11226. var normalType = bufferGuessNormalType( material ),
  11227. vertexColorType = bufferGuessVertexColorType( material ),
  11228. uvType = bufferGuessUVType( material ),
  11229. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  11230. var f, fl, fi, face,
  11231. vertexNormals, faceNormal, normal,
  11232. vertexColors, faceColor,
  11233. vertexTangents,
  11234. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  11235. c1, c2, c3, c4,
  11236. sw1, sw2, sw3, sw4,
  11237. si1, si2, si3, si4,
  11238. sa1, sa2, sa3, sa4,
  11239. sb1, sb2, sb3, sb4,
  11240. m, ml, i, il,
  11241. vn, uvi, uv2i,
  11242. vk, vkl, vka,
  11243. nka, chf, faceVertexNormals,
  11244. a,
  11245. vertexIndex = 0,
  11246. offset = 0,
  11247. offset_uv = 0,
  11248. offset_uv2 = 0,
  11249. offset_face = 0,
  11250. offset_normal = 0,
  11251. offset_tangent = 0,
  11252. offset_line = 0,
  11253. offset_color = 0,
  11254. offset_skin = 0,
  11255. offset_morphTarget = 0,
  11256. offset_custom = 0,
  11257. offset_customSrc = 0,
  11258. value,
  11259. vertexArray = geometryGroup.__vertexArray,
  11260. uvArray = geometryGroup.__uvArray,
  11261. uv2Array = geometryGroup.__uv2Array,
  11262. normalArray = geometryGroup.__normalArray,
  11263. tangentArray = geometryGroup.__tangentArray,
  11264. colorArray = geometryGroup.__colorArray,
  11265. skinIndexArray = geometryGroup.__skinIndexArray,
  11266. skinWeightArray = geometryGroup.__skinWeightArray,
  11267. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  11268. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  11269. customAttributes = geometryGroup.__webglCustomAttributesList,
  11270. customAttribute,
  11271. faceArray = geometryGroup.__faceArray,
  11272. lineArray = geometryGroup.__lineArray,
  11273. geometry = object.geometry, // this is shared for all chunks
  11274. dirtyVertices = geometry.verticesNeedUpdate,
  11275. dirtyElements = geometry.elementsNeedUpdate,
  11276. dirtyUvs = geometry.uvsNeedUpdate,
  11277. dirtyNormals = geometry.normalsNeedUpdate,
  11278. dirtyTangents = geometry.tangentsNeedUpdate,
  11279. dirtyColors = geometry.colorsNeedUpdate,
  11280. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  11281. vertices = geometry.vertices,
  11282. chunk_faces3 = geometryGroup.faces3,
  11283. chunk_faces4 = geometryGroup.faces4,
  11284. obj_faces = geometry.faces,
  11285. obj_uvs = geometry.faceVertexUvs[ 0 ],
  11286. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  11287. obj_colors = geometry.colors,
  11288. obj_skinIndices = geometry.skinIndices,
  11289. obj_skinWeights = geometry.skinWeights,
  11290. morphTargets = geometry.morphTargets,
  11291. morphNormals = geometry.morphNormals;
  11292. if ( dirtyVertices ) {
  11293. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11294. face = obj_faces[ chunk_faces3[ f ] ];
  11295. v1 = vertices[ face.a ];
  11296. v2 = vertices[ face.b ];
  11297. v3 = vertices[ face.c ];
  11298. vertexArray[ offset ] = v1.x;
  11299. vertexArray[ offset + 1 ] = v1.y;
  11300. vertexArray[ offset + 2 ] = v1.z;
  11301. vertexArray[ offset + 3 ] = v2.x;
  11302. vertexArray[ offset + 4 ] = v2.y;
  11303. vertexArray[ offset + 5 ] = v2.z;
  11304. vertexArray[ offset + 6 ] = v3.x;
  11305. vertexArray[ offset + 7 ] = v3.y;
  11306. vertexArray[ offset + 8 ] = v3.z;
  11307. offset += 9;
  11308. }
  11309. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11310. face = obj_faces[ chunk_faces4[ f ] ];
  11311. v1 = vertices[ face.a ];
  11312. v2 = vertices[ face.b ];
  11313. v3 = vertices[ face.c ];
  11314. v4 = vertices[ face.d ];
  11315. vertexArray[ offset ] = v1.x;
  11316. vertexArray[ offset + 1 ] = v1.y;
  11317. vertexArray[ offset + 2 ] = v1.z;
  11318. vertexArray[ offset + 3 ] = v2.x;
  11319. vertexArray[ offset + 4 ] = v2.y;
  11320. vertexArray[ offset + 5 ] = v2.z;
  11321. vertexArray[ offset + 6 ] = v3.x;
  11322. vertexArray[ offset + 7 ] = v3.y;
  11323. vertexArray[ offset + 8 ] = v3.z;
  11324. vertexArray[ offset + 9 ] = v4.x;
  11325. vertexArray[ offset + 10 ] = v4.y;
  11326. vertexArray[ offset + 11 ] = v4.z;
  11327. offset += 12;
  11328. }
  11329. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11330. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11331. }
  11332. if ( dirtyMorphTargets ) {
  11333. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  11334. offset_morphTarget = 0;
  11335. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11336. chf = chunk_faces3[ f ];
  11337. face = obj_faces[ chf ];
  11338. // morph positions
  11339. v1 = morphTargets[ vk ].vertices[ face.a ];
  11340. v2 = morphTargets[ vk ].vertices[ face.b ];
  11341. v3 = morphTargets[ vk ].vertices[ face.c ];
  11342. vka = morphTargetsArrays[ vk ];
  11343. vka[ offset_morphTarget ] = v1.x;
  11344. vka[ offset_morphTarget + 1 ] = v1.y;
  11345. vka[ offset_morphTarget + 2 ] = v1.z;
  11346. vka[ offset_morphTarget + 3 ] = v2.x;
  11347. vka[ offset_morphTarget + 4 ] = v2.y;
  11348. vka[ offset_morphTarget + 5 ] = v2.z;
  11349. vka[ offset_morphTarget + 6 ] = v3.x;
  11350. vka[ offset_morphTarget + 7 ] = v3.y;
  11351. vka[ offset_morphTarget + 8 ] = v3.z;
  11352. // morph normals
  11353. if ( material.morphNormals ) {
  11354. if ( needsSmoothNormals ) {
  11355. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11356. n1 = faceVertexNormals.a;
  11357. n2 = faceVertexNormals.b;
  11358. n3 = faceVertexNormals.c;
  11359. } else {
  11360. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11361. n2 = n1;
  11362. n3 = n1;
  11363. }
  11364. nka = morphNormalsArrays[ vk ];
  11365. nka[ offset_morphTarget ] = n1.x;
  11366. nka[ offset_morphTarget + 1 ] = n1.y;
  11367. nka[ offset_morphTarget + 2 ] = n1.z;
  11368. nka[ offset_morphTarget + 3 ] = n2.x;
  11369. nka[ offset_morphTarget + 4 ] = n2.y;
  11370. nka[ offset_morphTarget + 5 ] = n2.z;
  11371. nka[ offset_morphTarget + 6 ] = n3.x;
  11372. nka[ offset_morphTarget + 7 ] = n3.y;
  11373. nka[ offset_morphTarget + 8 ] = n3.z;
  11374. }
  11375. //
  11376. offset_morphTarget += 9;
  11377. }
  11378. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11379. chf = chunk_faces4[ f ];
  11380. face = obj_faces[ chf ];
  11381. // morph positions
  11382. v1 = morphTargets[ vk ].vertices[ face.a ];
  11383. v2 = morphTargets[ vk ].vertices[ face.b ];
  11384. v3 = morphTargets[ vk ].vertices[ face.c ];
  11385. v4 = morphTargets[ vk ].vertices[ face.d ];
  11386. vka = morphTargetsArrays[ vk ];
  11387. vka[ offset_morphTarget ] = v1.x;
  11388. vka[ offset_morphTarget + 1 ] = v1.y;
  11389. vka[ offset_morphTarget + 2 ] = v1.z;
  11390. vka[ offset_morphTarget + 3 ] = v2.x;
  11391. vka[ offset_morphTarget + 4 ] = v2.y;
  11392. vka[ offset_morphTarget + 5 ] = v2.z;
  11393. vka[ offset_morphTarget + 6 ] = v3.x;
  11394. vka[ offset_morphTarget + 7 ] = v3.y;
  11395. vka[ offset_morphTarget + 8 ] = v3.z;
  11396. vka[ offset_morphTarget + 9 ] = v4.x;
  11397. vka[ offset_morphTarget + 10 ] = v4.y;
  11398. vka[ offset_morphTarget + 11 ] = v4.z;
  11399. // morph normals
  11400. if ( material.morphNormals ) {
  11401. if ( needsSmoothNormals ) {
  11402. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11403. n1 = faceVertexNormals.a;
  11404. n2 = faceVertexNormals.b;
  11405. n3 = faceVertexNormals.c;
  11406. n4 = faceVertexNormals.d;
  11407. } else {
  11408. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11409. n2 = n1;
  11410. n3 = n1;
  11411. n4 = n1;
  11412. }
  11413. nka = morphNormalsArrays[ vk ];
  11414. nka[ offset_morphTarget ] = n1.x;
  11415. nka[ offset_morphTarget + 1 ] = n1.y;
  11416. nka[ offset_morphTarget + 2 ] = n1.z;
  11417. nka[ offset_morphTarget + 3 ] = n2.x;
  11418. nka[ offset_morphTarget + 4 ] = n2.y;
  11419. nka[ offset_morphTarget + 5 ] = n2.z;
  11420. nka[ offset_morphTarget + 6 ] = n3.x;
  11421. nka[ offset_morphTarget + 7 ] = n3.y;
  11422. nka[ offset_morphTarget + 8 ] = n3.z;
  11423. nka[ offset_morphTarget + 9 ] = n4.x;
  11424. nka[ offset_morphTarget + 10 ] = n4.y;
  11425. nka[ offset_morphTarget + 11 ] = n4.z;
  11426. }
  11427. //
  11428. offset_morphTarget += 12;
  11429. }
  11430. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  11431. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  11432. if ( material.morphNormals ) {
  11433. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  11434. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  11435. }
  11436. }
  11437. }
  11438. if ( obj_skinWeights.length ) {
  11439. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11440. face = obj_faces[ chunk_faces3[ f ] ];
  11441. // weights
  11442. sw1 = obj_skinWeights[ face.a ];
  11443. sw2 = obj_skinWeights[ face.b ];
  11444. sw3 = obj_skinWeights[ face.c ];
  11445. skinWeightArray[ offset_skin ] = sw1.x;
  11446. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11447. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11448. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11449. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11450. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11451. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11452. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11453. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11454. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11455. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11456. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11457. // indices
  11458. si1 = obj_skinIndices[ face.a ];
  11459. si2 = obj_skinIndices[ face.b ];
  11460. si3 = obj_skinIndices[ face.c ];
  11461. skinIndexArray[ offset_skin ] = si1.x;
  11462. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11463. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11464. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11465. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11466. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11467. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11468. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11469. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11470. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11471. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11472. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11473. offset_skin += 12;
  11474. }
  11475. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11476. face = obj_faces[ chunk_faces4[ f ] ];
  11477. // weights
  11478. sw1 = obj_skinWeights[ face.a ];
  11479. sw2 = obj_skinWeights[ face.b ];
  11480. sw3 = obj_skinWeights[ face.c ];
  11481. sw4 = obj_skinWeights[ face.d ];
  11482. skinWeightArray[ offset_skin ] = sw1.x;
  11483. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11484. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11485. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11486. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11487. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11488. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11489. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11490. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11491. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11492. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11493. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11494. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  11495. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  11496. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  11497. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  11498. // indices
  11499. si1 = obj_skinIndices[ face.a ];
  11500. si2 = obj_skinIndices[ face.b ];
  11501. si3 = obj_skinIndices[ face.c ];
  11502. si4 = obj_skinIndices[ face.d ];
  11503. skinIndexArray[ offset_skin ] = si1.x;
  11504. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11505. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11506. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11507. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11508. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11509. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11510. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11511. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11512. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11513. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11514. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11515. skinIndexArray[ offset_skin + 12 ] = si4.x;
  11516. skinIndexArray[ offset_skin + 13 ] = si4.y;
  11517. skinIndexArray[ offset_skin + 14 ] = si4.z;
  11518. skinIndexArray[ offset_skin + 15 ] = si4.w;
  11519. offset_skin += 16;
  11520. }
  11521. if ( offset_skin > 0 ) {
  11522. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11523. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  11524. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11525. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  11526. }
  11527. }
  11528. if ( dirtyColors && vertexColorType ) {
  11529. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11530. face = obj_faces[ chunk_faces3[ f ] ];
  11531. vertexColors = face.vertexColors;
  11532. faceColor = face.color;
  11533. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  11534. c1 = vertexColors[ 0 ];
  11535. c2 = vertexColors[ 1 ];
  11536. c3 = vertexColors[ 2 ];
  11537. } else {
  11538. c1 = faceColor;
  11539. c2 = faceColor;
  11540. c3 = faceColor;
  11541. }
  11542. colorArray[ offset_color ] = c1.r;
  11543. colorArray[ offset_color + 1 ] = c1.g;
  11544. colorArray[ offset_color + 2 ] = c1.b;
  11545. colorArray[ offset_color + 3 ] = c2.r;
  11546. colorArray[ offset_color + 4 ] = c2.g;
  11547. colorArray[ offset_color + 5 ] = c2.b;
  11548. colorArray[ offset_color + 6 ] = c3.r;
  11549. colorArray[ offset_color + 7 ] = c3.g;
  11550. colorArray[ offset_color + 8 ] = c3.b;
  11551. offset_color += 9;
  11552. }
  11553. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11554. face = obj_faces[ chunk_faces4[ f ] ];
  11555. vertexColors = face.vertexColors;
  11556. faceColor = face.color;
  11557. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  11558. c1 = vertexColors[ 0 ];
  11559. c2 = vertexColors[ 1 ];
  11560. c3 = vertexColors[ 2 ];
  11561. c4 = vertexColors[ 3 ];
  11562. } else {
  11563. c1 = faceColor;
  11564. c2 = faceColor;
  11565. c3 = faceColor;
  11566. c4 = faceColor;
  11567. }
  11568. colorArray[ offset_color ] = c1.r;
  11569. colorArray[ offset_color + 1 ] = c1.g;
  11570. colorArray[ offset_color + 2 ] = c1.b;
  11571. colorArray[ offset_color + 3 ] = c2.r;
  11572. colorArray[ offset_color + 4 ] = c2.g;
  11573. colorArray[ offset_color + 5 ] = c2.b;
  11574. colorArray[ offset_color + 6 ] = c3.r;
  11575. colorArray[ offset_color + 7 ] = c3.g;
  11576. colorArray[ offset_color + 8 ] = c3.b;
  11577. colorArray[ offset_color + 9 ] = c4.r;
  11578. colorArray[ offset_color + 10 ] = c4.g;
  11579. colorArray[ offset_color + 11 ] = c4.b;
  11580. offset_color += 12;
  11581. }
  11582. if ( offset_color > 0 ) {
  11583. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11584. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11585. }
  11586. }
  11587. if ( dirtyTangents && geometry.hasTangents ) {
  11588. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11589. face = obj_faces[ chunk_faces3[ f ] ];
  11590. vertexTangents = face.vertexTangents;
  11591. t1 = vertexTangents[ 0 ];
  11592. t2 = vertexTangents[ 1 ];
  11593. t3 = vertexTangents[ 2 ];
  11594. tangentArray[ offset_tangent ] = t1.x;
  11595. tangentArray[ offset_tangent + 1 ] = t1.y;
  11596. tangentArray[ offset_tangent + 2 ] = t1.z;
  11597. tangentArray[ offset_tangent + 3 ] = t1.w;
  11598. tangentArray[ offset_tangent + 4 ] = t2.x;
  11599. tangentArray[ offset_tangent + 5 ] = t2.y;
  11600. tangentArray[ offset_tangent + 6 ] = t2.z;
  11601. tangentArray[ offset_tangent + 7 ] = t2.w;
  11602. tangentArray[ offset_tangent + 8 ] = t3.x;
  11603. tangentArray[ offset_tangent + 9 ] = t3.y;
  11604. tangentArray[ offset_tangent + 10 ] = t3.z;
  11605. tangentArray[ offset_tangent + 11 ] = t3.w;
  11606. offset_tangent += 12;
  11607. }
  11608. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11609. face = obj_faces[ chunk_faces4[ f ] ];
  11610. vertexTangents = face.vertexTangents;
  11611. t1 = vertexTangents[ 0 ];
  11612. t2 = vertexTangents[ 1 ];
  11613. t3 = vertexTangents[ 2 ];
  11614. t4 = vertexTangents[ 3 ];
  11615. tangentArray[ offset_tangent ] = t1.x;
  11616. tangentArray[ offset_tangent + 1 ] = t1.y;
  11617. tangentArray[ offset_tangent + 2 ] = t1.z;
  11618. tangentArray[ offset_tangent + 3 ] = t1.w;
  11619. tangentArray[ offset_tangent + 4 ] = t2.x;
  11620. tangentArray[ offset_tangent + 5 ] = t2.y;
  11621. tangentArray[ offset_tangent + 6 ] = t2.z;
  11622. tangentArray[ offset_tangent + 7 ] = t2.w;
  11623. tangentArray[ offset_tangent + 8 ] = t3.x;
  11624. tangentArray[ offset_tangent + 9 ] = t3.y;
  11625. tangentArray[ offset_tangent + 10 ] = t3.z;
  11626. tangentArray[ offset_tangent + 11 ] = t3.w;
  11627. tangentArray[ offset_tangent + 12 ] = t4.x;
  11628. tangentArray[ offset_tangent + 13 ] = t4.y;
  11629. tangentArray[ offset_tangent + 14 ] = t4.z;
  11630. tangentArray[ offset_tangent + 15 ] = t4.w;
  11631. offset_tangent += 16;
  11632. }
  11633. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11634. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  11635. }
  11636. if ( dirtyNormals && normalType ) {
  11637. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11638. face = obj_faces[ chunk_faces3[ f ] ];
  11639. vertexNormals = face.vertexNormals;
  11640. faceNormal = face.normal;
  11641. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  11642. for ( i = 0; i < 3; i ++ ) {
  11643. vn = vertexNormals[ i ];
  11644. normalArray[ offset_normal ] = vn.x;
  11645. normalArray[ offset_normal + 1 ] = vn.y;
  11646. normalArray[ offset_normal + 2 ] = vn.z;
  11647. offset_normal += 3;
  11648. }
  11649. } else {
  11650. for ( i = 0; i < 3; i ++ ) {
  11651. normalArray[ offset_normal ] = faceNormal.x;
  11652. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11653. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11654. offset_normal += 3;
  11655. }
  11656. }
  11657. }
  11658. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11659. face = obj_faces[ chunk_faces4[ f ] ];
  11660. vertexNormals = face.vertexNormals;
  11661. faceNormal = face.normal;
  11662. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  11663. for ( i = 0; i < 4; i ++ ) {
  11664. vn = vertexNormals[ i ];
  11665. normalArray[ offset_normal ] = vn.x;
  11666. normalArray[ offset_normal + 1 ] = vn.y;
  11667. normalArray[ offset_normal + 2 ] = vn.z;
  11668. offset_normal += 3;
  11669. }
  11670. } else {
  11671. for ( i = 0; i < 4; i ++ ) {
  11672. normalArray[ offset_normal ] = faceNormal.x;
  11673. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11674. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11675. offset_normal += 3;
  11676. }
  11677. }
  11678. }
  11679. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11680. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11681. }
  11682. if ( dirtyUvs && obj_uvs && uvType ) {
  11683. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11684. fi = chunk_faces3[ f ];
  11685. uv = obj_uvs[ fi ];
  11686. if ( uv === undefined ) continue;
  11687. for ( i = 0; i < 3; i ++ ) {
  11688. uvi = uv[ i ];
  11689. uvArray[ offset_uv ] = uvi.x;
  11690. uvArray[ offset_uv + 1 ] = uvi.y;
  11691. offset_uv += 2;
  11692. }
  11693. }
  11694. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11695. fi = chunk_faces4[ f ];
  11696. uv = obj_uvs[ fi ];
  11697. if ( uv === undefined ) continue;
  11698. for ( i = 0; i < 4; i ++ ) {
  11699. uvi = uv[ i ];
  11700. uvArray[ offset_uv ] = uvi.x;
  11701. uvArray[ offset_uv + 1 ] = uvi.y;
  11702. offset_uv += 2;
  11703. }
  11704. }
  11705. if ( offset_uv > 0 ) {
  11706. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11707. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  11708. }
  11709. }
  11710. if ( dirtyUvs && obj_uvs2 && uvType ) {
  11711. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11712. fi = chunk_faces3[ f ];
  11713. uv2 = obj_uvs2[ fi ];
  11714. if ( uv2 === undefined ) continue;
  11715. for ( i = 0; i < 3; i ++ ) {
  11716. uv2i = uv2[ i ];
  11717. uv2Array[ offset_uv2 ] = uv2i.x;
  11718. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11719. offset_uv2 += 2;
  11720. }
  11721. }
  11722. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11723. fi = chunk_faces4[ f ];
  11724. uv2 = obj_uvs2[ fi ];
  11725. if ( uv2 === undefined ) continue;
  11726. for ( i = 0; i < 4; i ++ ) {
  11727. uv2i = uv2[ i ];
  11728. uv2Array[ offset_uv2 ] = uv2i.x;
  11729. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11730. offset_uv2 += 2;
  11731. }
  11732. }
  11733. if ( offset_uv2 > 0 ) {
  11734. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11735. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  11736. }
  11737. }
  11738. if ( dirtyElements ) {
  11739. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11740. faceArray[ offset_face ] = vertexIndex;
  11741. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11742. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  11743. offset_face += 3;
  11744. lineArray[ offset_line ] = vertexIndex;
  11745. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11746. lineArray[ offset_line + 2 ] = vertexIndex;
  11747. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  11748. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11749. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11750. offset_line += 6;
  11751. vertexIndex += 3;
  11752. }
  11753. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11754. faceArray[ offset_face ] = vertexIndex;
  11755. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11756. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  11757. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  11758. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  11759. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  11760. offset_face += 6;
  11761. lineArray[ offset_line ] = vertexIndex;
  11762. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11763. lineArray[ offset_line + 2 ] = vertexIndex;
  11764. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  11765. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11766. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11767. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  11768. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  11769. offset_line += 8;
  11770. vertexIndex += 4;
  11771. }
  11772. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11773. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  11774. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11775. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  11776. }
  11777. if ( customAttributes ) {
  11778. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11779. customAttribute = customAttributes[ i ];
  11780. if ( ! customAttribute.__original.needsUpdate ) continue;
  11781. offset_custom = 0;
  11782. offset_customSrc = 0;
  11783. if ( customAttribute.size === 1 ) {
  11784. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11785. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11786. face = obj_faces[ chunk_faces3[ f ] ];
  11787. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11788. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11789. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11790. offset_custom += 3;
  11791. }
  11792. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11793. face = obj_faces[ chunk_faces4[ f ] ];
  11794. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11795. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11796. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11797. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  11798. offset_custom += 4;
  11799. }
  11800. } else if ( customAttribute.boundTo === "faces" ) {
  11801. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11802. value = customAttribute.value[ chunk_faces3[ f ] ];
  11803. customAttribute.array[ offset_custom ] = value;
  11804. customAttribute.array[ offset_custom + 1 ] = value;
  11805. customAttribute.array[ offset_custom + 2 ] = value;
  11806. offset_custom += 3;
  11807. }
  11808. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11809. value = customAttribute.value[ chunk_faces4[ f ] ];
  11810. customAttribute.array[ offset_custom ] = value;
  11811. customAttribute.array[ offset_custom + 1 ] = value;
  11812. customAttribute.array[ offset_custom + 2 ] = value;
  11813. customAttribute.array[ offset_custom + 3 ] = value;
  11814. offset_custom += 4;
  11815. }
  11816. }
  11817. } else if ( customAttribute.size === 2 ) {
  11818. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11819. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11820. face = obj_faces[ chunk_faces3[ f ] ];
  11821. v1 = customAttribute.value[ face.a ];
  11822. v2 = customAttribute.value[ face.b ];
  11823. v3 = customAttribute.value[ face.c ];
  11824. customAttribute.array[ offset_custom ] = v1.x;
  11825. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11826. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11827. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11828. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11829. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11830. offset_custom += 6;
  11831. }
  11832. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11833. face = obj_faces[ chunk_faces4[ f ] ];
  11834. v1 = customAttribute.value[ face.a ];
  11835. v2 = customAttribute.value[ face.b ];
  11836. v3 = customAttribute.value[ face.c ];
  11837. v4 = customAttribute.value[ face.d ];
  11838. customAttribute.array[ offset_custom ] = v1.x;
  11839. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11840. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11841. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11842. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11843. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11844. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11845. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11846. offset_custom += 8;
  11847. }
  11848. } else if ( customAttribute.boundTo === "faces" ) {
  11849. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11850. value = customAttribute.value[ chunk_faces3[ f ] ];
  11851. v1 = value;
  11852. v2 = value;
  11853. v3 = value;
  11854. customAttribute.array[ offset_custom ] = v1.x;
  11855. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11856. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11857. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11858. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11859. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11860. offset_custom += 6;
  11861. }
  11862. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11863. value = customAttribute.value[ chunk_faces4[ f ] ];
  11864. v1 = value;
  11865. v2 = value;
  11866. v3 = value;
  11867. v4 = value;
  11868. customAttribute.array[ offset_custom ] = v1.x;
  11869. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11870. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11871. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11872. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11873. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11874. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11875. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11876. offset_custom += 8;
  11877. }
  11878. }
  11879. } else if ( customAttribute.size === 3 ) {
  11880. var pp;
  11881. if ( customAttribute.type === "c" ) {
  11882. pp = [ "r", "g", "b" ];
  11883. } else {
  11884. pp = [ "x", "y", "z" ];
  11885. }
  11886. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11887. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11888. face = obj_faces[ chunk_faces3[ f ] ];
  11889. v1 = customAttribute.value[ face.a ];
  11890. v2 = customAttribute.value[ face.b ];
  11891. v3 = customAttribute.value[ face.c ];
  11892. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11893. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11894. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11895. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11896. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11897. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11898. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11899. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11900. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11901. offset_custom += 9;
  11902. }
  11903. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11904. face = obj_faces[ chunk_faces4[ f ] ];
  11905. v1 = customAttribute.value[ face.a ];
  11906. v2 = customAttribute.value[ face.b ];
  11907. v3 = customAttribute.value[ face.c ];
  11908. v4 = customAttribute.value[ face.d ];
  11909. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11910. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11911. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11912. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11913. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11914. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11915. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11916. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11917. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11918. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11919. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11920. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11921. offset_custom += 12;
  11922. }
  11923. } else if ( customAttribute.boundTo === "faces" ) {
  11924. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11925. value = customAttribute.value[ chunk_faces3[ f ] ];
  11926. v1 = value;
  11927. v2 = value;
  11928. v3 = value;
  11929. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11930. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11931. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11932. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11933. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11934. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11935. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11936. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11937. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11938. offset_custom += 9;
  11939. }
  11940. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11941. value = customAttribute.value[ chunk_faces4[ f ] ];
  11942. v1 = value;
  11943. v2 = value;
  11944. v3 = value;
  11945. v4 = value;
  11946. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11947. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11948. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11949. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11950. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11951. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11952. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11953. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11954. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11955. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11956. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11957. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11958. offset_custom += 12;
  11959. }
  11960. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11961. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11962. value = customAttribute.value[ chunk_faces3[ f ] ];
  11963. v1 = value[ 0 ];
  11964. v2 = value[ 1 ];
  11965. v3 = value[ 2 ];
  11966. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11967. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11968. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11969. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11970. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11971. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11972. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11973. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11974. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11975. offset_custom += 9;
  11976. }
  11977. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11978. value = customAttribute.value[ chunk_faces4[ f ] ];
  11979. v1 = value[ 0 ];
  11980. v2 = value[ 1 ];
  11981. v3 = value[ 2 ];
  11982. v4 = value[ 3 ];
  11983. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11984. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11985. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11986. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11987. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11988. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11989. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11990. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11991. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11992. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11993. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11994. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11995. offset_custom += 12;
  11996. }
  11997. }
  11998. } else if ( customAttribute.size === 4 ) {
  11999. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12000. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12001. face = obj_faces[ chunk_faces3[ f ] ];
  12002. v1 = customAttribute.value[ face.a ];
  12003. v2 = customAttribute.value[ face.b ];
  12004. v3 = customAttribute.value[ face.c ];
  12005. customAttribute.array[ offset_custom ] = v1.x;
  12006. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12007. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12008. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12009. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12010. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12011. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12012. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12013. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12014. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12015. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12016. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12017. offset_custom += 12;
  12018. }
  12019. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12020. face = obj_faces[ chunk_faces4[ f ] ];
  12021. v1 = customAttribute.value[ face.a ];
  12022. v2 = customAttribute.value[ face.b ];
  12023. v3 = customAttribute.value[ face.c ];
  12024. v4 = customAttribute.value[ face.d ];
  12025. customAttribute.array[ offset_custom ] = v1.x;
  12026. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12027. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12028. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12029. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12030. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12031. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12032. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12033. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12034. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12035. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12036. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12037. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12038. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12039. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12040. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12041. offset_custom += 16;
  12042. }
  12043. } else if ( customAttribute.boundTo === "faces" ) {
  12044. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12045. value = customAttribute.value[ chunk_faces3[ f ] ];
  12046. v1 = value;
  12047. v2 = value;
  12048. v3 = value;
  12049. customAttribute.array[ offset_custom ] = v1.x;
  12050. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12051. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12052. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12053. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12054. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12055. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12056. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12057. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12058. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12059. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12060. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12061. offset_custom += 12;
  12062. }
  12063. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12064. value = customAttribute.value[ chunk_faces4[ f ] ];
  12065. v1 = value;
  12066. v2 = value;
  12067. v3 = value;
  12068. v4 = value;
  12069. customAttribute.array[ offset_custom ] = v1.x;
  12070. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12071. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12072. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12073. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12074. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12075. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12076. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12077. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12078. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12079. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12080. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12081. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12082. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12083. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12084. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12085. offset_custom += 16;
  12086. }
  12087. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12088. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12089. value = customAttribute.value[ chunk_faces3[ f ] ];
  12090. v1 = value[ 0 ];
  12091. v2 = value[ 1 ];
  12092. v3 = value[ 2 ];
  12093. customAttribute.array[ offset_custom ] = v1.x;
  12094. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12095. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12096. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12097. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12098. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12099. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12100. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12101. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12102. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12103. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12104. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12105. offset_custom += 12;
  12106. }
  12107. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12108. value = customAttribute.value[ chunk_faces4[ f ] ];
  12109. v1 = value[ 0 ];
  12110. v2 = value[ 1 ];
  12111. v3 = value[ 2 ];
  12112. v4 = value[ 3 ];
  12113. customAttribute.array[ offset_custom ] = v1.x;
  12114. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12115. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12116. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12117. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12118. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12119. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12120. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12121. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12122. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12123. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12124. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12125. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12126. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12127. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12128. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12129. offset_custom += 16;
  12130. }
  12131. }
  12132. }
  12133. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12134. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12135. }
  12136. }
  12137. if ( dispose ) {
  12138. delete geometryGroup.__inittedArrays;
  12139. delete geometryGroup.__colorArray;
  12140. delete geometryGroup.__normalArray;
  12141. delete geometryGroup.__tangentArray;
  12142. delete geometryGroup.__uvArray;
  12143. delete geometryGroup.__uv2Array;
  12144. delete geometryGroup.__faceArray;
  12145. delete geometryGroup.__vertexArray;
  12146. delete geometryGroup.__lineArray;
  12147. delete geometryGroup.__skinIndexArray;
  12148. delete geometryGroup.__skinWeightArray;
  12149. }
  12150. };
  12151. function setDirectBuffers ( geometry, hint, dispose ) {
  12152. var attributes = geometry.attributes;
  12153. var index = attributes[ "index" ];
  12154. var position = attributes[ "position" ];
  12155. var normal = attributes[ "normal" ];
  12156. var uv = attributes[ "uv" ];
  12157. var color = attributes[ "color" ];
  12158. var tangent = attributes[ "tangent" ];
  12159. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  12160. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12161. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  12162. }
  12163. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  12164. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12165. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  12166. }
  12167. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  12168. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12169. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  12170. }
  12171. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  12172. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12173. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  12174. }
  12175. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  12176. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12177. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  12178. }
  12179. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  12180. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12181. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  12182. }
  12183. if ( dispose ) {
  12184. for ( var i in geometry.attributes ) {
  12185. delete geometry.attributes[ i ].array;
  12186. }
  12187. }
  12188. };
  12189. // Buffer rendering
  12190. this.renderBufferImmediate = function ( object, program, material ) {
  12191. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12192. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12193. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12194. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12195. if ( object.hasPositions ) {
  12196. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12197. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12198. _gl.enableVertexAttribArray( program.attributes.position );
  12199. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12200. }
  12201. if ( object.hasNormals ) {
  12202. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12203. if ( material.shading === THREE.FlatShading ) {
  12204. var nx, ny, nz,
  12205. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12206. normalArray,
  12207. i, il = object.count * 3;
  12208. for( i = 0; i < il; i += 9 ) {
  12209. normalArray = object.normalArray;
  12210. nax = normalArray[ i ];
  12211. nay = normalArray[ i + 1 ];
  12212. naz = normalArray[ i + 2 ];
  12213. nbx = normalArray[ i + 3 ];
  12214. nby = normalArray[ i + 4 ];
  12215. nbz = normalArray[ i + 5 ];
  12216. ncx = normalArray[ i + 6 ];
  12217. ncy = normalArray[ i + 7 ];
  12218. ncz = normalArray[ i + 8 ];
  12219. nx = ( nax + nbx + ncx ) / 3;
  12220. ny = ( nay + nby + ncy ) / 3;
  12221. nz = ( naz + nbz + ncz ) / 3;
  12222. normalArray[ i ] = nx;
  12223. normalArray[ i + 1 ] = ny;
  12224. normalArray[ i + 2 ] = nz;
  12225. normalArray[ i + 3 ] = nx;
  12226. normalArray[ i + 4 ] = ny;
  12227. normalArray[ i + 5 ] = nz;
  12228. normalArray[ i + 6 ] = nx;
  12229. normalArray[ i + 7 ] = ny;
  12230. normalArray[ i + 8 ] = nz;
  12231. }
  12232. }
  12233. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12234. _gl.enableVertexAttribArray( program.attributes.normal );
  12235. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12236. }
  12237. if ( object.hasUvs && material.map ) {
  12238. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  12239. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12240. _gl.enableVertexAttribArray( program.attributes.uv );
  12241. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12242. }
  12243. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  12244. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  12245. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12246. _gl.enableVertexAttribArray( program.attributes.color );
  12247. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12248. }
  12249. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12250. object.count = 0;
  12251. };
  12252. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  12253. if ( material.visible === false ) return;
  12254. var program, attributes, linewidth, primitives, a, attribute;
  12255. program = setProgram( camera, lights, fog, material, object );
  12256. attributes = program.attributes;
  12257. var updateBuffers = false,
  12258. wireframeBit = material.wireframe ? 1 : 0,
  12259. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12260. if ( geometryHash !== _currentGeometryGroupHash ) {
  12261. _currentGeometryGroupHash = geometryHash;
  12262. updateBuffers = true;
  12263. }
  12264. if ( updateBuffers ) {
  12265. disableAttributes();
  12266. }
  12267. // render mesh
  12268. if ( object instanceof THREE.Mesh ) {
  12269. var index = geometry.attributes[ "index" ];
  12270. // indexed triangles
  12271. if ( index ) {
  12272. var offsets = geometry.offsets;
  12273. // if there is more than 1 chunk
  12274. // must set attribute pointers to use new offsets for each chunk
  12275. // even if geometry and materials didn't change
  12276. if ( offsets.length > 1 ) updateBuffers = true;
  12277. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12278. var startIndex = offsets[ i ].index;
  12279. if ( updateBuffers ) {
  12280. // vertices
  12281. var position = geometry.attributes[ "position" ];
  12282. var positionSize = position.itemSize;
  12283. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12284. enableAttribute( attributes.position );
  12285. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  12286. // normals
  12287. var normal = geometry.attributes[ "normal" ];
  12288. if ( attributes.normal >= 0 && normal ) {
  12289. var normalSize = normal.itemSize;
  12290. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12291. enableAttribute( attributes.normal );
  12292. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  12293. }
  12294. // uvs
  12295. var uv = geometry.attributes[ "uv" ];
  12296. if ( attributes.uv >= 0 && uv ) {
  12297. var uvSize = uv.itemSize;
  12298. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12299. enableAttribute( attributes.uv );
  12300. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  12301. }
  12302. // colors
  12303. var color = geometry.attributes[ "color" ];
  12304. if ( attributes.color >= 0 && color ) {
  12305. var colorSize = color.itemSize;
  12306. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12307. enableAttribute( attributes.color );
  12308. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  12309. }
  12310. // tangents
  12311. var tangent = geometry.attributes[ "tangent" ];
  12312. if ( attributes.tangent >= 0 && tangent ) {
  12313. var tangentSize = tangent.itemSize;
  12314. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12315. enableAttribute( attributes.tangent );
  12316. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  12317. }
  12318. // indices
  12319. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12320. }
  12321. // render indexed triangles
  12322. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  12323. _this.info.render.calls ++;
  12324. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12325. _this.info.render.faces += offsets[ i ].count / 3;
  12326. }
  12327. // non-indexed triangles
  12328. } else {
  12329. if ( updateBuffers ) {
  12330. // vertices
  12331. var position = geometry.attributes[ "position" ];
  12332. var positionSize = position.itemSize;
  12333. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12334. enableAttribute( attributes.position );
  12335. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12336. // normals
  12337. var normal = geometry.attributes[ "normal" ];
  12338. if ( attributes.normal >= 0 && normal ) {
  12339. var normalSize = normal.itemSize;
  12340. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12341. enableAttribute( attributes.normal );
  12342. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, 0 );
  12343. }
  12344. // uvs
  12345. var uv = geometry.attributes[ "uv" ];
  12346. if ( attributes.uv >= 0 && uv ) {
  12347. var uvSize = uv.itemSize;
  12348. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12349. enableAttribute( attributes.uv );
  12350. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, 0 );
  12351. }
  12352. // colors
  12353. var color = geometry.attributes[ "color" ];
  12354. if ( attributes.color >= 0 && color ) {
  12355. var colorSize = color.itemSize;
  12356. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12357. enableAttribute( attributes.color );
  12358. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12359. }
  12360. // tangents
  12361. var tangent = geometry.attributes[ "tangent" ];
  12362. if ( attributes.tangent >= 0 && tangent ) {
  12363. var tangentSize = tangent.itemSize;
  12364. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12365. enableAttribute( attributes.tangent );
  12366. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0 );
  12367. }
  12368. }
  12369. // render non-indexed triangles
  12370. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  12371. _this.info.render.calls ++;
  12372. _this.info.render.vertices += position.numItems / 3;
  12373. _this.info.render.faces += position.numItems / 3 / 3;
  12374. }
  12375. // render particles
  12376. } else if ( object instanceof THREE.ParticleSystem ) {
  12377. if ( updateBuffers ) {
  12378. // vertices
  12379. var position = geometry.attributes[ "position" ];
  12380. var positionSize = position.itemSize;
  12381. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12382. enableAttribute( attributes.position );
  12383. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12384. // colors
  12385. var color = geometry.attributes[ "color" ];
  12386. if ( attributes.color >= 0 && color ) {
  12387. var colorSize = color.itemSize;
  12388. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12389. enableAttribute( attributes.color );
  12390. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12391. }
  12392. // render particles
  12393. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  12394. _this.info.render.calls ++;
  12395. _this.info.render.points += position.numItems / 3;
  12396. }
  12397. }
  12398. };
  12399. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  12400. if ( material.visible === false ) return;
  12401. var program, attributes, linewidth, primitives, a, attribute, i, il;
  12402. program = setProgram( camera, lights, fog, material, object );
  12403. attributes = program.attributes;
  12404. var updateBuffers = false,
  12405. wireframeBit = material.wireframe ? 1 : 0,
  12406. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12407. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  12408. _currentGeometryGroupHash = geometryGroupHash;
  12409. updateBuffers = true;
  12410. }
  12411. if ( updateBuffers ) {
  12412. disableAttributes();
  12413. }
  12414. // vertices
  12415. if ( !material.morphTargets && attributes.position >= 0 ) {
  12416. if ( updateBuffers ) {
  12417. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12418. enableAttribute( attributes.position );
  12419. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12420. }
  12421. } else {
  12422. if ( object.morphTargetBase ) {
  12423. setupMorphTargets( material, geometryGroup, object );
  12424. }
  12425. }
  12426. if ( updateBuffers ) {
  12427. // custom attributes
  12428. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  12429. if ( geometryGroup.__webglCustomAttributesList ) {
  12430. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  12431. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  12432. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  12433. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  12434. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  12435. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  12436. }
  12437. }
  12438. }
  12439. // colors
  12440. if ( attributes.color >= 0 ) {
  12441. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12442. enableAttribute( attributes.color );
  12443. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12444. }
  12445. // normals
  12446. if ( attributes.normal >= 0 ) {
  12447. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12448. enableAttribute( attributes.normal );
  12449. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12450. }
  12451. // tangents
  12452. if ( attributes.tangent >= 0 ) {
  12453. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12454. enableAttribute( attributes.tangent );
  12455. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  12456. }
  12457. // uvs
  12458. if ( attributes.uv >= 0 ) {
  12459. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12460. enableAttribute( attributes.uv );
  12461. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12462. }
  12463. if ( attributes.uv2 >= 0 ) {
  12464. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12465. enableAttribute( attributes.uv2 );
  12466. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  12467. }
  12468. if ( material.skinning &&
  12469. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12470. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12471. enableAttribute( attributes.skinIndex );
  12472. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  12473. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12474. enableAttribute( attributes.skinWeight );
  12475. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  12476. }
  12477. // line distances
  12478. if ( attributes.lineDistance >= 0 ) {
  12479. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  12480. enableAttribute( attributes.lineDistance );
  12481. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  12482. }
  12483. }
  12484. // render mesh
  12485. if ( object instanceof THREE.Mesh ) {
  12486. // wireframe
  12487. if ( material.wireframe ) {
  12488. setLineWidth( material.wireframeLinewidth );
  12489. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12490. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  12491. // triangles
  12492. } else {
  12493. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12494. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  12495. }
  12496. _this.info.render.calls ++;
  12497. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  12498. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  12499. // render lines
  12500. } else if ( object instanceof THREE.Line ) {
  12501. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12502. setLineWidth( material.linewidth );
  12503. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  12504. _this.info.render.calls ++;
  12505. // render particles
  12506. } else if ( object instanceof THREE.ParticleSystem ) {
  12507. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  12508. _this.info.render.calls ++;
  12509. _this.info.render.points += geometryGroup.__webglParticleCount;
  12510. // render ribbon
  12511. } else if ( object instanceof THREE.Ribbon ) {
  12512. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  12513. _this.info.render.calls ++;
  12514. }
  12515. };
  12516. function enableAttribute( attribute ) {
  12517. if ( ! _enabledAttributes[ attribute ] ) {
  12518. _gl.enableVertexAttribArray( attribute );
  12519. _enabledAttributes[ attribute ] = true;
  12520. }
  12521. };
  12522. function disableAttributes() {
  12523. for ( var attribute in _enabledAttributes ) {
  12524. if ( _enabledAttributes[ attribute ] ) {
  12525. _gl.disableVertexAttribArray( attribute );
  12526. _enabledAttributes[ attribute ] = false;
  12527. }
  12528. }
  12529. };
  12530. function setupMorphTargets ( material, geometryGroup, object ) {
  12531. // set base
  12532. var attributes = material.program.attributes;
  12533. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  12534. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  12535. enableAttribute( attributes.position );
  12536. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12537. } else if ( attributes.position >= 0 ) {
  12538. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12539. enableAttribute( attributes.position );
  12540. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12541. }
  12542. if ( object.morphTargetForcedOrder.length ) {
  12543. // set forced order
  12544. var m = 0;
  12545. var order = object.morphTargetForcedOrder;
  12546. var influences = object.morphTargetInfluences;
  12547. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  12548. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12549. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  12550. enableAttribute( attributes[ "morphTarget" + m ] );
  12551. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12552. }
  12553. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12554. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  12555. enableAttribute( attributes[ "morphNormal" + m ] );
  12556. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12557. }
  12558. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  12559. m ++;
  12560. }
  12561. } else {
  12562. // find the most influencing
  12563. var influence, activeInfluenceIndices = [];
  12564. var influences = object.morphTargetInfluences;
  12565. var i, il = influences.length;
  12566. for ( i = 0; i < il; i ++ ) {
  12567. influence = influences[ i ];
  12568. if ( influence > 0 ) {
  12569. activeInfluenceIndices.push( [ influence, i ] );
  12570. }
  12571. }
  12572. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  12573. activeInfluenceIndices.sort( numericalSort );
  12574. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  12575. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  12576. activeInfluenceIndices.sort( numericalSort );
  12577. } else if ( activeInfluenceIndices.length === 0 ) {
  12578. activeInfluenceIndices.push( [ 0, 0 ] );
  12579. };
  12580. var influenceIndex, m = 0;
  12581. while ( m < material.numSupportedMorphTargets ) {
  12582. if ( activeInfluenceIndices[ m ] ) {
  12583. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  12584. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12585. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  12586. enableAttribute( attributes[ "morphTarget" + m ] );
  12587. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12588. }
  12589. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12590. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  12591. enableAttribute( attributes[ "morphNormal" + m ] );
  12592. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12593. }
  12594. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  12595. } else {
  12596. /*
  12597. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12598. if ( material.morphNormals ) {
  12599. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12600. }
  12601. */
  12602. object.__webglMorphTargetInfluences[ m ] = 0;
  12603. }
  12604. m ++;
  12605. }
  12606. }
  12607. // load updated influences uniform
  12608. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  12609. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  12610. }
  12611. };
  12612. // Sorting
  12613. function painterSortStable ( a, b ) {
  12614. if ( a.z !== b.z ) {
  12615. return b.z - a.z;
  12616. } else {
  12617. return b.id - a.id;
  12618. }
  12619. };
  12620. function numericalSort ( a, b ) {
  12621. return b[ 0 ] - a[ 0 ];
  12622. };
  12623. // Rendering
  12624. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12625. if ( camera instanceof THREE.Camera === false ) {
  12626. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12627. return;
  12628. }
  12629. var i, il,
  12630. webglObject, object,
  12631. renderList,
  12632. lights = scene.__lights,
  12633. fog = scene.fog;
  12634. // reset caching for this frame
  12635. _currentMaterialId = -1;
  12636. _lightsNeedUpdate = true;
  12637. // update scene graph
  12638. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  12639. // update camera matrices and frustum
  12640. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  12641. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12642. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  12643. _frustum.setFromMatrix( _projScreenMatrix );
  12644. // update WebGL objects
  12645. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  12646. // custom render plugins (pre pass)
  12647. renderPlugins( this.renderPluginsPre, scene, camera );
  12648. //
  12649. _this.info.render.calls = 0;
  12650. _this.info.render.vertices = 0;
  12651. _this.info.render.faces = 0;
  12652. _this.info.render.points = 0;
  12653. this.setRenderTarget( renderTarget );
  12654. if ( this.autoClear || forceClear ) {
  12655. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12656. }
  12657. // set matrices for regular objects (frustum culled)
  12658. renderList = scene.__webglObjects;
  12659. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12660. webglObject = renderList[ i ];
  12661. object = webglObject.object;
  12662. webglObject.render = false;
  12663. if ( object.visible ) {
  12664. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  12665. setupMatrices( object, camera );
  12666. unrollBufferMaterial( webglObject );
  12667. webglObject.render = true;
  12668. if ( this.sortObjects === true ) {
  12669. if ( object.renderDepth !== null ) {
  12670. webglObject.z = object.renderDepth;
  12671. } else {
  12672. _vector3.copy( object.matrixWorld.getPosition() );
  12673. _projScreenMatrix.multiplyVector3( _vector3 );
  12674. webglObject.z = _vector3.z;
  12675. }
  12676. webglObject.id = object.id;
  12677. }
  12678. }
  12679. }
  12680. }
  12681. if ( this.sortObjects ) {
  12682. renderList.sort( painterSortStable );
  12683. }
  12684. // set matrices for immediate objects
  12685. renderList = scene.__webglObjectsImmediate;
  12686. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12687. webglObject = renderList[ i ];
  12688. object = webglObject.object;
  12689. if ( object.visible ) {
  12690. setupMatrices( object, camera );
  12691. unrollImmediateBufferMaterial( webglObject );
  12692. }
  12693. }
  12694. if ( scene.overrideMaterial ) {
  12695. var material = scene.overrideMaterial;
  12696. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12697. this.setDepthTest( material.depthTest );
  12698. this.setDepthWrite( material.depthWrite );
  12699. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12700. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  12701. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  12702. } else {
  12703. var material = null;
  12704. // opaque pass (front-to-back order)
  12705. this.setBlending( THREE.NoBlending );
  12706. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  12707. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  12708. // transparent pass (back-to-front order)
  12709. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  12710. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  12711. }
  12712. // custom render plugins (post pass)
  12713. renderPlugins( this.renderPluginsPost, scene, camera );
  12714. // Generate mipmap if we're using any kind of mipmap filtering
  12715. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  12716. updateRenderTargetMipmap( renderTarget );
  12717. }
  12718. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12719. this.setDepthTest( true );
  12720. this.setDepthWrite( true );
  12721. // _gl.finish();
  12722. };
  12723. function renderPlugins( plugins, scene, camera ) {
  12724. if ( ! plugins.length ) return;
  12725. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  12726. // reset state for plugin (to start from clean slate)
  12727. _currentProgram = null;
  12728. _currentCamera = null;
  12729. _oldBlending = -1;
  12730. _oldDepthTest = -1;
  12731. _oldDepthWrite = -1;
  12732. _oldDoubleSided = -1;
  12733. _oldFlipSided = -1;
  12734. _currentGeometryGroupHash = -1;
  12735. _currentMaterialId = -1;
  12736. _lightsNeedUpdate = true;
  12737. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  12738. // reset state after plugin (anything could have changed)
  12739. _currentProgram = null;
  12740. _currentCamera = null;
  12741. _oldBlending = -1;
  12742. _oldDepthTest = -1;
  12743. _oldDepthWrite = -1;
  12744. _oldDoubleSided = -1;
  12745. _oldFlipSided = -1;
  12746. _currentGeometryGroupHash = -1;
  12747. _currentMaterialId = -1;
  12748. _lightsNeedUpdate = true;
  12749. }
  12750. };
  12751. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12752. var webglObject, object, buffer, material, start, end, delta;
  12753. if ( reverse ) {
  12754. start = renderList.length - 1;
  12755. end = -1;
  12756. delta = -1;
  12757. } else {
  12758. start = 0;
  12759. end = renderList.length;
  12760. delta = 1;
  12761. }
  12762. for ( var i = start; i !== end; i += delta ) {
  12763. webglObject = renderList[ i ];
  12764. if ( webglObject.render ) {
  12765. object = webglObject.object;
  12766. buffer = webglObject.buffer;
  12767. if ( overrideMaterial ) {
  12768. material = overrideMaterial;
  12769. } else {
  12770. material = webglObject[ materialType ];
  12771. if ( ! material ) continue;
  12772. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12773. _this.setDepthTest( material.depthTest );
  12774. _this.setDepthWrite( material.depthWrite );
  12775. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12776. }
  12777. _this.setMaterialFaces( material );
  12778. if ( buffer instanceof THREE.BufferGeometry ) {
  12779. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  12780. } else {
  12781. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  12782. }
  12783. }
  12784. }
  12785. };
  12786. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12787. var webglObject, object, material, program;
  12788. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  12789. webglObject = renderList[ i ];
  12790. object = webglObject.object;
  12791. if ( object.visible ) {
  12792. if ( overrideMaterial ) {
  12793. material = overrideMaterial;
  12794. } else {
  12795. material = webglObject[ materialType ];
  12796. if ( ! material ) continue;
  12797. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12798. _this.setDepthTest( material.depthTest );
  12799. _this.setDepthWrite( material.depthWrite );
  12800. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12801. }
  12802. _this.renderImmediateObject( camera, lights, fog, material, object );
  12803. }
  12804. }
  12805. };
  12806. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  12807. var program = setProgram( camera, lights, fog, material, object );
  12808. _currentGeometryGroupHash = -1;
  12809. _this.setMaterialFaces( material );
  12810. if ( object.immediateRenderCallback ) {
  12811. object.immediateRenderCallback( program, _gl, _frustum );
  12812. } else {
  12813. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  12814. }
  12815. };
  12816. function unrollImmediateBufferMaterial ( globject ) {
  12817. var object = globject.object,
  12818. material = object.material;
  12819. if ( material.transparent ) {
  12820. globject.transparent = material;
  12821. globject.opaque = null;
  12822. } else {
  12823. globject.opaque = material;
  12824. globject.transparent = null;
  12825. }
  12826. };
  12827. function unrollBufferMaterial ( globject ) {
  12828. var object = globject.object,
  12829. buffer = globject.buffer,
  12830. material, materialIndex, meshMaterial;
  12831. meshMaterial = object.material;
  12832. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  12833. materialIndex = buffer.materialIndex;
  12834. material = meshMaterial.materials[ materialIndex ];
  12835. if ( material.transparent ) {
  12836. globject.transparent = material;
  12837. globject.opaque = null;
  12838. } else {
  12839. globject.opaque = material;
  12840. globject.transparent = null;
  12841. }
  12842. } else {
  12843. material = meshMaterial;
  12844. if ( material ) {
  12845. if ( material.transparent ) {
  12846. globject.transparent = material;
  12847. globject.opaque = null;
  12848. } else {
  12849. globject.opaque = material;
  12850. globject.transparent = null;
  12851. }
  12852. }
  12853. }
  12854. };
  12855. // Geometry splitting
  12856. function sortFacesByMaterial ( geometry, material ) {
  12857. var f, fl, face, materialIndex, vertices,
  12858. groupHash, hash_map = {};
  12859. var numMorphTargets = geometry.morphTargets.length;
  12860. var numMorphNormals = geometry.morphNormals.length;
  12861. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  12862. geometry.geometryGroups = {};
  12863. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  12864. face = geometry.faces[ f ];
  12865. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  12866. if ( hash_map[ materialIndex ] === undefined ) {
  12867. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  12868. }
  12869. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12870. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12871. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12872. }
  12873. vertices = face instanceof THREE.Face3 ? 3 : 4;
  12874. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  12875. hash_map[ materialIndex ].counter += 1;
  12876. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12877. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12878. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12879. }
  12880. }
  12881. if ( face instanceof THREE.Face3 ) {
  12882. geometry.geometryGroups[ groupHash ].faces3.push( f );
  12883. } else {
  12884. geometry.geometryGroups[ groupHash ].faces4.push( f );
  12885. }
  12886. geometry.geometryGroups[ groupHash ].vertices += vertices;
  12887. }
  12888. geometry.geometryGroupsList = [];
  12889. for ( var g in geometry.geometryGroups ) {
  12890. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  12891. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  12892. }
  12893. };
  12894. // Objects refresh
  12895. this.initWebGLObjects = function ( scene ) {
  12896. if ( !scene.__webglObjects ) {
  12897. scene.__webglObjects = [];
  12898. scene.__webglObjectsImmediate = [];
  12899. scene.__webglSprites = [];
  12900. scene.__webglFlares = [];
  12901. }
  12902. while ( scene.__objectsAdded.length ) {
  12903. addObject( scene.__objectsAdded[ 0 ], scene );
  12904. scene.__objectsAdded.splice( 0, 1 );
  12905. }
  12906. while ( scene.__objectsRemoved.length ) {
  12907. removeObject( scene.__objectsRemoved[ 0 ], scene );
  12908. scene.__objectsRemoved.splice( 0, 1 );
  12909. }
  12910. // update must be called after objects adding / removal
  12911. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  12912. updateObject( scene.__webglObjects[ o ].object );
  12913. }
  12914. };
  12915. // Objects adding
  12916. function addObject ( object, scene ) {
  12917. var g, geometry, material, geometryGroup;
  12918. if ( ! object.__webglInit ) {
  12919. object.__webglInit = true;
  12920. object._modelViewMatrix = new THREE.Matrix4();
  12921. object._normalMatrix = new THREE.Matrix3();
  12922. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  12923. object.geometry.__webglInit = true;
  12924. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  12925. }
  12926. if ( object instanceof THREE.Mesh ) {
  12927. geometry = object.geometry;
  12928. material = object.material;
  12929. if ( geometry instanceof THREE.Geometry ) {
  12930. if ( geometry.geometryGroups === undefined ) {
  12931. sortFacesByMaterial( geometry, material );
  12932. }
  12933. // create separate VBOs per geometry chunk
  12934. for ( g in geometry.geometryGroups ) {
  12935. geometryGroup = geometry.geometryGroups[ g ];
  12936. // initialise VBO on the first access
  12937. if ( ! geometryGroup.__webglVertexBuffer ) {
  12938. createMeshBuffers( geometryGroup );
  12939. initMeshBuffers( geometryGroup, object );
  12940. geometry.verticesNeedUpdate = true;
  12941. geometry.morphTargetsNeedUpdate = true;
  12942. geometry.elementsNeedUpdate = true;
  12943. geometry.uvsNeedUpdate = true;
  12944. geometry.normalsNeedUpdate = true;
  12945. geometry.tangentsNeedUpdate = true;
  12946. geometry.colorsNeedUpdate = true;
  12947. }
  12948. }
  12949. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12950. initDirectBuffers( geometry );
  12951. }
  12952. } else if ( object instanceof THREE.Ribbon ) {
  12953. geometry = object.geometry;
  12954. if ( ! geometry.__webglVertexBuffer ) {
  12955. createRibbonBuffers( geometry );
  12956. initRibbonBuffers( geometry, object );
  12957. geometry.verticesNeedUpdate = true;
  12958. geometry.colorsNeedUpdate = true;
  12959. geometry.normalsNeedUpdate = true;
  12960. }
  12961. } else if ( object instanceof THREE.Line ) {
  12962. geometry = object.geometry;
  12963. if ( ! geometry.__webglVertexBuffer ) {
  12964. createLineBuffers( geometry );
  12965. initLineBuffers( geometry, object );
  12966. geometry.verticesNeedUpdate = true;
  12967. geometry.colorsNeedUpdate = true;
  12968. geometry.lineDistancesNeedUpdate = true;
  12969. }
  12970. } else if ( object instanceof THREE.ParticleSystem ) {
  12971. geometry = object.geometry;
  12972. if ( ! geometry.__webglVertexBuffer ) {
  12973. if ( geometry instanceof THREE.Geometry ) {
  12974. createParticleBuffers( geometry );
  12975. initParticleBuffers( geometry, object );
  12976. geometry.verticesNeedUpdate = true;
  12977. geometry.colorsNeedUpdate = true;
  12978. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12979. initDirectBuffers( geometry );
  12980. }
  12981. }
  12982. }
  12983. }
  12984. if ( ! object.__webglActive ) {
  12985. if ( object instanceof THREE.Mesh ) {
  12986. geometry = object.geometry;
  12987. if ( geometry instanceof THREE.BufferGeometry ) {
  12988. addBuffer( scene.__webglObjects, geometry, object );
  12989. } else {
  12990. for ( g in geometry.geometryGroups ) {
  12991. geometryGroup = geometry.geometryGroups[ g ];
  12992. addBuffer( scene.__webglObjects, geometryGroup, object );
  12993. }
  12994. }
  12995. } else if ( object instanceof THREE.Ribbon ||
  12996. object instanceof THREE.Line ||
  12997. object instanceof THREE.ParticleSystem ) {
  12998. geometry = object.geometry;
  12999. addBuffer( scene.__webglObjects, geometry, object );
  13000. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13001. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13002. } else if ( object instanceof THREE.Sprite ) {
  13003. scene.__webglSprites.push( object );
  13004. } else if ( object instanceof THREE.LensFlare ) {
  13005. scene.__webglFlares.push( object );
  13006. }
  13007. object.__webglActive = true;
  13008. }
  13009. };
  13010. function addBuffer ( objlist, buffer, object ) {
  13011. objlist.push(
  13012. {
  13013. buffer: buffer,
  13014. object: object,
  13015. opaque: null,
  13016. transparent: null
  13017. }
  13018. );
  13019. };
  13020. function addBufferImmediate ( objlist, object ) {
  13021. objlist.push(
  13022. {
  13023. object: object,
  13024. opaque: null,
  13025. transparent: null
  13026. }
  13027. );
  13028. };
  13029. // Objects updates
  13030. function updateObject ( object ) {
  13031. var geometry = object.geometry,
  13032. geometryGroup, customAttributesDirty, material;
  13033. if ( object instanceof THREE.Mesh ) {
  13034. if ( geometry instanceof THREE.BufferGeometry ) {
  13035. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  13036. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13037. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  13038. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13039. }
  13040. geometry.verticesNeedUpdate = false;
  13041. geometry.elementsNeedUpdate = false;
  13042. geometry.uvsNeedUpdate = false;
  13043. geometry.normalsNeedUpdate = false;
  13044. geometry.colorsNeedUpdate = false;
  13045. geometry.tangentsNeedUpdate = false;
  13046. } else {
  13047. // check all geometry groups
  13048. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13049. geometryGroup = geometry.geometryGroupsList[ i ];
  13050. material = getBufferMaterial( object, geometryGroup );
  13051. if ( geometry.buffersNeedUpdate ) {
  13052. initMeshBuffers( geometryGroup, object );
  13053. }
  13054. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13055. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13056. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13057. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13058. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13059. }
  13060. }
  13061. geometry.verticesNeedUpdate = false;
  13062. geometry.morphTargetsNeedUpdate = false;
  13063. geometry.elementsNeedUpdate = false;
  13064. geometry.uvsNeedUpdate = false;
  13065. geometry.normalsNeedUpdate = false;
  13066. geometry.colorsNeedUpdate = false;
  13067. geometry.tangentsNeedUpdate = false;
  13068. geometry.buffersNeedUpdate = false;
  13069. material.attributes && clearCustomAttributes( material );
  13070. }
  13071. } else if ( object instanceof THREE.Ribbon ) {
  13072. material = getBufferMaterial( object, geometry );
  13073. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13074. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  13075. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  13076. }
  13077. geometry.verticesNeedUpdate = false;
  13078. geometry.colorsNeedUpdate = false;
  13079. geometry.normalsNeedUpdate = false;
  13080. material.attributes && clearCustomAttributes( material );
  13081. } else if ( object instanceof THREE.Line ) {
  13082. material = getBufferMaterial( object, geometry );
  13083. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13084. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13085. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13086. }
  13087. geometry.verticesNeedUpdate = false;
  13088. geometry.colorsNeedUpdate = false;
  13089. geometry.lineDistancesNeedUpdate = false;
  13090. material.attributes && clearCustomAttributes( material );
  13091. } else if ( object instanceof THREE.ParticleSystem ) {
  13092. if ( geometry instanceof THREE.BufferGeometry ) {
  13093. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  13094. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13095. }
  13096. geometry.verticesNeedUpdate = false;
  13097. geometry.colorsNeedUpdate = false;
  13098. } else {
  13099. material = getBufferMaterial( object, geometry );
  13100. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13101. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13102. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13103. }
  13104. geometry.verticesNeedUpdate = false;
  13105. geometry.colorsNeedUpdate = false;
  13106. material.attributes && clearCustomAttributes( material );
  13107. }
  13108. }
  13109. };
  13110. // Objects updates - custom attributes check
  13111. function areCustomAttributesDirty ( material ) {
  13112. for ( var a in material.attributes ) {
  13113. if ( material.attributes[ a ].needsUpdate ) return true;
  13114. }
  13115. return false;
  13116. };
  13117. function clearCustomAttributes ( material ) {
  13118. for ( var a in material.attributes ) {
  13119. material.attributes[ a ].needsUpdate = false;
  13120. }
  13121. };
  13122. // Objects removal
  13123. function removeObject ( object, scene ) {
  13124. if ( object instanceof THREE.Mesh ||
  13125. object instanceof THREE.ParticleSystem ||
  13126. object instanceof THREE.Ribbon ||
  13127. object instanceof THREE.Line ) {
  13128. removeInstances( scene.__webglObjects, object );
  13129. } else if ( object instanceof THREE.Sprite ) {
  13130. removeInstancesDirect( scene.__webglSprites, object );
  13131. } else if ( object instanceof THREE.LensFlare ) {
  13132. removeInstancesDirect( scene.__webglFlares, object );
  13133. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13134. removeInstances( scene.__webglObjectsImmediate, object );
  13135. }
  13136. object.__webglActive = false;
  13137. };
  13138. function removeInstances ( objlist, object ) {
  13139. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13140. if ( objlist[ o ].object === object ) {
  13141. objlist.splice( o, 1 );
  13142. }
  13143. }
  13144. };
  13145. function removeInstancesDirect ( objlist, object ) {
  13146. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13147. if ( objlist[ o ] === object ) {
  13148. objlist.splice( o, 1 );
  13149. }
  13150. }
  13151. };
  13152. // Materials
  13153. this.initMaterial = function ( material, lights, fog, object ) {
  13154. material.addEventListener( 'dispose', onMaterialDispose );
  13155. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13156. if ( material instanceof THREE.MeshDepthMaterial ) {
  13157. shaderID = 'depth';
  13158. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13159. shaderID = 'normal';
  13160. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13161. shaderID = 'basic';
  13162. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13163. shaderID = 'lambert';
  13164. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13165. shaderID = 'phong';
  13166. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13167. shaderID = 'basic';
  13168. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13169. shaderID = 'dashed';
  13170. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13171. shaderID = 'particle_basic';
  13172. }
  13173. if ( shaderID ) {
  13174. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13175. }
  13176. // heuristics to create shader parameters according to lights in the scene
  13177. // (not to blow over maxLights budget)
  13178. maxLightCount = allocateLights( lights );
  13179. maxShadows = allocateShadows( lights );
  13180. maxBones = allocateBones( object );
  13181. parameters = {
  13182. map: !!material.map,
  13183. envMap: !!material.envMap,
  13184. lightMap: !!material.lightMap,
  13185. bumpMap: !!material.bumpMap,
  13186. normalMap: !!material.normalMap,
  13187. specularMap: !!material.specularMap,
  13188. vertexColors: material.vertexColors,
  13189. fog: fog,
  13190. useFog: material.fog,
  13191. fogExp: fog instanceof THREE.FogExp2,
  13192. sizeAttenuation: material.sizeAttenuation,
  13193. skinning: material.skinning,
  13194. maxBones: maxBones,
  13195. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13196. boneTextureWidth: object && object.boneTextureWidth,
  13197. boneTextureHeight: object && object.boneTextureHeight,
  13198. morphTargets: material.morphTargets,
  13199. morphNormals: material.morphNormals,
  13200. maxMorphTargets: this.maxMorphTargets,
  13201. maxMorphNormals: this.maxMorphNormals,
  13202. maxDirLights: maxLightCount.directional,
  13203. maxPointLights: maxLightCount.point,
  13204. maxSpotLights: maxLightCount.spot,
  13205. maxHemiLights: maxLightCount.hemi,
  13206. maxShadows: maxShadows,
  13207. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13208. shadowMapType: this.shadowMapType,
  13209. shadowMapDebug: this.shadowMapDebug,
  13210. shadowMapCascade: this.shadowMapCascade,
  13211. alphaTest: material.alphaTest,
  13212. metal: material.metal,
  13213. perPixel: material.perPixel,
  13214. wrapAround: material.wrapAround,
  13215. doubleSided: material.side === THREE.DoubleSide,
  13216. flipSided: material.side === THREE.BackSide
  13217. };
  13218. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  13219. var attributes = material.program.attributes;
  13220. if ( material.morphTargets ) {
  13221. material.numSupportedMorphTargets = 0;
  13222. var id, base = "morphTarget";
  13223. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13224. id = base + i;
  13225. if ( attributes[ id ] >= 0 ) {
  13226. material.numSupportedMorphTargets ++;
  13227. }
  13228. }
  13229. }
  13230. if ( material.morphNormals ) {
  13231. material.numSupportedMorphNormals = 0;
  13232. var id, base = "morphNormal";
  13233. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13234. id = base + i;
  13235. if ( attributes[ id ] >= 0 ) {
  13236. material.numSupportedMorphNormals ++;
  13237. }
  13238. }
  13239. }
  13240. material.uniformsList = [];
  13241. for ( u in material.uniforms ) {
  13242. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13243. }
  13244. };
  13245. function setMaterialShaders( material, shaders ) {
  13246. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  13247. material.vertexShader = shaders.vertexShader;
  13248. material.fragmentShader = shaders.fragmentShader;
  13249. };
  13250. function setProgram( camera, lights, fog, material, object ) {
  13251. _usedTextureUnits = 0;
  13252. if ( material.needsUpdate ) {
  13253. if ( material.program ) deallocateMaterial( material );
  13254. _this.initMaterial( material, lights, fog, object );
  13255. material.needsUpdate = false;
  13256. }
  13257. if ( material.morphTargets ) {
  13258. if ( ! object.__webglMorphTargetInfluences ) {
  13259. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13260. }
  13261. }
  13262. var refreshMaterial = false;
  13263. var program = material.program,
  13264. p_uniforms = program.uniforms,
  13265. m_uniforms = material.uniforms;
  13266. if ( program !== _currentProgram ) {
  13267. _gl.useProgram( program );
  13268. _currentProgram = program;
  13269. refreshMaterial = true;
  13270. }
  13271. if ( material.id !== _currentMaterialId ) {
  13272. _currentMaterialId = material.id;
  13273. refreshMaterial = true;
  13274. }
  13275. if ( refreshMaterial || camera !== _currentCamera ) {
  13276. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13277. if ( camera !== _currentCamera ) _currentCamera = camera;
  13278. }
  13279. // skinning uniforms must be set even if material didn't change
  13280. // auto-setting of texture unit for bone texture must go before other textures
  13281. // not sure why, but otherwise weird things happen
  13282. if ( material.skinning ) {
  13283. if ( _supportsBoneTextures && object.useVertexTexture ) {
  13284. if ( p_uniforms.boneTexture !== null ) {
  13285. var textureUnit = getTextureUnit();
  13286. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13287. _this.setTexture( object.boneTexture, textureUnit );
  13288. }
  13289. } else {
  13290. if ( p_uniforms.boneGlobalMatrices !== null ) {
  13291. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  13292. }
  13293. }
  13294. }
  13295. if ( refreshMaterial ) {
  13296. // refresh uniforms common to several materials
  13297. if ( fog && material.fog ) {
  13298. refreshUniformsFog( m_uniforms, fog );
  13299. }
  13300. if ( material instanceof THREE.MeshPhongMaterial ||
  13301. material instanceof THREE.MeshLambertMaterial ||
  13302. material.lights ) {
  13303. if ( _lightsNeedUpdate ) {
  13304. setupLights( program, lights );
  13305. _lightsNeedUpdate = false;
  13306. }
  13307. refreshUniformsLights( m_uniforms, _lights );
  13308. }
  13309. if ( material instanceof THREE.MeshBasicMaterial ||
  13310. material instanceof THREE.MeshLambertMaterial ||
  13311. material instanceof THREE.MeshPhongMaterial ) {
  13312. refreshUniformsCommon( m_uniforms, material );
  13313. }
  13314. // refresh single material specific uniforms
  13315. if ( material instanceof THREE.LineBasicMaterial ) {
  13316. refreshUniformsLine( m_uniforms, material );
  13317. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13318. refreshUniformsLine( m_uniforms, material );
  13319. refreshUniformsDash( m_uniforms, material );
  13320. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13321. refreshUniformsParticle( m_uniforms, material );
  13322. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13323. refreshUniformsPhong( m_uniforms, material );
  13324. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13325. refreshUniformsLambert( m_uniforms, material );
  13326. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13327. m_uniforms.mNear.value = camera.near;
  13328. m_uniforms.mFar.value = camera.far;
  13329. m_uniforms.opacity.value = material.opacity;
  13330. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13331. m_uniforms.opacity.value = material.opacity;
  13332. }
  13333. if ( object.receiveShadow && ! material._shadowPass ) {
  13334. refreshUniformsShadow( m_uniforms, lights );
  13335. }
  13336. // load common uniforms
  13337. loadUniformsGeneric( program, material.uniformsList );
  13338. // load material specific uniforms
  13339. // (shader material also gets them for the sake of genericity)
  13340. if ( material instanceof THREE.ShaderMaterial ||
  13341. material instanceof THREE.MeshPhongMaterial ||
  13342. material.envMap ) {
  13343. if ( p_uniforms.cameraPosition !== null ) {
  13344. var position = camera.matrixWorld.getPosition();
  13345. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  13346. }
  13347. }
  13348. if ( material instanceof THREE.MeshPhongMaterial ||
  13349. material instanceof THREE.MeshLambertMaterial ||
  13350. material instanceof THREE.ShaderMaterial ||
  13351. material.skinning ) {
  13352. if ( p_uniforms.viewMatrix !== null ) {
  13353. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13354. }
  13355. }
  13356. }
  13357. loadUniformsMatrices( p_uniforms, object );
  13358. if ( p_uniforms.modelMatrix !== null ) {
  13359. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13360. }
  13361. return program;
  13362. };
  13363. // Uniforms (refresh uniforms objects)
  13364. function refreshUniformsCommon ( uniforms, material ) {
  13365. uniforms.opacity.value = material.opacity;
  13366. if ( _this.gammaInput ) {
  13367. uniforms.diffuse.value.copyGammaToLinear( material.color );
  13368. } else {
  13369. uniforms.diffuse.value = material.color;
  13370. }
  13371. uniforms.map.value = material.map;
  13372. uniforms.lightMap.value = material.lightMap;
  13373. uniforms.specularMap.value = material.specularMap;
  13374. if ( material.bumpMap ) {
  13375. uniforms.bumpMap.value = material.bumpMap;
  13376. uniforms.bumpScale.value = material.bumpScale;
  13377. }
  13378. if ( material.normalMap ) {
  13379. uniforms.normalMap.value = material.normalMap;
  13380. uniforms.normalScale.value.copy( material.normalScale );
  13381. }
  13382. // uv repeat and offset setting priorities
  13383. // 1. color map
  13384. // 2. specular map
  13385. // 3. normal map
  13386. // 4. bump map
  13387. var uvScaleMap;
  13388. if ( material.map ) {
  13389. uvScaleMap = material.map;
  13390. } else if ( material.specularMap ) {
  13391. uvScaleMap = material.specularMap;
  13392. } else if ( material.normalMap ) {
  13393. uvScaleMap = material.normalMap;
  13394. } else if ( material.bumpMap ) {
  13395. uvScaleMap = material.bumpMap;
  13396. }
  13397. if ( uvScaleMap !== undefined ) {
  13398. var offset = uvScaleMap.offset;
  13399. var repeat = uvScaleMap.repeat;
  13400. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13401. }
  13402. uniforms.envMap.value = material.envMap;
  13403. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  13404. if ( _this.gammaInput ) {
  13405. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  13406. uniforms.reflectivity.value = material.reflectivity;
  13407. } else {
  13408. uniforms.reflectivity.value = material.reflectivity;
  13409. }
  13410. uniforms.refractionRatio.value = material.refractionRatio;
  13411. uniforms.combine.value = material.combine;
  13412. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  13413. };
  13414. function refreshUniformsLine ( uniforms, material ) {
  13415. uniforms.diffuse.value = material.color;
  13416. uniforms.opacity.value = material.opacity;
  13417. };
  13418. function refreshUniformsDash ( uniforms, material ) {
  13419. uniforms.dashSize.value = material.dashSize;
  13420. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13421. uniforms.scale.value = material.scale;
  13422. };
  13423. function refreshUniformsParticle ( uniforms, material ) {
  13424. uniforms.psColor.value = material.color;
  13425. uniforms.opacity.value = material.opacity;
  13426. uniforms.size.value = material.size;
  13427. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  13428. uniforms.map.value = material.map;
  13429. };
  13430. function refreshUniformsFog ( uniforms, fog ) {
  13431. uniforms.fogColor.value = fog.color;
  13432. if ( fog instanceof THREE.Fog ) {
  13433. uniforms.fogNear.value = fog.near;
  13434. uniforms.fogFar.value = fog.far;
  13435. } else if ( fog instanceof THREE.FogExp2 ) {
  13436. uniforms.fogDensity.value = fog.density;
  13437. }
  13438. };
  13439. function refreshUniformsPhong ( uniforms, material ) {
  13440. uniforms.shininess.value = material.shininess;
  13441. if ( _this.gammaInput ) {
  13442. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13443. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13444. uniforms.specular.value.copyGammaToLinear( material.specular );
  13445. } else {
  13446. uniforms.ambient.value = material.ambient;
  13447. uniforms.emissive.value = material.emissive;
  13448. uniforms.specular.value = material.specular;
  13449. }
  13450. if ( material.wrapAround ) {
  13451. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13452. }
  13453. };
  13454. function refreshUniformsLambert ( uniforms, material ) {
  13455. if ( _this.gammaInput ) {
  13456. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13457. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13458. } else {
  13459. uniforms.ambient.value = material.ambient;
  13460. uniforms.emissive.value = material.emissive;
  13461. }
  13462. if ( material.wrapAround ) {
  13463. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13464. }
  13465. };
  13466. function refreshUniformsLights ( uniforms, lights ) {
  13467. uniforms.ambientLightColor.value = lights.ambient;
  13468. uniforms.directionalLightColor.value = lights.directional.colors;
  13469. uniforms.directionalLightDirection.value = lights.directional.positions;
  13470. uniforms.pointLightColor.value = lights.point.colors;
  13471. uniforms.pointLightPosition.value = lights.point.positions;
  13472. uniforms.pointLightDistance.value = lights.point.distances;
  13473. uniforms.spotLightColor.value = lights.spot.colors;
  13474. uniforms.spotLightPosition.value = lights.spot.positions;
  13475. uniforms.spotLightDistance.value = lights.spot.distances;
  13476. uniforms.spotLightDirection.value = lights.spot.directions;
  13477. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  13478. uniforms.spotLightExponent.value = lights.spot.exponents;
  13479. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  13480. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  13481. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  13482. };
  13483. function refreshUniformsShadow ( uniforms, lights ) {
  13484. if ( uniforms.shadowMatrix ) {
  13485. var j = 0;
  13486. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  13487. var light = lights[ i ];
  13488. if ( ! light.castShadow ) continue;
  13489. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  13490. uniforms.shadowMap.value[ j ] = light.shadowMap;
  13491. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  13492. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  13493. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  13494. uniforms.shadowBias.value[ j ] = light.shadowBias;
  13495. j ++;
  13496. }
  13497. }
  13498. }
  13499. };
  13500. // Uniforms (load to GPU)
  13501. function loadUniformsMatrices ( uniforms, object ) {
  13502. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  13503. if ( uniforms.normalMatrix ) {
  13504. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  13505. }
  13506. };
  13507. function getTextureUnit() {
  13508. var textureUnit = _usedTextureUnits;
  13509. if ( textureUnit >= _maxTextures ) {
  13510. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  13511. }
  13512. _usedTextureUnits += 1;
  13513. return textureUnit;
  13514. };
  13515. function loadUniformsGeneric ( program, uniforms ) {
  13516. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  13517. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  13518. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  13519. if ( !location ) continue;
  13520. uniform = uniforms[ j ][ 0 ];
  13521. type = uniform.type;
  13522. value = uniform.value;
  13523. if ( type === "i" ) { // single integer
  13524. _gl.uniform1i( location, value );
  13525. } else if ( type === "f" ) { // single float
  13526. _gl.uniform1f( location, value );
  13527. } else if ( type === "v2" ) { // single THREE.Vector2
  13528. _gl.uniform2f( location, value.x, value.y );
  13529. } else if ( type === "v3" ) { // single THREE.Vector3
  13530. _gl.uniform3f( location, value.x, value.y, value.z );
  13531. } else if ( type === "v4" ) { // single THREE.Vector4
  13532. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  13533. } else if ( type === "c" ) { // single THREE.Color
  13534. _gl.uniform3f( location, value.r, value.g, value.b );
  13535. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  13536. _gl.uniform1iv( location, value );
  13537. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  13538. _gl.uniform3iv( location, value );
  13539. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  13540. _gl.uniform1fv( location, value );
  13541. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  13542. _gl.uniform3fv( location, value );
  13543. } else if ( type === "v2v" ) { // array of THREE.Vector2
  13544. if ( uniform._array === undefined ) {
  13545. uniform._array = new Float32Array( 2 * value.length );
  13546. }
  13547. for ( i = 0, il = value.length; i < il; i ++ ) {
  13548. offset = i * 2;
  13549. uniform._array[ offset ] = value[ i ].x;
  13550. uniform._array[ offset + 1 ] = value[ i ].y;
  13551. }
  13552. _gl.uniform2fv( location, uniform._array );
  13553. } else if ( type === "v3v" ) { // array of THREE.Vector3
  13554. if ( uniform._array === undefined ) {
  13555. uniform._array = new Float32Array( 3 * value.length );
  13556. }
  13557. for ( i = 0, il = value.length; i < il; i ++ ) {
  13558. offset = i * 3;
  13559. uniform._array[ offset ] = value[ i ].x;
  13560. uniform._array[ offset + 1 ] = value[ i ].y;
  13561. uniform._array[ offset + 2 ] = value[ i ].z;
  13562. }
  13563. _gl.uniform3fv( location, uniform._array );
  13564. } else if ( type === "v4v" ) { // array of THREE.Vector4
  13565. if ( uniform._array === undefined ) {
  13566. uniform._array = new Float32Array( 4 * value.length );
  13567. }
  13568. for ( i = 0, il = value.length; i < il; i ++ ) {
  13569. offset = i * 4;
  13570. uniform._array[ offset ] = value[ i ].x;
  13571. uniform._array[ offset + 1 ] = value[ i ].y;
  13572. uniform._array[ offset + 2 ] = value[ i ].z;
  13573. uniform._array[ offset + 3 ] = value[ i ].w;
  13574. }
  13575. _gl.uniform4fv( location, uniform._array );
  13576. } else if ( type === "m4") { // single THREE.Matrix4
  13577. if ( uniform._array === undefined ) {
  13578. uniform._array = new Float32Array( 16 );
  13579. }
  13580. value.flattenToArray( uniform._array );
  13581. _gl.uniformMatrix4fv( location, false, uniform._array );
  13582. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  13583. if ( uniform._array === undefined ) {
  13584. uniform._array = new Float32Array( 16 * value.length );
  13585. }
  13586. for ( i = 0, il = value.length; i < il; i ++ ) {
  13587. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  13588. }
  13589. _gl.uniformMatrix4fv( location, false, uniform._array );
  13590. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  13591. texture = value;
  13592. textureUnit = getTextureUnit();
  13593. _gl.uniform1i( location, textureUnit );
  13594. if ( !texture ) continue;
  13595. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  13596. setCubeTexture( texture, textureUnit );
  13597. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  13598. setCubeTextureDynamic( texture, textureUnit );
  13599. } else {
  13600. _this.setTexture( texture, textureUnit );
  13601. }
  13602. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  13603. if ( uniform._array === undefined ) {
  13604. uniform._array = [];
  13605. }
  13606. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13607. uniform._array[ i ] = getTextureUnit();
  13608. }
  13609. _gl.uniform1iv( location, uniform._array );
  13610. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13611. texture = uniform.value[ i ];
  13612. textureUnit = uniform._array[ i ];
  13613. if ( !texture ) continue;
  13614. _this.setTexture( texture, textureUnit );
  13615. }
  13616. }
  13617. }
  13618. };
  13619. function setupMatrices ( object, camera ) {
  13620. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  13621. object._normalMatrix.getInverse( object._modelViewMatrix );
  13622. object._normalMatrix.transpose();
  13623. };
  13624. //
  13625. function setColorGamma( array, offset, color, intensitySq ) {
  13626. array[ offset ] = color.r * color.r * intensitySq;
  13627. array[ offset + 1 ] = color.g * color.g * intensitySq;
  13628. array[ offset + 2 ] = color.b * color.b * intensitySq;
  13629. };
  13630. function setColorLinear( array, offset, color, intensity ) {
  13631. array[ offset ] = color.r * intensity;
  13632. array[ offset + 1 ] = color.g * intensity;
  13633. array[ offset + 2 ] = color.b * intensity;
  13634. };
  13635. function setupLights ( program, lights ) {
  13636. var l, ll, light, n,
  13637. r = 0, g = 0, b = 0,
  13638. color, skyColor, groundColor,
  13639. intensity, intensitySq,
  13640. position,
  13641. distance,
  13642. zlights = _lights,
  13643. dirColors = zlights.directional.colors,
  13644. dirPositions = zlights.directional.positions,
  13645. pointColors = zlights.point.colors,
  13646. pointPositions = zlights.point.positions,
  13647. pointDistances = zlights.point.distances,
  13648. spotColors = zlights.spot.colors,
  13649. spotPositions = zlights.spot.positions,
  13650. spotDistances = zlights.spot.distances,
  13651. spotDirections = zlights.spot.directions,
  13652. spotAnglesCos = zlights.spot.anglesCos,
  13653. spotExponents = zlights.spot.exponents,
  13654. hemiSkyColors = zlights.hemi.skyColors,
  13655. hemiGroundColors = zlights.hemi.groundColors,
  13656. hemiPositions = zlights.hemi.positions,
  13657. dirLength = 0,
  13658. pointLength = 0,
  13659. spotLength = 0,
  13660. hemiLength = 0,
  13661. dirCount = 0,
  13662. pointCount = 0,
  13663. spotCount = 0,
  13664. hemiCount = 0,
  13665. dirOffset = 0,
  13666. pointOffset = 0,
  13667. spotOffset = 0,
  13668. hemiOffset = 0;
  13669. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13670. light = lights[ l ];
  13671. if ( light.onlyShadow ) continue;
  13672. color = light.color;
  13673. intensity = light.intensity;
  13674. distance = light.distance;
  13675. if ( light instanceof THREE.AmbientLight ) {
  13676. if ( ! light.visible ) continue;
  13677. if ( _this.gammaInput ) {
  13678. r += color.r * color.r;
  13679. g += color.g * color.g;
  13680. b += color.b * color.b;
  13681. } else {
  13682. r += color.r;
  13683. g += color.g;
  13684. b += color.b;
  13685. }
  13686. } else if ( light instanceof THREE.DirectionalLight ) {
  13687. dirCount += 1;
  13688. if ( ! light.visible ) continue;
  13689. _direction.copy( light.matrixWorld.getPosition() );
  13690. _direction.subSelf( light.target.matrixWorld.getPosition() );
  13691. _direction.normalize();
  13692. // skip lights with undefined direction
  13693. // these create troubles in OpenGL (making pixel black)
  13694. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  13695. dirOffset = dirLength * 3;
  13696. dirPositions[ dirOffset ] = _direction.x;
  13697. dirPositions[ dirOffset + 1 ] = _direction.y;
  13698. dirPositions[ dirOffset + 2 ] = _direction.z;
  13699. if ( _this.gammaInput ) {
  13700. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  13701. } else {
  13702. setColorLinear( dirColors, dirOffset, color, intensity );
  13703. }
  13704. dirLength += 1;
  13705. } else if ( light instanceof THREE.PointLight ) {
  13706. pointCount += 1;
  13707. if ( ! light.visible ) continue;
  13708. pointOffset = pointLength * 3;
  13709. if ( _this.gammaInput ) {
  13710. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  13711. } else {
  13712. setColorLinear( pointColors, pointOffset, color, intensity );
  13713. }
  13714. position = light.matrixWorld.getPosition();
  13715. pointPositions[ pointOffset ] = position.x;
  13716. pointPositions[ pointOffset + 1 ] = position.y;
  13717. pointPositions[ pointOffset + 2 ] = position.z;
  13718. pointDistances[ pointLength ] = distance;
  13719. pointLength += 1;
  13720. } else if ( light instanceof THREE.SpotLight ) {
  13721. spotCount += 1;
  13722. if ( ! light.visible ) continue;
  13723. spotOffset = spotLength * 3;
  13724. if ( _this.gammaInput ) {
  13725. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  13726. } else {
  13727. setColorLinear( spotColors, spotOffset, color, intensity );
  13728. }
  13729. position = light.matrixWorld.getPosition();
  13730. spotPositions[ spotOffset ] = position.x;
  13731. spotPositions[ spotOffset + 1 ] = position.y;
  13732. spotPositions[ spotOffset + 2 ] = position.z;
  13733. spotDistances[ spotLength ] = distance;
  13734. _direction.copy( position );
  13735. _direction.subSelf( light.target.matrixWorld.getPosition() );
  13736. _direction.normalize();
  13737. spotDirections[ spotOffset ] = _direction.x;
  13738. spotDirections[ spotOffset + 1 ] = _direction.y;
  13739. spotDirections[ spotOffset + 2 ] = _direction.z;
  13740. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  13741. spotExponents[ spotLength ] = light.exponent;
  13742. spotLength += 1;
  13743. } else if ( light instanceof THREE.HemisphereLight ) {
  13744. hemiCount += 1;
  13745. if ( ! light.visible ) continue;
  13746. _direction.copy( light.matrixWorld.getPosition() );
  13747. _direction.normalize();
  13748. // skip lights with undefined direction
  13749. // these create troubles in OpenGL (making pixel black)
  13750. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  13751. hemiOffset = hemiLength * 3;
  13752. hemiPositions[ hemiOffset ] = _direction.x;
  13753. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  13754. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  13755. skyColor = light.color;
  13756. groundColor = light.groundColor;
  13757. if ( _this.gammaInput ) {
  13758. intensitySq = intensity * intensity;
  13759. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  13760. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  13761. } else {
  13762. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  13763. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  13764. }
  13765. hemiLength += 1;
  13766. }
  13767. }
  13768. // null eventual remains from removed lights
  13769. // (this is to avoid if in shader)
  13770. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  13771. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  13772. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  13773. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  13774. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  13775. zlights.directional.length = dirLength;
  13776. zlights.point.length = pointLength;
  13777. zlights.spot.length = spotLength;
  13778. zlights.hemi.length = hemiLength;
  13779. zlights.ambient[ 0 ] = r;
  13780. zlights.ambient[ 1 ] = g;
  13781. zlights.ambient[ 2 ] = b;
  13782. };
  13783. // GL state setting
  13784. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13785. if ( cullFace === THREE.CullFaceNone ) {
  13786. _gl.disable( _gl.CULL_FACE );
  13787. } else {
  13788. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  13789. _gl.frontFace( _gl.CW );
  13790. } else {
  13791. _gl.frontFace( _gl.CCW );
  13792. }
  13793. if ( cullFace === THREE.CullFaceBack ) {
  13794. _gl.cullFace( _gl.BACK );
  13795. } else if ( cullFace === THREE.CullFaceFront ) {
  13796. _gl.cullFace( _gl.FRONT );
  13797. } else {
  13798. _gl.cullFace( _gl.FRONT_AND_BACK );
  13799. }
  13800. _gl.enable( _gl.CULL_FACE );
  13801. }
  13802. };
  13803. this.setMaterialFaces = function ( material ) {
  13804. var doubleSided = material.side === THREE.DoubleSide;
  13805. var flipSided = material.side === THREE.BackSide;
  13806. if ( _oldDoubleSided !== doubleSided ) {
  13807. if ( doubleSided ) {
  13808. _gl.disable( _gl.CULL_FACE );
  13809. } else {
  13810. _gl.enable( _gl.CULL_FACE );
  13811. }
  13812. _oldDoubleSided = doubleSided;
  13813. }
  13814. if ( _oldFlipSided !== flipSided ) {
  13815. if ( flipSided ) {
  13816. _gl.frontFace( _gl.CW );
  13817. } else {
  13818. _gl.frontFace( _gl.CCW );
  13819. }
  13820. _oldFlipSided = flipSided;
  13821. }
  13822. };
  13823. this.setDepthTest = function ( depthTest ) {
  13824. if ( _oldDepthTest !== depthTest ) {
  13825. if ( depthTest ) {
  13826. _gl.enable( _gl.DEPTH_TEST );
  13827. } else {
  13828. _gl.disable( _gl.DEPTH_TEST );
  13829. }
  13830. _oldDepthTest = depthTest;
  13831. }
  13832. };
  13833. this.setDepthWrite = function ( depthWrite ) {
  13834. if ( _oldDepthWrite !== depthWrite ) {
  13835. _gl.depthMask( depthWrite );
  13836. _oldDepthWrite = depthWrite;
  13837. }
  13838. };
  13839. function setLineWidth ( width ) {
  13840. if ( width !== _oldLineWidth ) {
  13841. _gl.lineWidth( width );
  13842. _oldLineWidth = width;
  13843. }
  13844. };
  13845. function setPolygonOffset ( polygonoffset, factor, units ) {
  13846. if ( _oldPolygonOffset !== polygonoffset ) {
  13847. if ( polygonoffset ) {
  13848. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  13849. } else {
  13850. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  13851. }
  13852. _oldPolygonOffset = polygonoffset;
  13853. }
  13854. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  13855. _gl.polygonOffset( factor, units );
  13856. _oldPolygonOffsetFactor = factor;
  13857. _oldPolygonOffsetUnits = units;
  13858. }
  13859. };
  13860. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  13861. if ( blending !== _oldBlending ) {
  13862. if ( blending === THREE.NoBlending ) {
  13863. _gl.disable( _gl.BLEND );
  13864. } else if ( blending === THREE.AdditiveBlending ) {
  13865. _gl.enable( _gl.BLEND );
  13866. _gl.blendEquation( _gl.FUNC_ADD );
  13867. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  13868. } else if ( blending === THREE.SubtractiveBlending ) {
  13869. // TODO: Find blendFuncSeparate() combination
  13870. _gl.enable( _gl.BLEND );
  13871. _gl.blendEquation( _gl.FUNC_ADD );
  13872. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  13873. } else if ( blending === THREE.MultiplyBlending ) {
  13874. // TODO: Find blendFuncSeparate() combination
  13875. _gl.enable( _gl.BLEND );
  13876. _gl.blendEquation( _gl.FUNC_ADD );
  13877. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  13878. } else if ( blending === THREE.CustomBlending ) {
  13879. _gl.enable( _gl.BLEND );
  13880. } else {
  13881. _gl.enable( _gl.BLEND );
  13882. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  13883. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  13884. }
  13885. _oldBlending = blending;
  13886. }
  13887. if ( blending === THREE.CustomBlending ) {
  13888. if ( blendEquation !== _oldBlendEquation ) {
  13889. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  13890. _oldBlendEquation = blendEquation;
  13891. }
  13892. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  13893. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  13894. _oldBlendSrc = blendSrc;
  13895. _oldBlendDst = blendDst;
  13896. }
  13897. } else {
  13898. _oldBlendEquation = null;
  13899. _oldBlendSrc = null;
  13900. _oldBlendDst = null;
  13901. }
  13902. };
  13903. // Defines
  13904. function generateDefines ( defines ) {
  13905. var value, chunk, chunks = [];
  13906. for ( var d in defines ) {
  13907. value = defines[ d ];
  13908. if ( value === false ) continue;
  13909. chunk = "#define " + d + " " + value;
  13910. chunks.push( chunk );
  13911. }
  13912. return chunks.join( "\n" );
  13913. };
  13914. // Shaders
  13915. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  13916. var p, pl, d, program, code;
  13917. var chunks = [];
  13918. // Generate code
  13919. if ( shaderID ) {
  13920. chunks.push( shaderID );
  13921. } else {
  13922. chunks.push( fragmentShader );
  13923. chunks.push( vertexShader );
  13924. }
  13925. for ( d in defines ) {
  13926. chunks.push( d );
  13927. chunks.push( defines[ d ] );
  13928. }
  13929. for ( p in parameters ) {
  13930. chunks.push( p );
  13931. chunks.push( parameters[ p ] );
  13932. }
  13933. code = chunks.join();
  13934. // Check if code has been already compiled
  13935. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  13936. var programInfo = _programs[ p ];
  13937. if ( programInfo.code === code ) {
  13938. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  13939. programInfo.usedTimes ++;
  13940. return programInfo.program;
  13941. }
  13942. }
  13943. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  13944. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  13945. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  13946. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  13947. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  13948. }
  13949. //console.log( "building new program " );
  13950. //
  13951. var customDefines = generateDefines( defines );
  13952. //
  13953. program = _gl.createProgram();
  13954. var prefix_vertex = [
  13955. "precision " + _precision + " float;",
  13956. customDefines,
  13957. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  13958. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13959. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13960. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13961. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13962. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13963. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13964. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13965. "#define MAX_SHADOWS " + parameters.maxShadows,
  13966. "#define MAX_BONES " + parameters.maxBones,
  13967. parameters.map ? "#define USE_MAP" : "",
  13968. parameters.envMap ? "#define USE_ENVMAP" : "",
  13969. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13970. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13971. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13972. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13973. parameters.vertexColors ? "#define USE_COLOR" : "",
  13974. parameters.skinning ? "#define USE_SKINNING" : "",
  13975. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  13976. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  13977. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  13978. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  13979. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  13980. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13981. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13982. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13983. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13984. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13985. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  13986. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13987. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13988. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  13989. "uniform mat4 modelMatrix;",
  13990. "uniform mat4 modelViewMatrix;",
  13991. "uniform mat4 projectionMatrix;",
  13992. "uniform mat4 viewMatrix;",
  13993. "uniform mat3 normalMatrix;",
  13994. "uniform vec3 cameraPosition;",
  13995. "attribute vec3 position;",
  13996. "attribute vec3 normal;",
  13997. "attribute vec2 uv;",
  13998. "attribute vec2 uv2;",
  13999. "#ifdef USE_COLOR",
  14000. "attribute vec3 color;",
  14001. "#endif",
  14002. "#ifdef USE_MORPHTARGETS",
  14003. "attribute vec3 morphTarget0;",
  14004. "attribute vec3 morphTarget1;",
  14005. "attribute vec3 morphTarget2;",
  14006. "attribute vec3 morphTarget3;",
  14007. "#ifdef USE_MORPHNORMALS",
  14008. "attribute vec3 morphNormal0;",
  14009. "attribute vec3 morphNormal1;",
  14010. "attribute vec3 morphNormal2;",
  14011. "attribute vec3 morphNormal3;",
  14012. "#else",
  14013. "attribute vec3 morphTarget4;",
  14014. "attribute vec3 morphTarget5;",
  14015. "attribute vec3 morphTarget6;",
  14016. "attribute vec3 morphTarget7;",
  14017. "#endif",
  14018. "#endif",
  14019. "#ifdef USE_SKINNING",
  14020. "attribute vec4 skinIndex;",
  14021. "attribute vec4 skinWeight;",
  14022. "#endif",
  14023. ""
  14024. ].join("\n");
  14025. var prefix_fragment = [
  14026. "precision " + _precision + " float;",
  14027. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14028. customDefines,
  14029. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14030. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14031. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14032. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14033. "#define MAX_SHADOWS " + parameters.maxShadows,
  14034. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14035. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14036. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14037. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14038. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14039. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14040. parameters.map ? "#define USE_MAP" : "",
  14041. parameters.envMap ? "#define USE_ENVMAP" : "",
  14042. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14043. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14044. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14045. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14046. parameters.vertexColors ? "#define USE_COLOR" : "",
  14047. parameters.metal ? "#define METAL" : "",
  14048. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14049. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14050. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14051. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14052. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14053. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14054. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14055. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14056. "uniform mat4 viewMatrix;",
  14057. "uniform vec3 cameraPosition;",
  14058. ""
  14059. ].join("\n");
  14060. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14061. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14062. _gl.attachShader( program, glVertexShader );
  14063. _gl.attachShader( program, glFragmentShader );
  14064. _gl.linkProgram( program );
  14065. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14066. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14067. }
  14068. // clean up
  14069. _gl.deleteShader( glFragmentShader );
  14070. _gl.deleteShader( glVertexShader );
  14071. //console.log( prefix_fragment + fragmentShader );
  14072. //console.log( prefix_vertex + vertexShader );
  14073. program.uniforms = {};
  14074. program.attributes = {};
  14075. var identifiers, u, a, i;
  14076. // cache uniform locations
  14077. identifiers = [
  14078. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14079. 'morphTargetInfluences'
  14080. ];
  14081. if ( parameters.useVertexTexture ) {
  14082. identifiers.push( 'boneTexture' );
  14083. } else {
  14084. identifiers.push( 'boneGlobalMatrices' );
  14085. }
  14086. for ( u in uniforms ) {
  14087. identifiers.push( u );
  14088. }
  14089. cacheUniformLocations( program, identifiers );
  14090. // cache attributes locations
  14091. identifiers = [
  14092. "position", "normal", "uv", "uv2", "tangent", "color",
  14093. "skinIndex", "skinWeight", "lineDistance"
  14094. ];
  14095. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14096. identifiers.push( "morphTarget" + i );
  14097. }
  14098. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14099. identifiers.push( "morphNormal" + i );
  14100. }
  14101. for ( a in attributes ) {
  14102. identifiers.push( a );
  14103. }
  14104. cacheAttributeLocations( program, identifiers );
  14105. program.id = _programs_counter ++;
  14106. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14107. _this.info.memory.programs = _programs.length;
  14108. return program;
  14109. };
  14110. // Shader parameters cache
  14111. function cacheUniformLocations ( program, identifiers ) {
  14112. var i, l, id;
  14113. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14114. id = identifiers[ i ];
  14115. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14116. }
  14117. };
  14118. function cacheAttributeLocations ( program, identifiers ) {
  14119. var i, l, id;
  14120. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14121. id = identifiers[ i ];
  14122. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14123. }
  14124. };
  14125. function addLineNumbers ( string ) {
  14126. var chunks = string.split( "\n" );
  14127. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14128. // Chrome reports shader errors on lines
  14129. // starting counting from 1
  14130. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14131. }
  14132. return chunks.join( "\n" );
  14133. };
  14134. function getShader ( type, string ) {
  14135. var shader;
  14136. if ( type === "fragment" ) {
  14137. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14138. } else if ( type === "vertex" ) {
  14139. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14140. }
  14141. _gl.shaderSource( shader, string );
  14142. _gl.compileShader( shader );
  14143. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14144. console.error( _gl.getShaderInfoLog( shader ) );
  14145. console.error( addLineNumbers( string ) );
  14146. return null;
  14147. }
  14148. return shader;
  14149. };
  14150. // Textures
  14151. function isPowerOfTwo ( value ) {
  14152. return ( value & ( value - 1 ) ) === 0;
  14153. };
  14154. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14155. if ( isImagePowerOfTwo ) {
  14156. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14157. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14158. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14159. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14160. } else {
  14161. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14162. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14163. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14164. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14165. }
  14166. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14167. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14168. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14169. texture.__oldAnisotropy = texture.anisotropy;
  14170. }
  14171. }
  14172. };
  14173. this.setTexture = function ( texture, slot ) {
  14174. if ( texture.needsUpdate ) {
  14175. if ( ! texture.__webglInit ) {
  14176. texture.__webglInit = true;
  14177. texture.addEventListener( 'dispose', onTextureDispose );
  14178. texture.__webglTexture = _gl.createTexture();
  14179. _this.info.memory.textures ++;
  14180. }
  14181. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14182. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14183. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14184. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14185. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14186. var image = texture.image,
  14187. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14188. glFormat = paramThreeToGL( texture.format ),
  14189. glType = paramThreeToGL( texture.type );
  14190. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14191. var mipmap, mipmaps = texture.mipmaps;
  14192. if ( texture instanceof THREE.DataTexture ) {
  14193. // use manually created mipmaps if available
  14194. // if there are no manual mipmaps
  14195. // set 0 level mipmap and then use GL to generate other mipmap levels
  14196. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14197. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14198. mipmap = mipmaps[ i ];
  14199. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14200. }
  14201. texture.generateMipmaps = false;
  14202. } else {
  14203. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14204. }
  14205. } else if ( texture instanceof THREE.CompressedTexture ) {
  14206. // compressed textures can only use manually created mipmaps
  14207. // WebGL can't generate mipmaps for DDS textures
  14208. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14209. mipmap = mipmaps[ i ];
  14210. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14211. }
  14212. } else { // regular Texture (image, video, canvas)
  14213. // use manually created mipmaps if available
  14214. // if there are no manual mipmaps
  14215. // set 0 level mipmap and then use GL to generate other mipmap levels
  14216. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14217. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14218. mipmap = mipmaps[ i ];
  14219. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14220. }
  14221. texture.generateMipmaps = false;
  14222. } else {
  14223. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14224. }
  14225. }
  14226. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14227. texture.needsUpdate = false;
  14228. if ( texture.onUpdate ) texture.onUpdate();
  14229. } else {
  14230. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14231. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14232. }
  14233. };
  14234. function clampToMaxSize ( image, maxSize ) {
  14235. if ( image.width <= maxSize && image.height <= maxSize ) {
  14236. return image;
  14237. }
  14238. // Warning: Scaling through the canvas will only work with images that use
  14239. // premultiplied alpha.
  14240. var maxDimension = Math.max( image.width, image.height );
  14241. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  14242. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  14243. var canvas = document.createElement( 'canvas' );
  14244. canvas.width = newWidth;
  14245. canvas.height = newHeight;
  14246. var ctx = canvas.getContext( "2d" );
  14247. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  14248. return canvas;
  14249. }
  14250. function setCubeTexture ( texture, slot ) {
  14251. if ( texture.image.length === 6 ) {
  14252. if ( texture.needsUpdate ) {
  14253. if ( ! texture.image.__webglTextureCube ) {
  14254. texture.image.__webglTextureCube = _gl.createTexture();
  14255. _this.info.memory.textures ++;
  14256. }
  14257. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14258. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14259. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14260. var isCompressed = texture instanceof THREE.CompressedTexture;
  14261. var cubeImage = [];
  14262. for ( var i = 0; i < 6; i ++ ) {
  14263. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  14264. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14265. } else {
  14266. cubeImage[ i ] = texture.image[ i ];
  14267. }
  14268. }
  14269. var image = cubeImage[ 0 ],
  14270. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14271. glFormat = paramThreeToGL( texture.format ),
  14272. glType = paramThreeToGL( texture.type );
  14273. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14274. for ( var i = 0; i < 6; i ++ ) {
  14275. if ( isCompressed ) {
  14276. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14277. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14278. mipmap = mipmaps[ j ];
  14279. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14280. }
  14281. } else {
  14282. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14283. }
  14284. }
  14285. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  14286. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14287. }
  14288. texture.needsUpdate = false;
  14289. if ( texture.onUpdate ) texture.onUpdate();
  14290. } else {
  14291. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14292. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14293. }
  14294. }
  14295. };
  14296. function setCubeTextureDynamic ( texture, slot ) {
  14297. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14298. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  14299. };
  14300. // Render targets
  14301. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  14302. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14303. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  14304. };
  14305. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  14306. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14307. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14308. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14309. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14310. /* For some reason this is not working. Defaulting to RGBA4.
  14311. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14312. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14313. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14314. */
  14315. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14316. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14317. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14318. } else {
  14319. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14320. }
  14321. };
  14322. this.setRenderTarget = function ( renderTarget ) {
  14323. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14324. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  14325. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14326. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14327. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14328. renderTarget.__webglTexture = _gl.createTexture();
  14329. _this.info.memory.textures ++;
  14330. // Setup texture, create render and frame buffers
  14331. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  14332. glFormat = paramThreeToGL( renderTarget.format ),
  14333. glType = paramThreeToGL( renderTarget.type );
  14334. if ( isCube ) {
  14335. renderTarget.__webglFramebuffer = [];
  14336. renderTarget.__webglRenderbuffer = [];
  14337. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14338. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  14339. for ( var i = 0; i < 6; i ++ ) {
  14340. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14341. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14342. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14343. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14344. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  14345. }
  14346. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14347. } else {
  14348. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  14349. if ( renderTarget.shareDepthFrom ) {
  14350. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  14351. } else {
  14352. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  14353. }
  14354. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14355. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  14356. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14357. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14358. if ( renderTarget.shareDepthFrom ) {
  14359. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14360. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14361. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14362. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14363. }
  14364. } else {
  14365. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  14366. }
  14367. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14368. }
  14369. // Release everything
  14370. if ( isCube ) {
  14371. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14372. } else {
  14373. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14374. }
  14375. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14376. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14377. }
  14378. var framebuffer, width, height, vx, vy;
  14379. if ( renderTarget ) {
  14380. if ( isCube ) {
  14381. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  14382. } else {
  14383. framebuffer = renderTarget.__webglFramebuffer;
  14384. }
  14385. width = renderTarget.width;
  14386. height = renderTarget.height;
  14387. vx = 0;
  14388. vy = 0;
  14389. } else {
  14390. framebuffer = null;
  14391. width = _viewportWidth;
  14392. height = _viewportHeight;
  14393. vx = _viewportX;
  14394. vy = _viewportY;
  14395. }
  14396. if ( framebuffer !== _currentFramebuffer ) {
  14397. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14398. _gl.viewport( vx, vy, width, height );
  14399. _currentFramebuffer = framebuffer;
  14400. }
  14401. _currentWidth = width;
  14402. _currentHeight = height;
  14403. };
  14404. function updateRenderTargetMipmap ( renderTarget ) {
  14405. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14406. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14407. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14408. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14409. } else {
  14410. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14411. _gl.generateMipmap( _gl.TEXTURE_2D );
  14412. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14413. }
  14414. };
  14415. // Fallback filters for non-power-of-2 textures
  14416. function filterFallback ( f ) {
  14417. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  14418. return _gl.NEAREST;
  14419. }
  14420. return _gl.LINEAR;
  14421. };
  14422. // Map three.js constants to WebGL constants
  14423. function paramThreeToGL ( p ) {
  14424. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  14425. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  14426. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  14427. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  14428. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  14429. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  14430. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  14431. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  14432. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  14433. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  14434. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  14435. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  14436. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  14437. if ( p === THREE.ByteType ) return _gl.BYTE;
  14438. if ( p === THREE.ShortType ) return _gl.SHORT;
  14439. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  14440. if ( p === THREE.IntType ) return _gl.INT;
  14441. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  14442. if ( p === THREE.FloatType ) return _gl.FLOAT;
  14443. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  14444. if ( p === THREE.RGBFormat ) return _gl.RGB;
  14445. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  14446. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  14447. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  14448. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  14449. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  14450. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  14451. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  14452. if ( p === THREE.OneFactor ) return _gl.ONE;
  14453. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  14454. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  14455. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  14456. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  14457. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  14458. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  14459. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  14460. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  14461. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  14462. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  14463. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14464. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14465. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14466. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14467. }
  14468. return 0;
  14469. };
  14470. // Allocations
  14471. function allocateBones ( object ) {
  14472. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  14473. return 1024;
  14474. } else {
  14475. // default for when object is not specified
  14476. // ( for example when prebuilding shader
  14477. // to be used with multiple objects )
  14478. //
  14479. // - leave some extra space for other uniforms
  14480. // - limit here is ANGLE's 254 max uniform vectors
  14481. // (up to 54 should be safe)
  14482. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  14483. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14484. var maxBones = nVertexMatrices;
  14485. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  14486. maxBones = Math.min( object.bones.length, maxBones );
  14487. if ( maxBones < object.bones.length ) {
  14488. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  14489. }
  14490. }
  14491. return maxBones;
  14492. }
  14493. };
  14494. function allocateLights ( lights ) {
  14495. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  14496. dirLights = pointLights = spotLights = hemiLights = 0;
  14497. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14498. light = lights[ l ];
  14499. if ( light.onlyShadow ) continue;
  14500. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  14501. if ( light instanceof THREE.PointLight ) pointLights ++;
  14502. if ( light instanceof THREE.SpotLight ) spotLights ++;
  14503. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  14504. }
  14505. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  14506. };
  14507. function allocateShadows ( lights ) {
  14508. var l, ll, light, maxShadows = 0;
  14509. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  14510. light = lights[ l ];
  14511. if ( ! light.castShadow ) continue;
  14512. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  14513. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  14514. }
  14515. return maxShadows;
  14516. };
  14517. // Initialization
  14518. function initGL () {
  14519. try {
  14520. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  14521. throw 'Error creating WebGL context.';
  14522. }
  14523. } catch ( error ) {
  14524. console.error( error );
  14525. }
  14526. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  14527. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  14528. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  14529. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  14530. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  14531. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  14532. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  14533. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  14534. if ( ! _glExtensionTextureFloat ) {
  14535. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  14536. }
  14537. if ( ! _glExtensionStandardDerivatives ) {
  14538. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  14539. }
  14540. if ( ! _glExtensionTextureFilterAnisotropic ) {
  14541. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  14542. }
  14543. if ( ! _glExtensionCompressedTextureS3TC ) {
  14544. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  14545. }
  14546. };
  14547. function setDefaultGLState () {
  14548. _gl.clearColor( 0, 0, 0, 1 );
  14549. _gl.clearDepth( 1 );
  14550. _gl.clearStencil( 0 );
  14551. _gl.enable( _gl.DEPTH_TEST );
  14552. _gl.depthFunc( _gl.LEQUAL );
  14553. _gl.frontFace( _gl.CCW );
  14554. _gl.cullFace( _gl.BACK );
  14555. _gl.enable( _gl.CULL_FACE );
  14556. _gl.enable( _gl.BLEND );
  14557. _gl.blendEquation( _gl.FUNC_ADD );
  14558. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  14559. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14560. };
  14561. // default plugins (order is important)
  14562. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  14563. this.addPrePlugin( this.shadowMapPlugin );
  14564. this.addPostPlugin( new THREE.SpritePlugin() );
  14565. this.addPostPlugin( new THREE.LensFlarePlugin() );
  14566. };
  14567. /**
  14568. * @author szimek / https://github.com/szimek/
  14569. * @author alteredq / http://alteredqualia.com/
  14570. */
  14571. THREE.WebGLRenderTarget = function ( width, height, options ) {
  14572. THREE.EventDispatcher.call( this );
  14573. this.width = width;
  14574. this.height = height;
  14575. options = options || {};
  14576. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  14577. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  14578. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  14579. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  14580. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  14581. this.offset = new THREE.Vector2( 0, 0 );
  14582. this.repeat = new THREE.Vector2( 1, 1 );
  14583. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  14584. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  14585. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  14586. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  14587. this.generateMipmaps = true;
  14588. this.shareDepthFrom = null;
  14589. };
  14590. THREE.WebGLRenderTarget.prototype.clone = function() {
  14591. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  14592. tmp.wrapS = this.wrapS;
  14593. tmp.wrapT = this.wrapT;
  14594. tmp.magFilter = this.magFilter;
  14595. tmp.minFilter = this.minFilter;
  14596. tmp.anisotropy = this.anisotropy;
  14597. tmp.offset.copy( this.offset );
  14598. tmp.repeat.copy( this.repeat );
  14599. tmp.format = this.format;
  14600. tmp.type = this.type;
  14601. tmp.depthBuffer = this.depthBuffer;
  14602. tmp.stencilBuffer = this.stencilBuffer;
  14603. tmp.generateMipmaps = this.generateMipmaps;
  14604. tmp.shareDepthFrom = this.shareDepthFrom;
  14605. return tmp;
  14606. };
  14607. THREE.WebGLRenderTarget.prototype.dispose = function () {
  14608. this.dispatchEvent( { type: 'dispose' } );
  14609. };
  14610. /**
  14611. * @author alteredq / http://alteredqualia.com
  14612. */
  14613. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  14614. THREE.WebGLRenderTarget.call( this, width, height, options );
  14615. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  14616. };
  14617. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  14618. /**
  14619. * @author mrdoob / http://mrdoob.com/
  14620. */
  14621. THREE.RenderableVertex = function () {
  14622. this.positionWorld = new THREE.Vector3();
  14623. this.positionScreen = new THREE.Vector4();
  14624. this.visible = true;
  14625. };
  14626. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  14627. this.positionWorld.copy( vertex.positionWorld );
  14628. this.positionScreen.copy( vertex.positionScreen );
  14629. }
  14630. /**
  14631. * @author mrdoob / http://mrdoob.com/
  14632. */
  14633. THREE.RenderableFace3 = function () {
  14634. this.v1 = new THREE.RenderableVertex();
  14635. this.v2 = new THREE.RenderableVertex();
  14636. this.v3 = new THREE.RenderableVertex();
  14637. this.centroidWorld = new THREE.Vector3();
  14638. this.centroidScreen = new THREE.Vector3();
  14639. this.normalWorld = new THREE.Vector3();
  14640. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14641. this.vertexNormalsLength = 0;
  14642. this.color = null;
  14643. this.material = null;
  14644. this.uvs = [[]];
  14645. this.z = null;
  14646. };
  14647. /**
  14648. * @author mrdoob / http://mrdoob.com/
  14649. */
  14650. THREE.RenderableFace4 = function () {
  14651. this.v1 = new THREE.RenderableVertex();
  14652. this.v2 = new THREE.RenderableVertex();
  14653. this.v3 = new THREE.RenderableVertex();
  14654. this.v4 = new THREE.RenderableVertex();
  14655. this.centroidWorld = new THREE.Vector3();
  14656. this.centroidScreen = new THREE.Vector3();
  14657. this.normalWorld = new THREE.Vector3();
  14658. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14659. this.vertexNormalsLength = 0;
  14660. this.color = null;
  14661. this.material = null;
  14662. this.uvs = [[]];
  14663. this.z = null;
  14664. };
  14665. /**
  14666. * @author mrdoob / http://mrdoob.com/
  14667. */
  14668. THREE.RenderableObject = function () {
  14669. this.object = null;
  14670. this.z = null;
  14671. };
  14672. /**
  14673. * @author mrdoob / http://mrdoob.com/
  14674. */
  14675. THREE.RenderableParticle = function () {
  14676. this.object = null;
  14677. this.x = null;
  14678. this.y = null;
  14679. this.z = null;
  14680. this.rotation = null;
  14681. this.scale = new THREE.Vector2();
  14682. this.material = null;
  14683. };
  14684. /**
  14685. * @author mrdoob / http://mrdoob.com/
  14686. */
  14687. THREE.RenderableLine = function () {
  14688. this.z = null;
  14689. this.v1 = new THREE.RenderableVertex();
  14690. this.v2 = new THREE.RenderableVertex();
  14691. this.material = null;
  14692. };
  14693. /**
  14694. * @author alteredq / http://alteredqualia.com/
  14695. */
  14696. THREE.ColorUtils = {
  14697. adjustHSV : function ( color, h, s, v ) {
  14698. var hsv = THREE.ColorUtils.__hsv;
  14699. color.getHSV( hsv );
  14700. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  14701. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  14702. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  14703. color.setHSV( hsv.h, hsv.s, hsv.v );
  14704. }
  14705. };
  14706. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  14707. * @author mrdoob / http://mrdoob.com/
  14708. * @author alteredq / http://alteredqualia.com/
  14709. */
  14710. THREE.GeometryUtils = {
  14711. // Merge two geometries or geometry and geometry from object (using object's transform)
  14712. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  14713. var matrix, matrixRotation,
  14714. vertexOffset = geometry1.vertices.length,
  14715. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  14716. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  14717. vertices1 = geometry1.vertices,
  14718. vertices2 = geometry2.vertices,
  14719. faces1 = geometry1.faces,
  14720. faces2 = geometry2.faces,
  14721. uvs1 = geometry1.faceVertexUvs[ 0 ],
  14722. uvs2 = geometry2.faceVertexUvs[ 0 ];
  14723. if ( object2 instanceof THREE.Mesh ) {
  14724. object2.matrixAutoUpdate && object2.updateMatrix();
  14725. matrix = object2.matrix;
  14726. matrixRotation = new THREE.Matrix4();
  14727. matrixRotation.extractRotation( matrix, object2.scale );
  14728. }
  14729. // vertices
  14730. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  14731. var vertex = vertices2[ i ];
  14732. var vertexCopy = vertex.clone();
  14733. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  14734. vertices1.push( vertexCopy );
  14735. }
  14736. // faces
  14737. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  14738. var face = faces2[ i ], faceCopy, normal, color,
  14739. faceVertexNormals = face.vertexNormals,
  14740. faceVertexColors = face.vertexColors;
  14741. if ( face instanceof THREE.Face3 ) {
  14742. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  14743. } else if ( face instanceof THREE.Face4 ) {
  14744. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  14745. }
  14746. faceCopy.normal.copy( face.normal );
  14747. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  14748. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  14749. normal = faceVertexNormals[ j ].clone();
  14750. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  14751. faceCopy.vertexNormals.push( normal );
  14752. }
  14753. faceCopy.color.copy( face.color );
  14754. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  14755. color = faceVertexColors[ j ];
  14756. faceCopy.vertexColors.push( color.clone() );
  14757. }
  14758. faceCopy.materialIndex = face.materialIndex;
  14759. faceCopy.centroid.copy( face.centroid );
  14760. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  14761. faces1.push( faceCopy );
  14762. }
  14763. // uvs
  14764. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  14765. var uv = uvs2[ i ], uvCopy = [];
  14766. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  14767. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  14768. }
  14769. uvs1.push( uvCopy );
  14770. }
  14771. },
  14772. removeMaterials: function ( geometry, materialIndexArray ) {
  14773. var materialIndexMap = {};
  14774. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  14775. materialIndexMap[ materialIndexArray[i] ] = true;
  14776. }
  14777. var face, newFaces = [];
  14778. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14779. face = geometry.faces[ i ];
  14780. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  14781. }
  14782. geometry.faces = newFaces;
  14783. },
  14784. // Get random point in triangle (via barycentric coordinates)
  14785. // (uniform distribution)
  14786. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  14787. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  14788. var a, b, c,
  14789. point = new THREE.Vector3(),
  14790. tmp = THREE.GeometryUtils.__v1;
  14791. a = THREE.GeometryUtils.random();
  14792. b = THREE.GeometryUtils.random();
  14793. if ( ( a + b ) > 1 ) {
  14794. a = 1 - a;
  14795. b = 1 - b;
  14796. }
  14797. c = 1 - a - b;
  14798. point.copy( vectorA );
  14799. point.multiplyScalar( a );
  14800. tmp.copy( vectorB );
  14801. tmp.multiplyScalar( b );
  14802. point.addSelf( tmp );
  14803. tmp.copy( vectorC );
  14804. tmp.multiplyScalar( c );
  14805. point.addSelf( tmp );
  14806. return point;
  14807. },
  14808. // Get random point in face (triangle / quad)
  14809. // (uniform distribution)
  14810. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  14811. var vA, vB, vC, vD;
  14812. if ( face instanceof THREE.Face3 ) {
  14813. vA = geometry.vertices[ face.a ];
  14814. vB = geometry.vertices[ face.b ];
  14815. vC = geometry.vertices[ face.c ];
  14816. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  14817. } else if ( face instanceof THREE.Face4 ) {
  14818. vA = geometry.vertices[ face.a ];
  14819. vB = geometry.vertices[ face.b ];
  14820. vC = geometry.vertices[ face.c ];
  14821. vD = geometry.vertices[ face.d ];
  14822. var area1, area2;
  14823. if ( useCachedAreas ) {
  14824. if ( face._area1 && face._area2 ) {
  14825. area1 = face._area1;
  14826. area2 = face._area2;
  14827. } else {
  14828. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14829. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14830. face._area1 = area1;
  14831. face._area2 = area2;
  14832. }
  14833. } else {
  14834. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  14835. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14836. }
  14837. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  14838. if ( r < area1 ) {
  14839. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  14840. } else {
  14841. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  14842. }
  14843. }
  14844. },
  14845. // Get uniformly distributed random points in mesh
  14846. // - create array with cumulative sums of face areas
  14847. // - pick random number from 0 to total area
  14848. // - find corresponding place in area array by binary search
  14849. // - get random point in face
  14850. randomPointsInGeometry: function ( geometry, n ) {
  14851. var face, i,
  14852. faces = geometry.faces,
  14853. vertices = geometry.vertices,
  14854. il = faces.length,
  14855. totalArea = 0,
  14856. cumulativeAreas = [],
  14857. vA, vB, vC, vD;
  14858. // precompute face areas
  14859. for ( i = 0; i < il; i ++ ) {
  14860. face = faces[ i ];
  14861. if ( face instanceof THREE.Face3 ) {
  14862. vA = vertices[ face.a ];
  14863. vB = vertices[ face.b ];
  14864. vC = vertices[ face.c ];
  14865. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  14866. } else if ( face instanceof THREE.Face4 ) {
  14867. vA = vertices[ face.a ];
  14868. vB = vertices[ face.b ];
  14869. vC = vertices[ face.c ];
  14870. vD = vertices[ face.d ];
  14871. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14872. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14873. face._area = face._area1 + face._area2;
  14874. }
  14875. totalArea += face._area;
  14876. cumulativeAreas[ i ] = totalArea;
  14877. }
  14878. // binary search cumulative areas array
  14879. function binarySearchIndices( value ) {
  14880. function binarySearch( start, end ) {
  14881. // return closest larger index
  14882. // if exact number is not found
  14883. if ( end < start )
  14884. return start;
  14885. var mid = start + Math.floor( ( end - start ) / 2 );
  14886. if ( cumulativeAreas[ mid ] > value ) {
  14887. return binarySearch( start, mid - 1 );
  14888. } else if ( cumulativeAreas[ mid ] < value ) {
  14889. return binarySearch( mid + 1, end );
  14890. } else {
  14891. return mid;
  14892. }
  14893. }
  14894. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  14895. return result;
  14896. }
  14897. // pick random face weighted by face area
  14898. var r, index,
  14899. result = [];
  14900. var stats = {};
  14901. for ( i = 0; i < n; i ++ ) {
  14902. r = THREE.GeometryUtils.random() * totalArea;
  14903. index = binarySearchIndices( r );
  14904. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  14905. if ( ! stats[ index ] ) {
  14906. stats[ index ] = 1;
  14907. } else {
  14908. stats[ index ] += 1;
  14909. }
  14910. }
  14911. return result;
  14912. },
  14913. // Get triangle area (half of parallelogram)
  14914. // http://mathworld.wolfram.com/TriangleArea.html
  14915. triangleArea: function ( vectorA, vectorB, vectorC ) {
  14916. var tmp1 = THREE.GeometryUtils.__v1,
  14917. tmp2 = THREE.GeometryUtils.__v2;
  14918. tmp1.sub( vectorB, vectorA );
  14919. tmp2.sub( vectorC, vectorA );
  14920. tmp1.crossSelf( tmp2 );
  14921. return 0.5 * tmp1.length();
  14922. },
  14923. // Center geometry so that 0,0,0 is in center of bounding box
  14924. center: function ( geometry ) {
  14925. geometry.computeBoundingBox();
  14926. var bb = geometry.boundingBox;
  14927. var offset = new THREE.Vector3();
  14928. offset.add( bb.min, bb.max );
  14929. offset.multiplyScalar( -0.5 );
  14930. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset ) );
  14931. geometry.computeBoundingBox();
  14932. return offset;
  14933. },
  14934. // Normalize UVs to be from <0,1>
  14935. // (for now just the first set of UVs)
  14936. normalizeUVs: function ( geometry ) {
  14937. var uvSet = geometry.faceVertexUvs[ 0 ];
  14938. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  14939. var uvs = uvSet[ i ];
  14940. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  14941. // texture repeat
  14942. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  14943. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  14944. }
  14945. }
  14946. },
  14947. triangulateQuads: function ( geometry ) {
  14948. var i, il, j, jl;
  14949. var faces = [];
  14950. var faceUvs = [];
  14951. var faceVertexUvs = [];
  14952. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  14953. faceUvs[ i ] = [];
  14954. }
  14955. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14956. faceVertexUvs[ i ] = [];
  14957. }
  14958. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14959. var face = geometry.faces[ i ];
  14960. if ( face instanceof THREE.Face4 ) {
  14961. var a = face.a;
  14962. var b = face.b;
  14963. var c = face.c;
  14964. var d = face.d;
  14965. var triA = new THREE.Face3();
  14966. var triB = new THREE.Face3();
  14967. triA.color.copy( face.color );
  14968. triB.color.copy( face.color );
  14969. triA.materialIndex = face.materialIndex;
  14970. triB.materialIndex = face.materialIndex;
  14971. triA.a = a;
  14972. triA.b = b;
  14973. triA.c = d;
  14974. triB.a = b;
  14975. triB.b = c;
  14976. triB.c = d;
  14977. if ( face.vertexColors.length === 4 ) {
  14978. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  14979. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  14980. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14981. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  14982. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  14983. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14984. }
  14985. faces.push( triA, triB );
  14986. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14987. if ( geometry.faceVertexUvs[ j ].length ) {
  14988. var uvs = geometry.faceVertexUvs[ j ][ i ];
  14989. var uvA = uvs[ 0 ];
  14990. var uvB = uvs[ 1 ];
  14991. var uvC = uvs[ 2 ];
  14992. var uvD = uvs[ 3 ];
  14993. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  14994. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  14995. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14996. }
  14997. }
  14998. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14999. if ( geometry.faceUvs[ j ].length ) {
  15000. var faceUv = geometry.faceUvs[ j ][ i ];
  15001. faceUvs[ j ].push( faceUv, faceUv );
  15002. }
  15003. }
  15004. } else {
  15005. faces.push( face );
  15006. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15007. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  15008. }
  15009. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15010. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15011. }
  15012. }
  15013. }
  15014. geometry.faces = faces;
  15015. geometry.faceUvs = faceUvs;
  15016. geometry.faceVertexUvs = faceVertexUvs;
  15017. geometry.computeCentroids();
  15018. geometry.computeFaceNormals();
  15019. geometry.computeVertexNormals();
  15020. if ( geometry.hasTangents ) geometry.computeTangents();
  15021. },
  15022. // Make all faces use unique vertices
  15023. // so that each face can be separated from others
  15024. explode: function( geometry ) {
  15025. var vertices = [];
  15026. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15027. var n = vertices.length;
  15028. var face = geometry.faces[ i ];
  15029. if ( face instanceof THREE.Face4 ) {
  15030. var a = face.a;
  15031. var b = face.b;
  15032. var c = face.c;
  15033. var d = face.d;
  15034. var va = geometry.vertices[ a ];
  15035. var vb = geometry.vertices[ b ];
  15036. var vc = geometry.vertices[ c ];
  15037. var vd = geometry.vertices[ d ];
  15038. vertices.push( va.clone() );
  15039. vertices.push( vb.clone() );
  15040. vertices.push( vc.clone() );
  15041. vertices.push( vd.clone() );
  15042. face.a = n;
  15043. face.b = n + 1;
  15044. face.c = n + 2;
  15045. face.d = n + 3;
  15046. } else {
  15047. var a = face.a;
  15048. var b = face.b;
  15049. var c = face.c;
  15050. var va = geometry.vertices[ a ];
  15051. var vb = geometry.vertices[ b ];
  15052. var vc = geometry.vertices[ c ];
  15053. vertices.push( va.clone() );
  15054. vertices.push( vb.clone() );
  15055. vertices.push( vc.clone() );
  15056. face.a = n;
  15057. face.b = n + 1;
  15058. face.c = n + 2;
  15059. }
  15060. }
  15061. geometry.vertices = vertices;
  15062. delete geometry.__tmpVertices;
  15063. },
  15064. // Break faces with edges longer than maxEdgeLength
  15065. // - not recursive
  15066. tessellate: function ( geometry, maxEdgeLength ) {
  15067. var i, il, face,
  15068. a, b, c, d,
  15069. va, vb, vc, vd,
  15070. dab, dbc, dac, dcd, dad,
  15071. m, m1, m2,
  15072. vm, vm1, vm2,
  15073. vnm, vnm1, vnm2,
  15074. vcm, vcm1, vcm2,
  15075. triA, triB,
  15076. quadA, quadB,
  15077. edge;
  15078. var faces = [];
  15079. var faceVertexUvs = [];
  15080. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15081. faceVertexUvs[ i ] = [];
  15082. }
  15083. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15084. face = geometry.faces[ i ];
  15085. if ( face instanceof THREE.Face3 ) {
  15086. a = face.a;
  15087. b = face.b;
  15088. c = face.c;
  15089. va = geometry.vertices[ a ];
  15090. vb = geometry.vertices[ b ];
  15091. vc = geometry.vertices[ c ];
  15092. dab = va.distanceTo( vb );
  15093. dbc = vb.distanceTo( vc );
  15094. dac = va.distanceTo( vc );
  15095. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  15096. m = geometry.vertices.length;
  15097. triA = face.clone();
  15098. triB = face.clone();
  15099. if ( dab >= dbc && dab >= dac ) {
  15100. vm = va.clone();
  15101. vm.lerpSelf( vb, 0.5 );
  15102. triA.a = a;
  15103. triA.b = m;
  15104. triA.c = c;
  15105. triB.a = m;
  15106. triB.b = b;
  15107. triB.c = c;
  15108. if ( face.vertexNormals.length === 3 ) {
  15109. vnm = face.vertexNormals[ 0 ].clone();
  15110. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  15111. triA.vertexNormals[ 1 ].copy( vnm );
  15112. triB.vertexNormals[ 0 ].copy( vnm );
  15113. }
  15114. if ( face.vertexColors.length === 3 ) {
  15115. vcm = face.vertexColors[ 0 ].clone();
  15116. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  15117. triA.vertexColors[ 1 ].copy( vcm );
  15118. triB.vertexColors[ 0 ].copy( vcm );
  15119. }
  15120. edge = 0;
  15121. } else if ( dbc >= dab && dbc >= dac ) {
  15122. vm = vb.clone();
  15123. vm.lerpSelf( vc, 0.5 );
  15124. triA.a = a;
  15125. triA.b = b;
  15126. triA.c = m;
  15127. triB.a = m;
  15128. triB.b = c;
  15129. triB.c = a;
  15130. if ( face.vertexNormals.length === 3 ) {
  15131. vnm = face.vertexNormals[ 1 ].clone();
  15132. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  15133. triA.vertexNormals[ 2 ].copy( vnm );
  15134. triB.vertexNormals[ 0 ].copy( vnm );
  15135. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  15136. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  15137. }
  15138. if ( face.vertexColors.length === 3 ) {
  15139. vcm = face.vertexColors[ 1 ].clone();
  15140. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  15141. triA.vertexColors[ 2 ].copy( vcm );
  15142. triB.vertexColors[ 0 ].copy( vcm );
  15143. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  15144. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  15145. }
  15146. edge = 1;
  15147. } else {
  15148. vm = va.clone();
  15149. vm.lerpSelf( vc, 0.5 );
  15150. triA.a = a;
  15151. triA.b = b;
  15152. triA.c = m;
  15153. triB.a = m;
  15154. triB.b = b;
  15155. triB.c = c;
  15156. if ( face.vertexNormals.length === 3 ) {
  15157. vnm = face.vertexNormals[ 0 ].clone();
  15158. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  15159. triA.vertexNormals[ 2 ].copy( vnm );
  15160. triB.vertexNormals[ 0 ].copy( vnm );
  15161. }
  15162. if ( face.vertexColors.length === 3 ) {
  15163. vcm = face.vertexColors[ 0 ].clone();
  15164. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  15165. triA.vertexColors[ 2 ].copy( vcm );
  15166. triB.vertexColors[ 0 ].copy( vcm );
  15167. }
  15168. edge = 2;
  15169. }
  15170. faces.push( triA, triB );
  15171. geometry.vertices.push( vm );
  15172. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  15173. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15174. if ( geometry.faceVertexUvs[ j ].length ) {
  15175. uvs = geometry.faceVertexUvs[ j ][ i ];
  15176. uvA = uvs[ 0 ];
  15177. uvB = uvs[ 1 ];
  15178. uvC = uvs[ 2 ];
  15179. // AB
  15180. if ( edge === 0 ) {
  15181. uvM = uvA.clone();
  15182. uvM.lerpSelf( uvB, 0.5 );
  15183. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  15184. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  15185. // BC
  15186. } else if ( edge === 1 ) {
  15187. uvM = uvB.clone();
  15188. uvM.lerpSelf( uvC, 0.5 );
  15189. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  15190. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  15191. // AC
  15192. } else {
  15193. uvM = uvA.clone();
  15194. uvM.lerpSelf( uvC, 0.5 );
  15195. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  15196. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  15197. }
  15198. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  15199. }
  15200. }
  15201. } else {
  15202. faces.push( face );
  15203. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15204. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15205. }
  15206. }
  15207. } else {
  15208. a = face.a;
  15209. b = face.b;
  15210. c = face.c;
  15211. d = face.d;
  15212. va = geometry.vertices[ a ];
  15213. vb = geometry.vertices[ b ];
  15214. vc = geometry.vertices[ c ];
  15215. vd = geometry.vertices[ d ];
  15216. dab = va.distanceTo( vb );
  15217. dbc = vb.distanceTo( vc );
  15218. dcd = vc.distanceTo( vd );
  15219. dad = va.distanceTo( vd );
  15220. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  15221. m1 = geometry.vertices.length;
  15222. m2 = geometry.vertices.length + 1;
  15223. quadA = face.clone();
  15224. quadB = face.clone();
  15225. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  15226. vm1 = va.clone();
  15227. vm1.lerpSelf( vb, 0.5 );
  15228. vm2 = vc.clone();
  15229. vm2.lerpSelf( vd, 0.5 );
  15230. quadA.a = a;
  15231. quadA.b = m1;
  15232. quadA.c = m2;
  15233. quadA.d = d;
  15234. quadB.a = m1;
  15235. quadB.b = b;
  15236. quadB.c = c;
  15237. quadB.d = m2;
  15238. if ( face.vertexNormals.length === 4 ) {
  15239. vnm1 = face.vertexNormals[ 0 ].clone();
  15240. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  15241. vnm2 = face.vertexNormals[ 2 ].clone();
  15242. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  15243. quadA.vertexNormals[ 1 ].copy( vnm1 );
  15244. quadA.vertexNormals[ 2 ].copy( vnm2 );
  15245. quadB.vertexNormals[ 0 ].copy( vnm1 );
  15246. quadB.vertexNormals[ 3 ].copy( vnm2 );
  15247. }
  15248. if ( face.vertexColors.length === 4 ) {
  15249. vcm1 = face.vertexColors[ 0 ].clone();
  15250. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  15251. vcm2 = face.vertexColors[ 2 ].clone();
  15252. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  15253. quadA.vertexColors[ 1 ].copy( vcm1 );
  15254. quadA.vertexColors[ 2 ].copy( vcm2 );
  15255. quadB.vertexColors[ 0 ].copy( vcm1 );
  15256. quadB.vertexColors[ 3 ].copy( vcm2 );
  15257. }
  15258. edge = 0;
  15259. } else {
  15260. vm1 = vb.clone();
  15261. vm1.lerpSelf( vc, 0.5 );
  15262. vm2 = vd.clone();
  15263. vm2.lerpSelf( va, 0.5 );
  15264. quadA.a = a;
  15265. quadA.b = b;
  15266. quadA.c = m1;
  15267. quadA.d = m2;
  15268. quadB.a = m2;
  15269. quadB.b = m1;
  15270. quadB.c = c;
  15271. quadB.d = d;
  15272. if ( face.vertexNormals.length === 4 ) {
  15273. vnm1 = face.vertexNormals[ 1 ].clone();
  15274. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  15275. vnm2 = face.vertexNormals[ 3 ].clone();
  15276. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  15277. quadA.vertexNormals[ 2 ].copy( vnm1 );
  15278. quadA.vertexNormals[ 3 ].copy( vnm2 );
  15279. quadB.vertexNormals[ 0 ].copy( vnm2 );
  15280. quadB.vertexNormals[ 1 ].copy( vnm1 );
  15281. }
  15282. if ( face.vertexColors.length === 4 ) {
  15283. vcm1 = face.vertexColors[ 1 ].clone();
  15284. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  15285. vcm2 = face.vertexColors[ 3 ].clone();
  15286. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  15287. quadA.vertexColors[ 2 ].copy( vcm1 );
  15288. quadA.vertexColors[ 3 ].copy( vcm2 );
  15289. quadB.vertexColors[ 0 ].copy( vcm2 );
  15290. quadB.vertexColors[ 1 ].copy( vcm1 );
  15291. }
  15292. edge = 1;
  15293. }
  15294. faces.push( quadA, quadB );
  15295. geometry.vertices.push( vm1, vm2 );
  15296. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  15297. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15298. if ( geometry.faceVertexUvs[ j ].length ) {
  15299. uvs = geometry.faceVertexUvs[ j ][ i ];
  15300. uvA = uvs[ 0 ];
  15301. uvB = uvs[ 1 ];
  15302. uvC = uvs[ 2 ];
  15303. uvD = uvs[ 3 ];
  15304. // AB + CD
  15305. if ( edge === 0 ) {
  15306. uvM1 = uvA.clone();
  15307. uvM1.lerpSelf( uvB, 0.5 );
  15308. uvM2 = uvC.clone();
  15309. uvM2.lerpSelf( uvD, 0.5 );
  15310. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  15311. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  15312. // BC + AD
  15313. } else {
  15314. uvM1 = uvB.clone();
  15315. uvM1.lerpSelf( uvC, 0.5 );
  15316. uvM2 = uvD.clone();
  15317. uvM2.lerpSelf( uvA, 0.5 );
  15318. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  15319. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  15320. }
  15321. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  15322. }
  15323. }
  15324. } else {
  15325. faces.push( face );
  15326. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15327. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15328. }
  15329. }
  15330. }
  15331. }
  15332. geometry.faces = faces;
  15333. geometry.faceVertexUvs = faceVertexUvs;
  15334. }
  15335. };
  15336. THREE.GeometryUtils.random = THREE.Math.random16;
  15337. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  15338. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  15339. /**
  15340. * @author alteredq / http://alteredqualia.com/
  15341. * @author mrdoob / http://mrdoob.com/
  15342. */
  15343. THREE.ImageUtils = {
  15344. crossOrigin: 'anonymous',
  15345. loadTexture: function ( url, mapping, onLoad, onError ) {
  15346. var image = new Image();
  15347. var texture = new THREE.Texture( image, mapping );
  15348. var loader = new THREE.ImageLoader();
  15349. loader.addEventListener( 'load', function ( event ) {
  15350. texture.image = event.content;
  15351. texture.needsUpdate = true;
  15352. if ( onLoad ) onLoad( texture );
  15353. } );
  15354. loader.addEventListener( 'error', function ( event ) {
  15355. if ( onError ) onError( event.message );
  15356. } );
  15357. loader.crossOrigin = this.crossOrigin;
  15358. loader.load( url, image );
  15359. texture.sourceFile = url;
  15360. return texture;
  15361. },
  15362. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15363. var texture = new THREE.CompressedTexture();
  15364. texture.mapping = mapping;
  15365. var request = new XMLHttpRequest();
  15366. request.onload = function () {
  15367. var buffer = request.response;
  15368. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15369. texture.format = dds.format;
  15370. texture.mipmaps = dds.mipmaps;
  15371. texture.image.width = dds.width;
  15372. texture.image.height = dds.height;
  15373. // gl.generateMipmap fails for compressed textures
  15374. // mipmaps must be embedded in the DDS file
  15375. // or texture filters must not use mipmapping
  15376. texture.generateMipmaps = false;
  15377. texture.needsUpdate = true;
  15378. if ( onLoad ) onLoad( texture );
  15379. }
  15380. request.onerror = onError;
  15381. request.open( 'GET', url, true );
  15382. request.responseType = "arraybuffer";
  15383. request.send( null );
  15384. return texture;
  15385. },
  15386. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15387. var images = [];
  15388. images.loadCount = 0;
  15389. var texture = new THREE.Texture();
  15390. texture.image = images;
  15391. if ( mapping !== undefined ) texture.mapping = mapping;
  15392. // no flipping needed for cube textures
  15393. texture.flipY = false;
  15394. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15395. var cubeImage = new Image();
  15396. images[ i ] = cubeImage;
  15397. cubeImage.onload = function () {
  15398. images.loadCount += 1;
  15399. if ( images.loadCount === 6 ) {
  15400. texture.needsUpdate = true;
  15401. if ( onLoad ) onLoad( texture );
  15402. }
  15403. };
  15404. cubeImage.onerror = onError;
  15405. cubeImage.crossOrigin = this.crossOrigin;
  15406. cubeImage.src = array[ i ];
  15407. }
  15408. return texture;
  15409. },
  15410. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15411. var images = [];
  15412. images.loadCount = 0;
  15413. var texture = new THREE.CompressedTexture();
  15414. texture.image = images;
  15415. if ( mapping !== undefined ) texture.mapping = mapping;
  15416. // no flipping for cube textures
  15417. // (also flipping doesn't work for compressed textures )
  15418. texture.flipY = false;
  15419. // can't generate mipmaps for compressed textures
  15420. // mips must be embedded in DDS files
  15421. texture.generateMipmaps = false;
  15422. var generateCubeFaceCallback = function ( rq, img ) {
  15423. return function () {
  15424. var buffer = rq.response;
  15425. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15426. img.format = dds.format;
  15427. img.mipmaps = dds.mipmaps;
  15428. img.width = dds.width;
  15429. img.height = dds.height;
  15430. images.loadCount += 1;
  15431. if ( images.loadCount === 6 ) {
  15432. texture.format = dds.format;
  15433. texture.needsUpdate = true;
  15434. if ( onLoad ) onLoad( texture );
  15435. }
  15436. }
  15437. }
  15438. // compressed cubemap textures as 6 separate DDS files
  15439. if ( array instanceof Array ) {
  15440. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15441. var cubeImage = {};
  15442. images[ i ] = cubeImage;
  15443. var request = new XMLHttpRequest();
  15444. request.onload = generateCubeFaceCallback( request, cubeImage );
  15445. request.onerror = onError;
  15446. var url = array[ i ];
  15447. request.open( 'GET', url, true );
  15448. request.responseType = "arraybuffer";
  15449. request.send( null );
  15450. }
  15451. // compressed cubemap texture stored in a single DDS file
  15452. } else {
  15453. var url = array;
  15454. var request = new XMLHttpRequest();
  15455. request.onload = function( ) {
  15456. var buffer = request.response;
  15457. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15458. if ( dds.isCubemap ) {
  15459. var faces = dds.mipmaps.length / dds.mipmapCount;
  15460. for ( var f = 0; f < faces; f ++ ) {
  15461. images[ f ] = { mipmaps : [] };
  15462. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15463. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15464. images[ f ].format = dds.format;
  15465. images[ f ].width = dds.width;
  15466. images[ f ].height = dds.height;
  15467. }
  15468. }
  15469. texture.format = dds.format;
  15470. texture.needsUpdate = true;
  15471. if ( onLoad ) onLoad( texture );
  15472. }
  15473. }
  15474. request.onerror = onError;
  15475. request.open( 'GET', url, true );
  15476. request.responseType = "arraybuffer";
  15477. request.send( null );
  15478. }
  15479. return texture;
  15480. },
  15481. parseDDS: function ( buffer, loadMipmaps ) {
  15482. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15483. // Adapted from @toji's DDS utils
  15484. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15485. // All values and structures referenced from:
  15486. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15487. var DDS_MAGIC = 0x20534444;
  15488. var DDSD_CAPS = 0x1,
  15489. DDSD_HEIGHT = 0x2,
  15490. DDSD_WIDTH = 0x4,
  15491. DDSD_PITCH = 0x8,
  15492. DDSD_PIXELFORMAT = 0x1000,
  15493. DDSD_MIPMAPCOUNT = 0x20000,
  15494. DDSD_LINEARSIZE = 0x80000,
  15495. DDSD_DEPTH = 0x800000;
  15496. var DDSCAPS_COMPLEX = 0x8,
  15497. DDSCAPS_MIPMAP = 0x400000,
  15498. DDSCAPS_TEXTURE = 0x1000;
  15499. var DDSCAPS2_CUBEMAP = 0x200,
  15500. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15501. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15502. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15503. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15504. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15505. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15506. DDSCAPS2_VOLUME = 0x200000;
  15507. var DDPF_ALPHAPIXELS = 0x1,
  15508. DDPF_ALPHA = 0x2,
  15509. DDPF_FOURCC = 0x4,
  15510. DDPF_RGB = 0x40,
  15511. DDPF_YUV = 0x200,
  15512. DDPF_LUMINANCE = 0x20000;
  15513. function fourCCToInt32( value ) {
  15514. return value.charCodeAt(0) +
  15515. (value.charCodeAt(1) << 8) +
  15516. (value.charCodeAt(2) << 16) +
  15517. (value.charCodeAt(3) << 24);
  15518. }
  15519. function int32ToFourCC( value ) {
  15520. return String.fromCharCode(
  15521. value & 0xff,
  15522. (value >> 8) & 0xff,
  15523. (value >> 16) & 0xff,
  15524. (value >> 24) & 0xff
  15525. );
  15526. }
  15527. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15528. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15529. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15530. var headerLengthInt = 31; // The header length in 32 bit ints
  15531. // Offsets into the header array
  15532. var off_magic = 0;
  15533. var off_size = 1;
  15534. var off_flags = 2;
  15535. var off_height = 3;
  15536. var off_width = 4;
  15537. var off_mipmapCount = 7;
  15538. var off_pfFlags = 20;
  15539. var off_pfFourCC = 21;
  15540. var off_caps = 27;
  15541. var off_caps2 = 28;
  15542. var off_caps3 = 29;
  15543. var off_caps4 = 30;
  15544. // Parse header
  15545. var header = new Int32Array( buffer, 0, headerLengthInt );
  15546. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15547. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15548. return dds;
  15549. }
  15550. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15551. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15552. return dds;
  15553. }
  15554. var blockBytes;
  15555. var fourCC = header[ off_pfFourCC ];
  15556. switch ( fourCC ) {
  15557. case FOURCC_DXT1:
  15558. blockBytes = 8;
  15559. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15560. break;
  15561. case FOURCC_DXT3:
  15562. blockBytes = 16;
  15563. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15564. break;
  15565. case FOURCC_DXT5:
  15566. blockBytes = 16;
  15567. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15568. break;
  15569. default:
  15570. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15571. return dds;
  15572. }
  15573. dds.mipmapCount = 1;
  15574. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15575. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15576. }
  15577. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15578. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15579. dds.width = header[ off_width ];
  15580. dds.height = header[ off_height ];
  15581. var dataOffset = header[ off_size ] + 4;
  15582. // Extract mipmaps buffers
  15583. var width = dds.width;
  15584. var height = dds.height;
  15585. var faces = dds.isCubemap ? 6 : 1;
  15586. for ( var face = 0; face < faces; face ++ ) {
  15587. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15588. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  15589. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  15590. var mipmap = { "data": byteArray, "width": width, "height": height };
  15591. dds.mipmaps.push( mipmap );
  15592. dataOffset += dataLength;
  15593. width = Math.max( width * 0.5, 1 );
  15594. height = Math.max( height * 0.5, 1 );
  15595. }
  15596. width = dds.width;
  15597. height = dds.height;
  15598. }
  15599. return dds;
  15600. },
  15601. getNormalMap: function ( image, depth ) {
  15602. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15603. var cross = function ( a, b ) {
  15604. 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 ] ];
  15605. }
  15606. var subtract = function ( a, b ) {
  15607. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15608. }
  15609. var normalize = function ( a ) {
  15610. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15611. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15612. }
  15613. depth = depth | 1;
  15614. var width = image.width;
  15615. var height = image.height;
  15616. var canvas = document.createElement( 'canvas' );
  15617. canvas.width = width;
  15618. canvas.height = height;
  15619. var context = canvas.getContext( '2d' );
  15620. context.drawImage( image, 0, 0 );
  15621. var data = context.getImageData( 0, 0, width, height ).data;
  15622. var imageData = context.createImageData( width, height );
  15623. var output = imageData.data;
  15624. for ( var x = 0; x < width; x ++ ) {
  15625. for ( var y = 0; y < height; y ++ ) {
  15626. var ly = y - 1 < 0 ? 0 : y - 1;
  15627. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15628. var lx = x - 1 < 0 ? 0 : x - 1;
  15629. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15630. var points = [];
  15631. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15632. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15633. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15634. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15635. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15636. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15637. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15638. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15639. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15640. var normals = [];
  15641. var num_points = points.length;
  15642. for ( var i = 0; i < num_points; i ++ ) {
  15643. var v1 = points[ i ];
  15644. var v2 = points[ ( i + 1 ) % num_points ];
  15645. v1 = subtract( v1, origin );
  15646. v2 = subtract( v2, origin );
  15647. normals.push( normalize( cross( v1, v2 ) ) );
  15648. }
  15649. var normal = [ 0, 0, 0 ];
  15650. for ( var i = 0; i < normals.length; i ++ ) {
  15651. normal[ 0 ] += normals[ i ][ 0 ];
  15652. normal[ 1 ] += normals[ i ][ 1 ];
  15653. normal[ 2 ] += normals[ i ][ 2 ];
  15654. }
  15655. normal[ 0 ] /= normals.length;
  15656. normal[ 1 ] /= normals.length;
  15657. normal[ 2 ] /= normals.length;
  15658. var idx = ( y * width + x ) * 4;
  15659. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15660. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15661. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15662. output[ idx + 3 ] = 255;
  15663. }
  15664. }
  15665. context.putImageData( imageData, 0, 0 );
  15666. return canvas;
  15667. },
  15668. generateDataTexture: function ( width, height, color ) {
  15669. var size = width * height;
  15670. var data = new Uint8Array( 3 * size );
  15671. var r = Math.floor( color.r * 255 );
  15672. var g = Math.floor( color.g * 255 );
  15673. var b = Math.floor( color.b * 255 );
  15674. for ( var i = 0; i < size; i ++ ) {
  15675. data[ i * 3 ] = r;
  15676. data[ i * 3 + 1 ] = g;
  15677. data[ i * 3 + 2 ] = b;
  15678. }
  15679. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15680. texture.needsUpdate = true;
  15681. return texture;
  15682. }
  15683. };
  15684. /**
  15685. * @author alteredq / http://alteredqualia.com/
  15686. */
  15687. THREE.SceneUtils = {
  15688. createMultiMaterialObject: function ( geometry, materials ) {
  15689. var group = new THREE.Object3D();
  15690. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15691. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15692. }
  15693. return group;
  15694. },
  15695. detach : function ( child, parent, scene ) {
  15696. child.applyMatrix( parent.matrixWorld );
  15697. parent.remove( child );
  15698. scene.add( child );
  15699. },
  15700. attach: function ( child, scene, parent ) {
  15701. var matrixWorldInverse = new THREE.Matrix4();
  15702. matrixWorldInverse.getInverse( parent.matrixWorld );
  15703. child.applyMatrix( matrixWorldInverse );
  15704. scene.remove( child );
  15705. parent.add( child );
  15706. }
  15707. };
  15708. /**
  15709. * @author alteredq / http://alteredqualia.com/
  15710. * @author mrdoob / http://mrdoob.com/
  15711. *
  15712. * ShaderUtils currently contains:
  15713. *
  15714. * fresnel
  15715. * normal
  15716. * cube
  15717. *
  15718. */
  15719. THREE.ShaderUtils = {
  15720. lib: {
  15721. /* -------------------------------------------------------------------------
  15722. // Fresnel shader
  15723. // - based on Nvidia Cg tutorial
  15724. ------------------------------------------------------------------------- */
  15725. 'fresnel': {
  15726. uniforms: {
  15727. "mRefractionRatio": { type: "f", value: 1.02 },
  15728. "mFresnelBias": { type: "f", value: 0.1 },
  15729. "mFresnelPower": { type: "f", value: 2.0 },
  15730. "mFresnelScale": { type: "f", value: 1.0 },
  15731. "tCube": { type: "t", value: null }
  15732. },
  15733. fragmentShader: [
  15734. "uniform samplerCube tCube;",
  15735. "varying vec3 vReflect;",
  15736. "varying vec3 vRefract[3];",
  15737. "varying float vReflectionFactor;",
  15738. "void main() {",
  15739. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15740. "vec4 refractedColor = vec4( 1.0 );",
  15741. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  15742. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  15743. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  15744. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  15745. "}"
  15746. ].join("\n"),
  15747. vertexShader: [
  15748. "uniform float mRefractionRatio;",
  15749. "uniform float mFresnelBias;",
  15750. "uniform float mFresnelScale;",
  15751. "uniform float mFresnelPower;",
  15752. "varying vec3 vReflect;",
  15753. "varying vec3 vRefract[3];",
  15754. "varying float vReflectionFactor;",
  15755. "void main() {",
  15756. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  15757. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15758. "vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  15759. "vec3 I = worldPosition.xyz - cameraPosition;",
  15760. "vReflect = reflect( I, worldNormal );",
  15761. "vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );",
  15762. "vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );",
  15763. "vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );",
  15764. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );",
  15765. "gl_Position = projectionMatrix * mvPosition;",
  15766. "}"
  15767. ].join("\n")
  15768. },
  15769. /* -------------------------------------------------------------------------
  15770. // Normal map shader
  15771. // - Blinn-Phong
  15772. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  15773. // - point and directional lights (use with "lights: true" material option)
  15774. ------------------------------------------------------------------------- */
  15775. 'normal' : {
  15776. uniforms: THREE.UniformsUtils.merge( [
  15777. THREE.UniformsLib[ "fog" ],
  15778. THREE.UniformsLib[ "lights" ],
  15779. THREE.UniformsLib[ "shadowmap" ],
  15780. {
  15781. "enableAO" : { type: "i", value: 0 },
  15782. "enableDiffuse" : { type: "i", value: 0 },
  15783. "enableSpecular" : { type: "i", value: 0 },
  15784. "enableReflection": { type: "i", value: 0 },
  15785. "enableDisplacement": { type: "i", value: 0 },
  15786. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  15787. "tDiffuse" : { type: "t", value: null },
  15788. "tCube" : { type: "t", value: null },
  15789. "tNormal" : { type: "t", value: null },
  15790. "tSpecular" : { type: "t", value: null },
  15791. "tAO" : { type: "t", value: null },
  15792. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  15793. "uDisplacementBias": { type: "f", value: 0.0 },
  15794. "uDisplacementScale": { type: "f", value: 1.0 },
  15795. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  15796. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  15797. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  15798. "uShininess": { type: "f", value: 30 },
  15799. "uOpacity": { type: "f", value: 1 },
  15800. "useRefract": { type: "i", value: 0 },
  15801. "uRefractionRatio": { type: "f", value: 0.98 },
  15802. "uReflectivity": { type: "f", value: 0.5 },
  15803. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  15804. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  15805. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  15806. }
  15807. ] ),
  15808. fragmentShader: [
  15809. "uniform vec3 uAmbientColor;",
  15810. "uniform vec3 uDiffuseColor;",
  15811. "uniform vec3 uSpecularColor;",
  15812. "uniform float uShininess;",
  15813. "uniform float uOpacity;",
  15814. "uniform bool enableDiffuse;",
  15815. "uniform bool enableSpecular;",
  15816. "uniform bool enableAO;",
  15817. "uniform bool enableReflection;",
  15818. "uniform sampler2D tDiffuse;",
  15819. "uniform sampler2D tNormal;",
  15820. "uniform sampler2D tSpecular;",
  15821. "uniform sampler2D tAO;",
  15822. "uniform samplerCube tCube;",
  15823. "uniform vec2 uNormalScale;",
  15824. "uniform bool useRefract;",
  15825. "uniform float uRefractionRatio;",
  15826. "uniform float uReflectivity;",
  15827. "varying vec3 vTangent;",
  15828. "varying vec3 vBinormal;",
  15829. "varying vec3 vNormal;",
  15830. "varying vec2 vUv;",
  15831. "uniform vec3 ambientLightColor;",
  15832. "#if MAX_DIR_LIGHTS > 0",
  15833. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  15834. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  15835. "#endif",
  15836. "#if MAX_HEMI_LIGHTS > 0",
  15837. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  15838. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  15839. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  15840. "#endif",
  15841. "#if MAX_POINT_LIGHTS > 0",
  15842. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  15843. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  15844. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  15845. "#endif",
  15846. "#if MAX_SPOT_LIGHTS > 0",
  15847. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  15848. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  15849. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  15850. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  15851. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  15852. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  15853. "#endif",
  15854. "#ifdef WRAP_AROUND",
  15855. "uniform vec3 wrapRGB;",
  15856. "#endif",
  15857. "varying vec3 vWorldPosition;",
  15858. "varying vec3 vViewPosition;",
  15859. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  15860. THREE.ShaderChunk[ "fog_pars_fragment" ],
  15861. "void main() {",
  15862. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  15863. "vec3 specularTex = vec3( 1.0 );",
  15864. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  15865. "normalTex.xy *= uNormalScale;",
  15866. "normalTex = normalize( normalTex );",
  15867. "if( enableDiffuse ) {",
  15868. "#ifdef GAMMA_INPUT",
  15869. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  15870. "texelColor.xyz *= texelColor.xyz;",
  15871. "gl_FragColor = gl_FragColor * texelColor;",
  15872. "#else",
  15873. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  15874. "#endif",
  15875. "}",
  15876. "if( enableAO ) {",
  15877. "#ifdef GAMMA_INPUT",
  15878. "vec4 aoColor = texture2D( tAO, vUv );",
  15879. "aoColor.xyz *= aoColor.xyz;",
  15880. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  15881. "#else",
  15882. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  15883. "#endif",
  15884. "}",
  15885. "if( enableSpecular )",
  15886. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  15887. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  15888. "vec3 finalNormal = tsb * normalTex;",
  15889. "#ifdef FLIP_SIDED",
  15890. "finalNormal = -finalNormal;",
  15891. "#endif",
  15892. "vec3 normal = normalize( finalNormal );",
  15893. "vec3 viewPosition = normalize( vViewPosition );",
  15894. // point lights
  15895. "#if MAX_POINT_LIGHTS > 0",
  15896. "vec3 pointDiffuse = vec3( 0.0 );",
  15897. "vec3 pointSpecular = vec3( 0.0 );",
  15898. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  15899. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  15900. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  15901. "float pointDistance = 1.0;",
  15902. "if ( pointLightDistance[ i ] > 0.0 )",
  15903. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  15904. "pointVector = normalize( pointVector );",
  15905. // diffuse
  15906. "#ifdef WRAP_AROUND",
  15907. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  15908. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  15909. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  15910. "#else",
  15911. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  15912. "#endif",
  15913. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  15914. // specular
  15915. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  15916. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  15917. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  15918. "#ifdef PHYSICALLY_BASED_SHADING",
  15919. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15920. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15921. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  15922. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  15923. "#else",
  15924. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  15925. "#endif",
  15926. "}",
  15927. "#endif",
  15928. // spot lights
  15929. "#if MAX_SPOT_LIGHTS > 0",
  15930. "vec3 spotDiffuse = vec3( 0.0 );",
  15931. "vec3 spotSpecular = vec3( 0.0 );",
  15932. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  15933. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  15934. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  15935. "float spotDistance = 1.0;",
  15936. "if ( spotLightDistance[ i ] > 0.0 )",
  15937. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  15938. "spotVector = normalize( spotVector );",
  15939. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  15940. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  15941. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  15942. // diffuse
  15943. "#ifdef WRAP_AROUND",
  15944. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  15945. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  15946. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  15947. "#else",
  15948. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  15949. "#endif",
  15950. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  15951. // specular
  15952. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  15953. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  15954. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  15955. "#ifdef PHYSICALLY_BASED_SHADING",
  15956. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15957. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15958. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  15959. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  15960. "#else",
  15961. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  15962. "#endif",
  15963. "}",
  15964. "}",
  15965. "#endif",
  15966. // directional lights
  15967. "#if MAX_DIR_LIGHTS > 0",
  15968. "vec3 dirDiffuse = vec3( 0.0 );",
  15969. "vec3 dirSpecular = vec3( 0.0 );",
  15970. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  15971. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  15972. "vec3 dirVector = normalize( lDirection.xyz );",
  15973. // diffuse
  15974. "#ifdef WRAP_AROUND",
  15975. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  15976. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  15977. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  15978. "#else",
  15979. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  15980. "#endif",
  15981. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  15982. // specular
  15983. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  15984. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  15985. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  15986. "#ifdef PHYSICALLY_BASED_SHADING",
  15987. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15988. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15989. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  15990. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  15991. "#else",
  15992. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  15993. "#endif",
  15994. "}",
  15995. "#endif",
  15996. // hemisphere lights
  15997. "#if MAX_HEMI_LIGHTS > 0",
  15998. "vec3 hemiDiffuse = vec3( 0.0 );",
  15999. "vec3 hemiSpecular = vec3( 0.0 );" ,
  16000. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  16001. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  16002. "vec3 lVector = normalize( lDirection.xyz );",
  16003. // diffuse
  16004. "float dotProduct = dot( normal, lVector );",
  16005. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  16006. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  16007. "hemiDiffuse += uDiffuseColor * hemiColor;",
  16008. // specular (sky light)
  16009. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  16010. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  16011. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  16012. // specular (ground light)
  16013. "vec3 lVectorGround = -lVector;",
  16014. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  16015. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  16016. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  16017. "#ifdef PHYSICALLY_BASED_SHADING",
  16018. "float dotProductGround = dot( normal, lVectorGround );",
  16019. // 2.0 => 2.0001 is hack to work around ANGLE bug
  16020. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  16021. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  16022. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  16023. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  16024. "#else",
  16025. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  16026. "#endif",
  16027. "}",
  16028. "#endif",
  16029. // all lights contribution summation
  16030. "vec3 totalDiffuse = vec3( 0.0 );",
  16031. "vec3 totalSpecular = vec3( 0.0 );",
  16032. "#if MAX_DIR_LIGHTS > 0",
  16033. "totalDiffuse += dirDiffuse;",
  16034. "totalSpecular += dirSpecular;",
  16035. "#endif",
  16036. "#if MAX_HEMI_LIGHTS > 0",
  16037. "totalDiffuse += hemiDiffuse;",
  16038. "totalSpecular += hemiSpecular;",
  16039. "#endif",
  16040. "#if MAX_POINT_LIGHTS > 0",
  16041. "totalDiffuse += pointDiffuse;",
  16042. "totalSpecular += pointSpecular;",
  16043. "#endif",
  16044. "#if MAX_SPOT_LIGHTS > 0",
  16045. "totalDiffuse += spotDiffuse;",
  16046. "totalSpecular += spotSpecular;",
  16047. "#endif",
  16048. "#ifdef METAL",
  16049. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  16050. "#else",
  16051. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  16052. "#endif",
  16053. "if ( enableReflection ) {",
  16054. "vec3 vReflect;",
  16055. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  16056. "if ( useRefract ) {",
  16057. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  16058. "} else {",
  16059. "vReflect = reflect( cameraToVertex, normal );",
  16060. "}",
  16061. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  16062. "#ifdef GAMMA_INPUT",
  16063. "cubeColor.xyz *= cubeColor.xyz;",
  16064. "#endif",
  16065. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  16066. "}",
  16067. THREE.ShaderChunk[ "shadowmap_fragment" ],
  16068. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  16069. THREE.ShaderChunk[ "fog_fragment" ],
  16070. "}"
  16071. ].join("\n"),
  16072. vertexShader: [
  16073. "attribute vec4 tangent;",
  16074. "uniform vec2 uOffset;",
  16075. "uniform vec2 uRepeat;",
  16076. "uniform bool enableDisplacement;",
  16077. "#ifdef VERTEX_TEXTURES",
  16078. "uniform sampler2D tDisplacement;",
  16079. "uniform float uDisplacementScale;",
  16080. "uniform float uDisplacementBias;",
  16081. "#endif",
  16082. "varying vec3 vTangent;",
  16083. "varying vec3 vBinormal;",
  16084. "varying vec3 vNormal;",
  16085. "varying vec2 vUv;",
  16086. "varying vec3 vWorldPosition;",
  16087. "varying vec3 vViewPosition;",
  16088. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  16089. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  16090. "void main() {",
  16091. THREE.ShaderChunk[ "skinbase_vertex" ],
  16092. THREE.ShaderChunk[ "skinnormal_vertex" ],
  16093. // normal, tangent and binormal vectors
  16094. "#ifdef USE_SKINNING",
  16095. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  16096. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  16097. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  16098. "#else",
  16099. "vNormal = normalize( normalMatrix * normal );",
  16100. "vTangent = normalize( normalMatrix * tangent.xyz );",
  16101. "#endif",
  16102. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  16103. "vUv = uv * uRepeat + uOffset;",
  16104. // displacement mapping
  16105. "vec3 displacedPosition;",
  16106. "#ifdef VERTEX_TEXTURES",
  16107. "if ( enableDisplacement ) {",
  16108. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  16109. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  16110. "displacedPosition = position + normalize( normal ) * df;",
  16111. "} else {",
  16112. "#ifdef USE_SKINNING",
  16113. "vec4 skinVertex = vec4( position, 1.0 );",
  16114. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  16115. "skinned += boneMatY * skinVertex * skinWeight.y;",
  16116. "displacedPosition = skinned.xyz;",
  16117. "#else",
  16118. "displacedPosition = position;",
  16119. "#endif",
  16120. "}",
  16121. "#else",
  16122. "#ifdef USE_SKINNING",
  16123. "vec4 skinVertex = vec4( position, 1.0 );",
  16124. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  16125. "skinned += boneMatY * skinVertex * skinWeight.y;",
  16126. "displacedPosition = skinned.xyz;",
  16127. "#else",
  16128. "displacedPosition = position;",
  16129. "#endif",
  16130. "#endif",
  16131. //
  16132. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  16133. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  16134. "gl_Position = projectionMatrix * mvPosition;",
  16135. //
  16136. "vWorldPosition = worldPosition.xyz;",
  16137. "vViewPosition = -mvPosition.xyz;",
  16138. // shadows
  16139. "#ifdef USE_SHADOWMAP",
  16140. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  16141. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  16142. "}",
  16143. "#endif",
  16144. "}"
  16145. ].join("\n")
  16146. },
  16147. /* -------------------------------------------------------------------------
  16148. // Cube map shader
  16149. ------------------------------------------------------------------------- */
  16150. 'cube': {
  16151. uniforms: { "tCube": { type: "t", value: null },
  16152. "tFlip": { type: "f", value: -1 } },
  16153. vertexShader: [
  16154. "varying vec3 vWorldPosition;",
  16155. "void main() {",
  16156. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  16157. "vWorldPosition = worldPosition.xyz;",
  16158. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  16159. "}"
  16160. ].join("\n"),
  16161. fragmentShader: [
  16162. "uniform samplerCube tCube;",
  16163. "uniform float tFlip;",
  16164. "varying vec3 vWorldPosition;",
  16165. "void main() {",
  16166. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  16167. "}"
  16168. ].join("\n")
  16169. }
  16170. }
  16171. };
  16172. /**
  16173. * @author zz85 / http://www.lab4games.net/zz85/blog
  16174. * @author alteredq / http://alteredqualia.com/
  16175. *
  16176. * For Text operations in three.js (See TextGeometry)
  16177. *
  16178. * It uses techniques used in:
  16179. *
  16180. * typeface.js and canvastext
  16181. * For converting fonts and rendering with javascript
  16182. * http://typeface.neocracy.org
  16183. *
  16184. * Triangulation ported from AS3
  16185. * Simple Polygon Triangulation
  16186. * http://actionsnippet.com/?p=1462
  16187. *
  16188. * A Method to triangulate shapes with holes
  16189. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16190. *
  16191. */
  16192. THREE.FontUtils = {
  16193. faces : {},
  16194. // Just for now. face[weight][style]
  16195. face : "helvetiker",
  16196. weight: "normal",
  16197. style : "normal",
  16198. size : 150,
  16199. divisions : 10,
  16200. getFace : function() {
  16201. return this.faces[ this.face ][ this.weight ][ this.style ];
  16202. },
  16203. loadFace : function( data ) {
  16204. var family = data.familyName.toLowerCase();
  16205. var ThreeFont = this;
  16206. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16207. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16208. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16209. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16210. return data;
  16211. },
  16212. drawText : function( text ) {
  16213. var characterPts = [], allPts = [];
  16214. // RenderText
  16215. var i, p,
  16216. face = this.getFace(),
  16217. scale = this.size / face.resolution,
  16218. offset = 0,
  16219. chars = String( text ).split( '' ),
  16220. length = chars.length;
  16221. var fontPaths = [];
  16222. for ( i = 0; i < length; i ++ ) {
  16223. var path = new THREE.Path();
  16224. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16225. offset += ret.offset;
  16226. fontPaths.push( ret.path );
  16227. }
  16228. // get the width
  16229. var width = offset / 2;
  16230. //
  16231. // for ( p = 0; p < allPts.length; p++ ) {
  16232. //
  16233. // allPts[ p ].x -= width;
  16234. //
  16235. // }
  16236. //var extract = this.extractPoints( allPts, characterPts );
  16237. //extract.contour = allPts;
  16238. //extract.paths = fontPaths;
  16239. //extract.offset = width;
  16240. return { paths : fontPaths, offset : width };
  16241. },
  16242. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16243. var pts = [];
  16244. var i, i2, divisions,
  16245. outline, action, length,
  16246. scaleX, scaleY,
  16247. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16248. laste,
  16249. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16250. if ( !glyph ) return;
  16251. if ( glyph.o ) {
  16252. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16253. length = outline.length;
  16254. scaleX = scale;
  16255. scaleY = scale;
  16256. for ( i = 0; i < length; ) {
  16257. action = outline[ i ++ ];
  16258. //console.log( action );
  16259. switch( action ) {
  16260. case 'm':
  16261. // Move To
  16262. x = outline[ i++ ] * scaleX + offset;
  16263. y = outline[ i++ ] * scaleY;
  16264. path.moveTo( x, y );
  16265. break;
  16266. case 'l':
  16267. // Line To
  16268. x = outline[ i++ ] * scaleX + offset;
  16269. y = outline[ i++ ] * scaleY;
  16270. path.lineTo(x,y);
  16271. break;
  16272. case 'q':
  16273. // QuadraticCurveTo
  16274. cpx = outline[ i++ ] * scaleX + offset;
  16275. cpy = outline[ i++ ] * scaleY;
  16276. cpx1 = outline[ i++ ] * scaleX + offset;
  16277. cpy1 = outline[ i++ ] * scaleY;
  16278. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16279. laste = pts[ pts.length - 1 ];
  16280. if ( laste ) {
  16281. cpx0 = laste.x;
  16282. cpy0 = laste.y;
  16283. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16284. var t = i2 / divisions;
  16285. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16286. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16287. }
  16288. }
  16289. break;
  16290. case 'b':
  16291. // Cubic Bezier Curve
  16292. cpx = outline[ i++ ] * scaleX + offset;
  16293. cpy = outline[ i++ ] * scaleY;
  16294. cpx1 = outline[ i++ ] * scaleX + offset;
  16295. cpy1 = outline[ i++ ] * -scaleY;
  16296. cpx2 = outline[ i++ ] * scaleX + offset;
  16297. cpy2 = outline[ i++ ] * -scaleY;
  16298. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16299. laste = pts[ pts.length - 1 ];
  16300. if ( laste ) {
  16301. cpx0 = laste.x;
  16302. cpy0 = laste.y;
  16303. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16304. var t = i2 / divisions;
  16305. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16306. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16307. }
  16308. }
  16309. break;
  16310. }
  16311. }
  16312. }
  16313. return { offset: glyph.ha*scale, path:path};
  16314. }
  16315. };
  16316. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16317. // Parameters
  16318. parameters = parameters || {};
  16319. var size = parameters.size !== undefined ? parameters.size : 100;
  16320. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16321. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16322. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16323. var style = parameters.style !== undefined ? parameters.style : "normal";
  16324. THREE.FontUtils.size = size;
  16325. THREE.FontUtils.divisions = curveSegments;
  16326. THREE.FontUtils.face = font;
  16327. THREE.FontUtils.weight = weight;
  16328. THREE.FontUtils.style = style;
  16329. // Get a Font data json object
  16330. var data = THREE.FontUtils.drawText( text );
  16331. var paths = data.paths;
  16332. var shapes = [];
  16333. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16334. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16335. }
  16336. return shapes;
  16337. };
  16338. /**
  16339. * This code is a quick port of code written in C++ which was submitted to
  16340. * flipcode.com by John W. Ratcliff // July 22, 2000
  16341. * See original code and more information here:
  16342. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16343. *
  16344. * ported to actionscript by Zevan Rosser
  16345. * www.actionsnippet.com
  16346. *
  16347. * ported to javascript by Joshua Koo
  16348. * http://www.lab4games.net/zz85/blog
  16349. *
  16350. */
  16351. ( function( namespace ) {
  16352. var EPSILON = 0.0000000001;
  16353. // takes in an contour array and returns
  16354. var process = function( contour, indices ) {
  16355. var n = contour.length;
  16356. if ( n < 3 ) return null;
  16357. var result = [],
  16358. verts = [],
  16359. vertIndices = [];
  16360. /* we want a counter-clockwise polygon in verts */
  16361. var u, v, w;
  16362. if ( area( contour ) > 0.0 ) {
  16363. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16364. } else {
  16365. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16366. }
  16367. var nv = n;
  16368. /* remove nv - 2 vertices, creating 1 triangle every time */
  16369. var count = 2 * nv; /* error detection */
  16370. for( v = nv - 1; nv > 2; ) {
  16371. /* if we loop, it is probably a non-simple polygon */
  16372. if ( ( count-- ) <= 0 ) {
  16373. //** Triangulate: ERROR - probable bad polygon!
  16374. //throw ( "Warning, unable to triangulate polygon!" );
  16375. //return null;
  16376. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16377. console.log( "Warning, unable to triangulate polygon!" );
  16378. if ( indices ) return vertIndices;
  16379. return result;
  16380. }
  16381. /* three consecutive vertices in current polygon, <u,v,w> */
  16382. u = v; if ( nv <= u ) u = 0; /* previous */
  16383. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16384. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16385. if ( snip( contour, u, v, w, nv, verts ) ) {
  16386. var a, b, c, s, t;
  16387. /* true names of the vertices */
  16388. a = verts[ u ];
  16389. b = verts[ v ];
  16390. c = verts[ w ];
  16391. /* output Triangle */
  16392. result.push( [ contour[ a ],
  16393. contour[ b ],
  16394. contour[ c ] ] );
  16395. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16396. /* remove v from the remaining polygon */
  16397. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16398. verts[ s ] = verts[ t ];
  16399. }
  16400. nv--;
  16401. /* reset error detection counter */
  16402. count = 2 * nv;
  16403. }
  16404. }
  16405. if ( indices ) return vertIndices;
  16406. return result;
  16407. };
  16408. // calculate area of the contour polygon
  16409. var area = function ( contour ) {
  16410. var n = contour.length;
  16411. var a = 0.0;
  16412. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16413. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16414. }
  16415. return a * 0.5;
  16416. };
  16417. var snip = function ( contour, u, v, w, n, verts ) {
  16418. var p;
  16419. var ax, ay, bx, by;
  16420. var cx, cy, px, py;
  16421. ax = contour[ verts[ u ] ].x;
  16422. ay = contour[ verts[ u ] ].y;
  16423. bx = contour[ verts[ v ] ].x;
  16424. by = contour[ verts[ v ] ].y;
  16425. cx = contour[ verts[ w ] ].x;
  16426. cy = contour[ verts[ w ] ].y;
  16427. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16428. var aX, aY, bX, bY, cX, cY;
  16429. var apx, apy, bpx, bpy, cpx, cpy;
  16430. var cCROSSap, bCROSScp, aCROSSbp;
  16431. aX = cx - bx; aY = cy - by;
  16432. bX = ax - cx; bY = ay - cy;
  16433. cX = bx - ax; cY = by - ay;
  16434. for ( p = 0; p < n; p++ ) {
  16435. if( (p === u) || (p === v) || (p === w) ) continue;
  16436. px = contour[ verts[ p ] ].x
  16437. py = contour[ verts[ p ] ].y
  16438. apx = px - ax; apy = py - ay;
  16439. bpx = px - bx; bpy = py - by;
  16440. cpx = px - cx; cpy = py - cy;
  16441. // see if p is inside triangle abc
  16442. aCROSSbp = aX*bpy - aY*bpx;
  16443. cCROSSap = cX*apy - cY*apx;
  16444. bCROSScp = bX*cpy - bY*cpx;
  16445. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16446. }
  16447. return true;
  16448. };
  16449. namespace.Triangulate = process;
  16450. namespace.Triangulate.area = area;
  16451. return namespace;
  16452. })(THREE.FontUtils);
  16453. // To use the typeface.js face files, hook up the API
  16454. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  16455. * @author zz85 / http://www.lab4games.net/zz85/blog
  16456. * Extensible curve object
  16457. *
  16458. * Some common of Curve methods
  16459. * .getPoint(t), getTangent(t)
  16460. * .getPointAt(u), getTagentAt(u)
  16461. * .getPoints(), .getSpacedPoints()
  16462. * .getLength()
  16463. * .updateArcLengths()
  16464. *
  16465. * This file contains following classes:
  16466. *
  16467. * -- 2d classes --
  16468. * THREE.Curve
  16469. * THREE.LineCurve
  16470. * THREE.QuadraticBezierCurve
  16471. * THREE.CubicBezierCurve
  16472. * THREE.SplineCurve
  16473. * THREE.ArcCurve
  16474. * THREE.EllipseCurve
  16475. *
  16476. * -- 3d classes --
  16477. * THREE.LineCurve3
  16478. * THREE.QuadraticBezierCurve3
  16479. * THREE.CubicBezierCurve3
  16480. * THREE.SplineCurve3
  16481. * THREE.ClosedSplineCurve3
  16482. *
  16483. * A series of curves can be represented as a THREE.CurvePath
  16484. *
  16485. **/
  16486. /**************************************************************
  16487. * Abstract Curve base class
  16488. **************************************************************/
  16489. THREE.Curve = function () {
  16490. };
  16491. // Virtual base class method to overwrite and implement in subclasses
  16492. // - t [0 .. 1]
  16493. THREE.Curve.prototype.getPoint = function ( t ) {
  16494. console.log( "Warning, getPoint() not implemented!" );
  16495. return null;
  16496. };
  16497. // Get point at relative position in curve according to arc length
  16498. // - u [0 .. 1]
  16499. THREE.Curve.prototype.getPointAt = function ( u ) {
  16500. var t = this.getUtoTmapping( u );
  16501. return this.getPoint( t );
  16502. };
  16503. // Get sequence of points using getPoint( t )
  16504. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16505. if ( !divisions ) divisions = 5;
  16506. var d, pts = [];
  16507. for ( d = 0; d <= divisions; d ++ ) {
  16508. pts.push( this.getPoint( d / divisions ) );
  16509. }
  16510. return pts;
  16511. };
  16512. // Get sequence of points using getPointAt( u )
  16513. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16514. if ( !divisions ) divisions = 5;
  16515. var d, pts = [];
  16516. for ( d = 0; d <= divisions; d ++ ) {
  16517. pts.push( this.getPointAt( d / divisions ) );
  16518. }
  16519. return pts;
  16520. };
  16521. // Get total curve arc length
  16522. THREE.Curve.prototype.getLength = function () {
  16523. var lengths = this.getLengths();
  16524. return lengths[ lengths.length - 1 ];
  16525. };
  16526. // Get list of cumulative segment lengths
  16527. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16528. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16529. if ( this.cacheArcLengths
  16530. && ( this.cacheArcLengths.length == divisions + 1 )
  16531. && !this.needsUpdate) {
  16532. //console.log( "cached", this.cacheArcLengths );
  16533. return this.cacheArcLengths;
  16534. }
  16535. this.needsUpdate = false;
  16536. var cache = [];
  16537. var current, last = this.getPoint( 0 );
  16538. var p, sum = 0;
  16539. cache.push( 0 );
  16540. for ( p = 1; p <= divisions; p ++ ) {
  16541. current = this.getPoint ( p / divisions );
  16542. sum += current.distanceTo( last );
  16543. cache.push( sum );
  16544. last = current;
  16545. }
  16546. this.cacheArcLengths = cache;
  16547. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16548. };
  16549. THREE.Curve.prototype.updateArcLengths = function() {
  16550. this.needsUpdate = true;
  16551. this.getLengths();
  16552. };
  16553. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16554. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16555. var arcLengths = this.getLengths();
  16556. var i = 0, il = arcLengths.length;
  16557. var targetArcLength; // The targeted u distance value to get
  16558. if ( distance ) {
  16559. targetArcLength = distance;
  16560. } else {
  16561. targetArcLength = u * arcLengths[ il - 1 ];
  16562. }
  16563. //var time = Date.now();
  16564. // binary search for the index with largest value smaller than target u distance
  16565. var low = 0, high = il - 1, comparison;
  16566. while ( low <= high ) {
  16567. 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
  16568. comparison = arcLengths[ i ] - targetArcLength;
  16569. if ( comparison < 0 ) {
  16570. low = i + 1;
  16571. continue;
  16572. } else if ( comparison > 0 ) {
  16573. high = i - 1;
  16574. continue;
  16575. } else {
  16576. high = i;
  16577. break;
  16578. // DONE
  16579. }
  16580. }
  16581. i = high;
  16582. //console.log('b' , i, low, high, Date.now()- time);
  16583. if ( arcLengths[ i ] == targetArcLength ) {
  16584. var t = i / ( il - 1 );
  16585. return t;
  16586. }
  16587. // we could get finer grain at lengths, or use simple interpolatation between two points
  16588. var lengthBefore = arcLengths[ i ];
  16589. var lengthAfter = arcLengths[ i + 1 ];
  16590. var segmentLength = lengthAfter - lengthBefore;
  16591. // determine where we are between the 'before' and 'after' points
  16592. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16593. // add that fractional amount to t
  16594. var t = ( i + segmentFraction ) / ( il -1 );
  16595. return t;
  16596. };
  16597. // Returns a unit vector tangent at t
  16598. // In case any sub curve does not implement its tangent derivation,
  16599. // 2 points a small delta apart will be used to find its gradient
  16600. // which seems to give a reasonable approximation
  16601. THREE.Curve.prototype.getTangent = function( t ) {
  16602. var delta = 0.0001;
  16603. var t1 = t - delta;
  16604. var t2 = t + delta;
  16605. // Capping in case of danger
  16606. if ( t1 < 0 ) t1 = 0;
  16607. if ( t2 > 1 ) t2 = 1;
  16608. var pt1 = this.getPoint( t1 );
  16609. var pt2 = this.getPoint( t2 );
  16610. var vec = pt2.clone().subSelf(pt1);
  16611. return vec.normalize();
  16612. };
  16613. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16614. var t = this.getUtoTmapping( u );
  16615. return this.getTangent( t );
  16616. };
  16617. /**************************************************************
  16618. * Line
  16619. **************************************************************/
  16620. THREE.LineCurve = function ( v1, v2 ) {
  16621. this.v1 = v1;
  16622. this.v2 = v2;
  16623. };
  16624. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16625. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16626. var point = this.v2.clone().subSelf(this.v1);
  16627. point.multiplyScalar( t ).addSelf( this.v1 );
  16628. return point;
  16629. };
  16630. // Line curve is linear, so we can overwrite default getPointAt
  16631. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16632. return this.getPoint( u );
  16633. };
  16634. THREE.LineCurve.prototype.getTangent = function( t ) {
  16635. var tangent = this.v2.clone().subSelf(this.v1);
  16636. return tangent.normalize();
  16637. };
  16638. /**************************************************************
  16639. * Quadratic Bezier curve
  16640. **************************************************************/
  16641. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16642. this.v0 = v0;
  16643. this.v1 = v1;
  16644. this.v2 = v2;
  16645. };
  16646. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16647. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16648. var tx, ty;
  16649. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16650. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16651. return new THREE.Vector2( tx, ty );
  16652. };
  16653. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16654. var tx, ty;
  16655. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16656. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16657. // returns unit vector
  16658. var tangent = new THREE.Vector2( tx, ty );
  16659. tangent.normalize();
  16660. return tangent;
  16661. };
  16662. /**************************************************************
  16663. * Cubic Bezier curve
  16664. **************************************************************/
  16665. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16666. this.v0 = v0;
  16667. this.v1 = v1;
  16668. this.v2 = v2;
  16669. this.v3 = v3;
  16670. };
  16671. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16672. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16673. var tx, ty;
  16674. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16675. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16676. return new THREE.Vector2( tx, ty );
  16677. };
  16678. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16679. var tx, ty;
  16680. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16681. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16682. var tangent = new THREE.Vector2( tx, ty );
  16683. tangent.normalize();
  16684. return tangent;
  16685. };
  16686. /**************************************************************
  16687. * Spline curve
  16688. **************************************************************/
  16689. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16690. this.points = (points == undefined) ? [] : points;
  16691. };
  16692. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16693. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16694. var v = new THREE.Vector2();
  16695. var c = [];
  16696. var points = this.points, point, intPoint, weight;
  16697. point = ( points.length - 1 ) * t;
  16698. intPoint = Math.floor( point );
  16699. weight = point - intPoint;
  16700. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16701. c[ 1 ] = intPoint;
  16702. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16703. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16704. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16705. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16706. return v;
  16707. };
  16708. /**************************************************************
  16709. * Ellipse curve
  16710. **************************************************************/
  16711. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16712. aStartAngle, aEndAngle,
  16713. aClockwise ) {
  16714. this.aX = aX;
  16715. this.aY = aY;
  16716. this.xRadius = xRadius;
  16717. this.yRadius = yRadius;
  16718. this.aStartAngle = aStartAngle;
  16719. this.aEndAngle = aEndAngle;
  16720. this.aClockwise = aClockwise;
  16721. };
  16722. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16723. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16724. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16725. if ( !this.aClockwise ) {
  16726. t = 1 - t;
  16727. }
  16728. var angle = this.aStartAngle + t * deltaAngle;
  16729. var tx = this.aX + this.xRadius * Math.cos( angle );
  16730. var ty = this.aY + this.yRadius * Math.sin( angle );
  16731. return new THREE.Vector2( tx, ty );
  16732. };
  16733. /**************************************************************
  16734. * Arc curve
  16735. **************************************************************/
  16736. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16737. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16738. };
  16739. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16740. /**************************************************************
  16741. * Utils
  16742. **************************************************************/
  16743. THREE.Curve.Utils = {
  16744. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16745. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16746. },
  16747. // Puay Bing, thanks for helping with this derivative!
  16748. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16749. return -3 * p0 * (1 - t) * (1 - t) +
  16750. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16751. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16752. 3 * t * t * p3;
  16753. },
  16754. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16755. // To check if my formulas are correct
  16756. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16757. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16758. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16759. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16760. return h00 + h10 + h01 + h11;
  16761. },
  16762. // Catmull-Rom
  16763. interpolate: function( p0, p1, p2, p3, t ) {
  16764. var v0 = ( p2 - p0 ) * 0.5;
  16765. var v1 = ( p3 - p1 ) * 0.5;
  16766. var t2 = t * t;
  16767. var t3 = t * t2;
  16768. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16769. }
  16770. };
  16771. // TODO: Transformation for Curves?
  16772. /**************************************************************
  16773. * 3D Curves
  16774. **************************************************************/
  16775. // A Factory method for creating new curve subclasses
  16776. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16777. constructor.prototype = Object.create( THREE.Curve.prototype );
  16778. constructor.prototype.getPoint = getPointFunc;
  16779. return constructor;
  16780. };
  16781. /**************************************************************
  16782. * Line3D
  16783. **************************************************************/
  16784. THREE.LineCurve3 = THREE.Curve.create(
  16785. function ( v1, v2 ) {
  16786. this.v1 = v1;
  16787. this.v2 = v2;
  16788. },
  16789. function ( t ) {
  16790. var r = new THREE.Vector3();
  16791. r.sub( this.v2, this.v1 ); // diff
  16792. r.multiplyScalar( t );
  16793. r.addSelf( this.v1 );
  16794. return r;
  16795. }
  16796. );
  16797. /**************************************************************
  16798. * Quadratic Bezier 3D curve
  16799. **************************************************************/
  16800. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  16801. function ( v0, v1, v2 ) {
  16802. this.v0 = v0;
  16803. this.v1 = v1;
  16804. this.v2 = v2;
  16805. },
  16806. function ( t ) {
  16807. var tx, ty, tz;
  16808. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16809. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16810. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16811. return new THREE.Vector3( tx, ty, tz );
  16812. }
  16813. );
  16814. /**************************************************************
  16815. * Cubic Bezier 3D curve
  16816. **************************************************************/
  16817. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16818. function ( v0, v1, v2, v3 ) {
  16819. this.v0 = v0;
  16820. this.v1 = v1;
  16821. this.v2 = v2;
  16822. this.v3 = v3;
  16823. },
  16824. function ( t ) {
  16825. var tx, ty, tz;
  16826. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16827. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16828. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16829. return new THREE.Vector3( tx, ty, tz );
  16830. }
  16831. );
  16832. /**************************************************************
  16833. * Spline 3D curve
  16834. **************************************************************/
  16835. THREE.SplineCurve3 = THREE.Curve.create(
  16836. function ( points /* array of Vector3 */) {
  16837. this.points = (points == undefined) ? [] : points;
  16838. },
  16839. function ( t ) {
  16840. var v = new THREE.Vector3();
  16841. var c = [];
  16842. var points = this.points, point, intPoint, weight;
  16843. point = ( points.length - 1 ) * t;
  16844. intPoint = Math.floor( point );
  16845. weight = point - intPoint;
  16846. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16847. c[ 1 ] = intPoint;
  16848. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16849. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16850. var pt0 = points[ c[0] ],
  16851. pt1 = points[ c[1] ],
  16852. pt2 = points[ c[2] ],
  16853. pt3 = points[ c[3] ];
  16854. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16855. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16856. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16857. return v;
  16858. }
  16859. );
  16860. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16861. // var v = new THREE.Vector3();
  16862. // var c = [];
  16863. // var points = this.points, point, intPoint, weight;
  16864. // point = ( points.length - 1 ) * t;
  16865. // intPoint = Math.floor( point );
  16866. // weight = point - intPoint;
  16867. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16868. // c[ 1 ] = intPoint;
  16869. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16870. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16871. // var pt0 = points[ c[0] ],
  16872. // pt1 = points[ c[1] ],
  16873. // pt2 = points[ c[2] ],
  16874. // pt3 = points[ c[3] ];
  16875. // // t = weight;
  16876. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16877. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16878. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16879. // return v;
  16880. // }
  16881. /**************************************************************
  16882. * Closed Spline 3D curve
  16883. **************************************************************/
  16884. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16885. function ( points /* array of Vector3 */) {
  16886. this.points = (points == undefined) ? [] : points;
  16887. },
  16888. function ( t ) {
  16889. var v = new THREE.Vector3();
  16890. var c = [];
  16891. var points = this.points, point, intPoint, weight;
  16892. point = ( points.length - 0 ) * t;
  16893. // This needs to be from 0-length +1
  16894. intPoint = Math.floor( point );
  16895. weight = point - intPoint;
  16896. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16897. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16898. c[ 1 ] = ( intPoint ) % points.length;
  16899. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16900. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16901. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16902. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16903. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16904. return v;
  16905. }
  16906. );
  16907. /**
  16908. * @author zz85 / http://www.lab4games.net/zz85/blog
  16909. *
  16910. **/
  16911. /**************************************************************
  16912. * Curved Path - a curve path is simply a array of connected
  16913. * curves, but retains the api of a curve
  16914. **************************************************************/
  16915. THREE.CurvePath = function () {
  16916. this.curves = [];
  16917. this.bends = [];
  16918. this.autoClose = false; // Automatically closes the path
  16919. };
  16920. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16921. THREE.CurvePath.prototype.add = function ( curve ) {
  16922. this.curves.push( curve );
  16923. };
  16924. THREE.CurvePath.prototype.checkConnection = function() {
  16925. // TODO
  16926. // If the ending of curve is not connected to the starting
  16927. // or the next curve, then, this is not a real path
  16928. };
  16929. THREE.CurvePath.prototype.closePath = function() {
  16930. // TODO Test
  16931. // and verify for vector3 (needs to implement equals)
  16932. // Add a line curve if start and end of lines are not connected
  16933. var startPoint = this.curves[0].getPoint(0);
  16934. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16935. if (!startPoint.equals(endPoint)) {
  16936. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16937. }
  16938. };
  16939. // To get accurate point with reference to
  16940. // entire path distance at time t,
  16941. // following has to be done:
  16942. // 1. Length of each sub path have to be known
  16943. // 2. Locate and identify type of curve
  16944. // 3. Get t for the curve
  16945. // 4. Return curve.getPointAt(t')
  16946. THREE.CurvePath.prototype.getPoint = function( t ) {
  16947. var d = t * this.getLength();
  16948. var curveLengths = this.getCurveLengths();
  16949. var i = 0, diff, curve;
  16950. // To think about boundaries points.
  16951. while ( i < curveLengths.length ) {
  16952. if ( curveLengths[ i ] >= d ) {
  16953. diff = curveLengths[ i ] - d;
  16954. curve = this.curves[ i ];
  16955. var u = 1 - diff / curve.getLength();
  16956. return curve.getPointAt( u );
  16957. break;
  16958. }
  16959. i ++;
  16960. }
  16961. return null;
  16962. // loop where sum != 0, sum > d , sum+1 <d
  16963. };
  16964. /*
  16965. THREE.CurvePath.prototype.getTangent = function( t ) {
  16966. };*/
  16967. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16968. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16969. // getPoint() depends on getLength
  16970. THREE.CurvePath.prototype.getLength = function() {
  16971. var lens = this.getCurveLengths();
  16972. return lens[ lens.length - 1 ];
  16973. };
  16974. // Compute lengths and cache them
  16975. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16976. THREE.CurvePath.prototype.getCurveLengths = function() {
  16977. // We use cache values if curves and cache array are same length
  16978. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16979. return this.cacheLengths;
  16980. };
  16981. // Get length of subsurve
  16982. // Push sums into cached array
  16983. var lengths = [], sums = 0;
  16984. var i, il = this.curves.length;
  16985. for ( i = 0; i < il; i ++ ) {
  16986. sums += this.curves[ i ].getLength();
  16987. lengths.push( sums );
  16988. }
  16989. this.cacheLengths = lengths;
  16990. return lengths;
  16991. };
  16992. // Returns min and max coordinates, as well as centroid
  16993. THREE.CurvePath.prototype.getBoundingBox = function () {
  16994. var points = this.getPoints();
  16995. var maxX, maxY, maxZ;
  16996. var minX, minY, minZ;
  16997. maxX = maxY = Number.NEGATIVE_INFINITY;
  16998. minX = minY = Number.POSITIVE_INFINITY;
  16999. var p, i, il, sum;
  17000. var v3 = points[0] instanceof THREE.Vector3;
  17001. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  17002. for ( i = 0, il = points.length; i < il; i ++ ) {
  17003. p = points[ i ];
  17004. if ( p.x > maxX ) maxX = p.x;
  17005. else if ( p.x < minX ) minX = p.x;
  17006. if ( p.y > maxY ) maxY = p.y;
  17007. else if ( p.y < minY ) minY = p.y;
  17008. if (v3) {
  17009. if ( p.z > maxZ ) maxZ = p.z;
  17010. else if ( p.z < minZ ) minZ = p.z;
  17011. }
  17012. sum.addSelf( p );
  17013. }
  17014. var ret = {
  17015. minX: minX,
  17016. minY: minY,
  17017. maxX: maxX,
  17018. maxY: maxY,
  17019. centroid: sum.divideScalar( il )
  17020. };
  17021. if (v3) {
  17022. ret.maxZ = maxZ;
  17023. ret.minZ = minZ;
  17024. }
  17025. return ret;
  17026. };
  17027. /**************************************************************
  17028. * Create Geometries Helpers
  17029. **************************************************************/
  17030. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17031. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17032. var pts = this.getPoints( divisions, true );
  17033. return this.createGeometry( pts );
  17034. };
  17035. // Generate geometry from equidistance sampling along the path
  17036. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17037. var pts = this.getSpacedPoints( divisions, true );
  17038. return this.createGeometry( pts );
  17039. };
  17040. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17041. var geometry = new THREE.Geometry();
  17042. for ( var i = 0; i < points.length; i ++ ) {
  17043. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17044. }
  17045. return geometry;
  17046. };
  17047. /**************************************************************
  17048. * Bend / Wrap Helper Methods
  17049. **************************************************************/
  17050. // Wrap path / Bend modifiers?
  17051. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17052. this.bends.push( bendpath );
  17053. };
  17054. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17055. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17056. var i, il;
  17057. if ( !bends ) {
  17058. bends = this.bends;
  17059. }
  17060. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17061. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17062. }
  17063. return oldPts;
  17064. };
  17065. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17066. var oldPts = this.getSpacedPoints( segments );
  17067. var i, il;
  17068. if ( !bends ) {
  17069. bends = this.bends;
  17070. }
  17071. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17072. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17073. }
  17074. return oldPts;
  17075. };
  17076. // This returns getPoints() bend/wrapped around the contour of a path.
  17077. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17078. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17079. var bounds = this.getBoundingBox();
  17080. var i, il, p, oldX, oldY, xNorm;
  17081. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17082. p = oldPts[ i ];
  17083. oldX = p.x;
  17084. oldY = p.y;
  17085. xNorm = oldX / bounds.maxX;
  17086. // If using actual distance, for length > path, requires line extrusions
  17087. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17088. xNorm = path.getUtoTmapping( xNorm, oldX );
  17089. // check for out of bounds?
  17090. var pathPt = path.getPoint( xNorm );
  17091. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  17092. p.x = pathPt.x + normal.x;
  17093. p.y = pathPt.y + normal.y;
  17094. }
  17095. return oldPts;
  17096. };
  17097. /**
  17098. * @author alteredq / http://alteredqualia.com/
  17099. */
  17100. THREE.Gyroscope = function () {
  17101. THREE.Object3D.call( this );
  17102. };
  17103. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17104. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17105. this.matrixAutoUpdate && this.updateMatrix();
  17106. // update matrixWorld
  17107. if ( this.matrixWorldNeedsUpdate || force ) {
  17108. if ( this.parent ) {
  17109. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  17110. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  17111. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  17112. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  17113. } else {
  17114. this.matrixWorld.copy( this.matrix );
  17115. }
  17116. this.matrixWorldNeedsUpdate = false;
  17117. force = true;
  17118. }
  17119. // update children
  17120. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17121. this.children[ i ].updateMatrixWorld( force );
  17122. }
  17123. };
  17124. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17125. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17126. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  17127. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  17128. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17129. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17130. /**
  17131. * @author zz85 / http://www.lab4games.net/zz85/blog
  17132. * Creates free form 2d path using series of points, lines or curves.
  17133. *
  17134. **/
  17135. THREE.Path = function ( points ) {
  17136. THREE.CurvePath.call(this);
  17137. this.actions = [];
  17138. if ( points ) {
  17139. this.fromPoints( points );
  17140. }
  17141. };
  17142. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17143. THREE.PathActions = {
  17144. MOVE_TO: 'moveTo',
  17145. LINE_TO: 'lineTo',
  17146. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17147. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17148. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17149. ARC: 'arc', // Circle
  17150. ELLIPSE: 'ellipse'
  17151. };
  17152. // TODO Clean up PATH API
  17153. // Create path using straight lines to connect all points
  17154. // - vectors: array of Vector2
  17155. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17156. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17157. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17158. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17159. };
  17160. };
  17161. // startPath() endPath()?
  17162. THREE.Path.prototype.moveTo = function ( x, y ) {
  17163. var args = Array.prototype.slice.call( arguments );
  17164. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17165. };
  17166. THREE.Path.prototype.lineTo = function ( x, y ) {
  17167. var args = Array.prototype.slice.call( arguments );
  17168. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17169. var x0 = lastargs[ lastargs.length - 2 ];
  17170. var y0 = lastargs[ lastargs.length - 1 ];
  17171. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17172. this.curves.push( curve );
  17173. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17174. };
  17175. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17176. var args = Array.prototype.slice.call( arguments );
  17177. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17178. var x0 = lastargs[ lastargs.length - 2 ];
  17179. var y0 = lastargs[ lastargs.length - 1 ];
  17180. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17181. new THREE.Vector2( aCPx, aCPy ),
  17182. new THREE.Vector2( aX, aY ) );
  17183. this.curves.push( curve );
  17184. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17185. };
  17186. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17187. aCP2x, aCP2y,
  17188. aX, aY ) {
  17189. var args = Array.prototype.slice.call( arguments );
  17190. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17191. var x0 = lastargs[ lastargs.length - 2 ];
  17192. var y0 = lastargs[ lastargs.length - 1 ];
  17193. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17194. new THREE.Vector2( aCP1x, aCP1y ),
  17195. new THREE.Vector2( aCP2x, aCP2y ),
  17196. new THREE.Vector2( aX, aY ) );
  17197. this.curves.push( curve );
  17198. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17199. };
  17200. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17201. var args = Array.prototype.slice.call( arguments );
  17202. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17203. var x0 = lastargs[ lastargs.length - 2 ];
  17204. var y0 = lastargs[ lastargs.length - 1 ];
  17205. //---
  17206. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17207. Array.prototype.push.apply( npts, pts );
  17208. var curve = new THREE.SplineCurve( npts );
  17209. this.curves.push( curve );
  17210. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17211. };
  17212. // FUTURE: Change the API or follow canvas API?
  17213. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17214. aStartAngle, aEndAngle, aClockwise ) {
  17215. var lastargs = this.actions[ this.actions.length - 1].args;
  17216. var x0 = lastargs[ lastargs.length - 2 ];
  17217. var y0 = lastargs[ lastargs.length - 1 ];
  17218. this.absarc(aX + x0, aY + y0, aRadius,
  17219. aStartAngle, aEndAngle, aClockwise );
  17220. };
  17221. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17222. aStartAngle, aEndAngle, aClockwise ) {
  17223. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17224. };
  17225. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17226. aStartAngle, aEndAngle, aClockwise ) {
  17227. var lastargs = this.actions[ this.actions.length - 1].args;
  17228. var x0 = lastargs[ lastargs.length - 2 ];
  17229. var y0 = lastargs[ lastargs.length - 1 ];
  17230. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17231. aStartAngle, aEndAngle, aClockwise );
  17232. };
  17233. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17234. aStartAngle, aEndAngle, aClockwise ) {
  17235. var args = Array.prototype.slice.call( arguments );
  17236. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17237. aStartAngle, aEndAngle, aClockwise );
  17238. this.curves.push( curve );
  17239. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17240. args.push(lastPoint.x);
  17241. args.push(lastPoint.y);
  17242. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17243. };
  17244. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17245. if ( ! divisions ) divisions = 40;
  17246. var points = [];
  17247. for ( var i = 0; i < divisions; i ++ ) {
  17248. points.push( this.getPoint( i / divisions ) );
  17249. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17250. }
  17251. // if ( closedPath ) {
  17252. //
  17253. // points.push( points[ 0 ] );
  17254. //
  17255. // }
  17256. return points;
  17257. };
  17258. /* Return an array of vectors based on contour of the path */
  17259. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17260. if (this.useSpacedPoints) {
  17261. console.log('tata');
  17262. return this.getSpacedPoints( divisions, closedPath );
  17263. }
  17264. divisions = divisions || 12;
  17265. var points = [];
  17266. var i, il, item, action, args;
  17267. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17268. laste, j,
  17269. t, tx, ty;
  17270. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17271. item = this.actions[ i ];
  17272. action = item.action;
  17273. args = item.args;
  17274. switch( action ) {
  17275. case THREE.PathActions.MOVE_TO:
  17276. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17277. break;
  17278. case THREE.PathActions.LINE_TO:
  17279. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17280. break;
  17281. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17282. cpx = args[ 2 ];
  17283. cpy = args[ 3 ];
  17284. cpx1 = args[ 0 ];
  17285. cpy1 = args[ 1 ];
  17286. if ( points.length > 0 ) {
  17287. laste = points[ points.length - 1 ];
  17288. cpx0 = laste.x;
  17289. cpy0 = laste.y;
  17290. } else {
  17291. laste = this.actions[ i - 1 ].args;
  17292. cpx0 = laste[ laste.length - 2 ];
  17293. cpy0 = laste[ laste.length - 1 ];
  17294. }
  17295. for ( j = 1; j <= divisions; j ++ ) {
  17296. t = j / divisions;
  17297. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17298. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17299. points.push( new THREE.Vector2( tx, ty ) );
  17300. }
  17301. break;
  17302. case THREE.PathActions.BEZIER_CURVE_TO:
  17303. cpx = args[ 4 ];
  17304. cpy = args[ 5 ];
  17305. cpx1 = args[ 0 ];
  17306. cpy1 = args[ 1 ];
  17307. cpx2 = args[ 2 ];
  17308. cpy2 = args[ 3 ];
  17309. if ( points.length > 0 ) {
  17310. laste = points[ points.length - 1 ];
  17311. cpx0 = laste.x;
  17312. cpy0 = laste.y;
  17313. } else {
  17314. laste = this.actions[ i - 1 ].args;
  17315. cpx0 = laste[ laste.length - 2 ];
  17316. cpy0 = laste[ laste.length - 1 ];
  17317. }
  17318. for ( j = 1; j <= divisions; j ++ ) {
  17319. t = j / divisions;
  17320. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17321. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17322. points.push( new THREE.Vector2( tx, ty ) );
  17323. }
  17324. break;
  17325. case THREE.PathActions.CSPLINE_THRU:
  17326. laste = this.actions[ i - 1 ].args;
  17327. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17328. var spts = [ last ];
  17329. var n = divisions * args[ 0 ].length;
  17330. spts = spts.concat( args[ 0 ] );
  17331. var spline = new THREE.SplineCurve( spts );
  17332. for ( j = 1; j <= n; j ++ ) {
  17333. points.push( spline.getPointAt( j / n ) ) ;
  17334. }
  17335. break;
  17336. case THREE.PathActions.ARC:
  17337. var aX = args[ 0 ], aY = args[ 1 ],
  17338. aRadius = args[ 2 ],
  17339. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17340. aClockwise = !!args[ 5 ];
  17341. var deltaAngle = aEndAngle - aStartAngle;
  17342. var angle;
  17343. var tdivisions = divisions * 2;
  17344. for ( j = 1; j <= tdivisions; j ++ ) {
  17345. t = j / tdivisions;
  17346. if ( ! aClockwise ) {
  17347. t = 1 - t;
  17348. }
  17349. angle = aStartAngle + t * deltaAngle;
  17350. tx = aX + aRadius * Math.cos( angle );
  17351. ty = aY + aRadius * Math.sin( angle );
  17352. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17353. points.push( new THREE.Vector2( tx, ty ) );
  17354. }
  17355. //console.log(points);
  17356. break;
  17357. case THREE.PathActions.ELLIPSE:
  17358. var aX = args[ 0 ], aY = args[ 1 ],
  17359. xRadius = args[ 2 ],
  17360. yRadius = args[ 3 ],
  17361. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17362. aClockwise = !!args[ 6 ];
  17363. var deltaAngle = aEndAngle - aStartAngle;
  17364. var angle;
  17365. var tdivisions = divisions * 2;
  17366. for ( j = 1; j <= tdivisions; j ++ ) {
  17367. t = j / tdivisions;
  17368. if ( ! aClockwise ) {
  17369. t = 1 - t;
  17370. }
  17371. angle = aStartAngle + t * deltaAngle;
  17372. tx = aX + xRadius * Math.cos( angle );
  17373. ty = aY + yRadius * Math.sin( angle );
  17374. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17375. points.push( new THREE.Vector2( tx, ty ) );
  17376. }
  17377. //console.log(points);
  17378. break;
  17379. } // end switch
  17380. }
  17381. // Normalize to remove the closing point by default.
  17382. var lastPoint = points[ points.length - 1];
  17383. var EPSILON = 0.0000000001;
  17384. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17385. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17386. points.splice( points.length - 1, 1);
  17387. if ( closedPath ) {
  17388. points.push( points[ 0 ] );
  17389. }
  17390. return points;
  17391. };
  17392. // Breaks path into shapes
  17393. THREE.Path.prototype.toShapes = function() {
  17394. var i, il, item, action, args;
  17395. var subPaths = [], lastPath = new THREE.Path();
  17396. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17397. item = this.actions[ i ];
  17398. args = item.args;
  17399. action = item.action;
  17400. if ( action == THREE.PathActions.MOVE_TO ) {
  17401. if ( lastPath.actions.length != 0 ) {
  17402. subPaths.push( lastPath );
  17403. lastPath = new THREE.Path();
  17404. }
  17405. }
  17406. lastPath[ action ].apply( lastPath, args );
  17407. }
  17408. if ( lastPath.actions.length != 0 ) {
  17409. subPaths.push( lastPath );
  17410. }
  17411. // console.log(subPaths);
  17412. if ( subPaths.length == 0 ) return [];
  17413. var tmpPath, tmpShape, shapes = [];
  17414. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17415. // console.log("Holes first", holesFirst);
  17416. if ( subPaths.length == 1) {
  17417. tmpPath = subPaths[0];
  17418. tmpShape = new THREE.Shape();
  17419. tmpShape.actions = tmpPath.actions;
  17420. tmpShape.curves = tmpPath.curves;
  17421. shapes.push( tmpShape );
  17422. return shapes;
  17423. };
  17424. if ( holesFirst ) {
  17425. tmpShape = new THREE.Shape();
  17426. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17427. tmpPath = subPaths[ i ];
  17428. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17429. tmpShape.actions = tmpPath.actions;
  17430. tmpShape.curves = tmpPath.curves;
  17431. shapes.push( tmpShape );
  17432. tmpShape = new THREE.Shape();
  17433. //console.log('cw', i);
  17434. } else {
  17435. tmpShape.holes.push( tmpPath );
  17436. //console.log('ccw', i);
  17437. }
  17438. }
  17439. } else {
  17440. // Shapes first
  17441. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17442. tmpPath = subPaths[ i ];
  17443. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17444. if ( tmpShape ) shapes.push( tmpShape );
  17445. tmpShape = new THREE.Shape();
  17446. tmpShape.actions = tmpPath.actions;
  17447. tmpShape.curves = tmpPath.curves;
  17448. } else {
  17449. tmpShape.holes.push( tmpPath );
  17450. }
  17451. }
  17452. shapes.push( tmpShape );
  17453. }
  17454. //console.log("shape", shapes);
  17455. return shapes;
  17456. };
  17457. /**
  17458. * @author zz85 / http://www.lab4games.net/zz85/blog
  17459. * Defines a 2d shape plane using paths.
  17460. **/
  17461. // STEP 1 Create a path.
  17462. // STEP 2 Turn path into shape.
  17463. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17464. // STEP 3a - Extract points from each shape, turn to vertices
  17465. // STEP 3b - Triangulate each shape, add faces.
  17466. THREE.Shape = function ( ) {
  17467. THREE.Path.apply( this, arguments );
  17468. this.holes = [];
  17469. };
  17470. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17471. // Convenience method to return ExtrudeGeometry
  17472. THREE.Shape.prototype.extrude = function ( options ) {
  17473. var extruded = new THREE.ExtrudeGeometry( this, options );
  17474. return extruded;
  17475. };
  17476. // Convenience method to return ShapeGeometry
  17477. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17478. var geometry = new THREE.ShapeGeometry( this, options );
  17479. return geometry;
  17480. };
  17481. // Get points of holes
  17482. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17483. var i, il = this.holes.length, holesPts = [];
  17484. for ( i = 0; i < il; i ++ ) {
  17485. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17486. }
  17487. return holesPts;
  17488. };
  17489. // Get points of holes (spaced by regular distance)
  17490. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17491. var i, il = this.holes.length, holesPts = [];
  17492. for ( i = 0; i < il; i ++ ) {
  17493. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17494. }
  17495. return holesPts;
  17496. };
  17497. // Get points of shape and holes (keypoints based on segments parameter)
  17498. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17499. return {
  17500. shape: this.getTransformedPoints( divisions ),
  17501. holes: this.getPointsHoles( divisions )
  17502. };
  17503. };
  17504. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17505. if (this.useSpacedPoints) {
  17506. return this.extractAllSpacedPoints(divisions);
  17507. }
  17508. return this.extractAllPoints(divisions);
  17509. };
  17510. //
  17511. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17512. //
  17513. // return {
  17514. //
  17515. // shape: this.transform( bend, divisions ),
  17516. // holes: this.getPointsHoles( divisions, bend )
  17517. //
  17518. // };
  17519. //
  17520. // };
  17521. // Get points of shape and holes (spaced by regular distance)
  17522. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17523. return {
  17524. shape: this.getTransformedSpacedPoints( divisions ),
  17525. holes: this.getSpacedPointsHoles( divisions )
  17526. };
  17527. };
  17528. /**************************************************************
  17529. * Utils
  17530. **************************************************************/
  17531. THREE.Shape.Utils = {
  17532. /*
  17533. contour - array of vector2 for contour
  17534. holes - array of array of vector2
  17535. */
  17536. removeHoles: function ( contour, holes ) {
  17537. var shape = contour.concat(); // work on this shape
  17538. var allpoints = shape.concat();
  17539. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17540. var prevShapeVert, nextShapeVert,
  17541. prevHoleVert, nextHoleVert,
  17542. holeIndex, shapeIndex,
  17543. shapeId, shapeGroup,
  17544. h, h2,
  17545. hole, shortest, d,
  17546. p, pts1, pts2,
  17547. tmpShape1, tmpShape2,
  17548. tmpHole1, tmpHole2,
  17549. verts = [];
  17550. for ( h = 0; h < holes.length; h ++ ) {
  17551. hole = holes[ h ];
  17552. /*
  17553. shapeholes[ h ].concat(); // preserves original
  17554. holes.push( hole );
  17555. */
  17556. Array.prototype.push.apply( allpoints, hole );
  17557. shortest = Number.POSITIVE_INFINITY;
  17558. // Find the shortest pair of pts between shape and hole
  17559. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17560. // Using distanceToSquared() intead of distanceTo() should speed a little
  17561. // since running square roots operations are reduced.
  17562. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17563. pts1 = hole[ h2 ];
  17564. var dist = [];
  17565. for ( p = 0; p < shape.length; p++ ) {
  17566. pts2 = shape[ p ];
  17567. d = pts1.distanceToSquared( pts2 );
  17568. dist.push( d );
  17569. if ( d < shortest ) {
  17570. shortest = d;
  17571. holeIndex = h2;
  17572. shapeIndex = p;
  17573. }
  17574. }
  17575. }
  17576. //console.log("shortest", shortest, dist);
  17577. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17578. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17579. var areaapts = [
  17580. hole[ holeIndex ],
  17581. shape[ shapeIndex ],
  17582. shape[ prevShapeVert ]
  17583. ];
  17584. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17585. var areabpts = [
  17586. hole[ holeIndex ],
  17587. hole[ prevHoleVert ],
  17588. shape[ shapeIndex ]
  17589. ];
  17590. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17591. var shapeOffset = 1;
  17592. var holeOffset = -1;
  17593. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17594. shapeIndex += shapeOffset;
  17595. holeIndex += holeOffset;
  17596. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17597. shapeIndex %= shape.length;
  17598. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17599. holeIndex %= hole.length;
  17600. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17601. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17602. areaapts = [
  17603. hole[ holeIndex ],
  17604. shape[ shapeIndex ],
  17605. shape[ prevShapeVert ]
  17606. ];
  17607. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17608. areabpts = [
  17609. hole[ holeIndex ],
  17610. hole[ prevHoleVert ],
  17611. shape[ shapeIndex ]
  17612. ];
  17613. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17614. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17615. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17616. // In case areas are not correct.
  17617. //console.log("USE THIS");
  17618. shapeIndex = oldShapeIndex;
  17619. holeIndex = oldHoleIndex ;
  17620. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17621. shapeIndex %= shape.length;
  17622. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17623. holeIndex %= hole.length;
  17624. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17625. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17626. } else {
  17627. //console.log("USE THAT ")
  17628. }
  17629. tmpShape1 = shape.slice( 0, shapeIndex );
  17630. tmpShape2 = shape.slice( shapeIndex );
  17631. tmpHole1 = hole.slice( holeIndex );
  17632. tmpHole2 = hole.slice( 0, holeIndex );
  17633. // Should check orders here again?
  17634. var trianglea = [
  17635. hole[ holeIndex ],
  17636. shape[ shapeIndex ],
  17637. shape[ prevShapeVert ]
  17638. ];
  17639. var triangleb = [
  17640. hole[ holeIndex ] ,
  17641. hole[ prevHoleVert ],
  17642. shape[ shapeIndex ]
  17643. ];
  17644. verts.push( trianglea );
  17645. verts.push( triangleb );
  17646. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17647. }
  17648. return {
  17649. shape:shape, /* shape with no holes */
  17650. isolatedPts: verts, /* isolated faces */
  17651. allpoints: allpoints
  17652. }
  17653. },
  17654. triangulateShape: function ( contour, holes ) {
  17655. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17656. var shape = shapeWithoutHoles.shape,
  17657. allpoints = shapeWithoutHoles.allpoints,
  17658. isolatedPts = shapeWithoutHoles.isolatedPts;
  17659. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17660. // 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.
  17661. //console.log( "triangles",triangles, triangles.length );
  17662. //console.log( "allpoints",allpoints, allpoints.length );
  17663. var i, il, f, face,
  17664. key, index,
  17665. allPointsMap = {},
  17666. isolatedPointsMap = {};
  17667. // prepare all points map
  17668. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17669. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17670. if ( allPointsMap[ key ] !== undefined ) {
  17671. console.log( "Duplicate point", key );
  17672. }
  17673. allPointsMap[ key ] = i;
  17674. }
  17675. // check all face vertices against all points map
  17676. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17677. face = triangles[ i ];
  17678. for ( f = 0; f < 3; f ++ ) {
  17679. key = face[ f ].x + ":" + face[ f ].y;
  17680. index = allPointsMap[ key ];
  17681. if ( index !== undefined ) {
  17682. face[ f ] = index;
  17683. }
  17684. }
  17685. }
  17686. // check isolated points vertices against all points map
  17687. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17688. face = isolatedPts[ i ];
  17689. for ( f = 0; f < 3; f ++ ) {
  17690. key = face[ f ].x + ":" + face[ f ].y;
  17691. index = allPointsMap[ key ];
  17692. if ( index !== undefined ) {
  17693. face[ f ] = index;
  17694. }
  17695. }
  17696. }
  17697. return triangles.concat( isolatedPts );
  17698. }, // end triangulate shapes
  17699. /*
  17700. triangulate2 : function( pts, holes ) {
  17701. // For use with Poly2Tri.js
  17702. var allpts = pts.concat();
  17703. var shape = [];
  17704. for (var p in pts) {
  17705. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17706. }
  17707. var swctx = new js.poly2tri.SweepContext(shape);
  17708. for (var h in holes) {
  17709. var aHole = holes[h];
  17710. var newHole = []
  17711. for (i in aHole) {
  17712. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17713. allpts.push(aHole[i]);
  17714. }
  17715. swctx.AddHole(newHole);
  17716. }
  17717. var find;
  17718. var findIndexForPt = function (pt) {
  17719. find = new THREE.Vector2(pt.x, pt.y);
  17720. var p;
  17721. for (p=0, pl = allpts.length; p<pl; p++) {
  17722. if (allpts[p].equals(find)) return p;
  17723. }
  17724. return -1;
  17725. };
  17726. // triangulate
  17727. js.poly2tri.sweep.Triangulate(swctx);
  17728. var triangles = swctx.GetTriangles();
  17729. var tr ;
  17730. var facesPts = [];
  17731. for (var t in triangles) {
  17732. tr = triangles[t];
  17733. facesPts.push([
  17734. findIndexForPt(tr.GetPoint(0)),
  17735. findIndexForPt(tr.GetPoint(1)),
  17736. findIndexForPt(tr.GetPoint(2))
  17737. ]);
  17738. }
  17739. // console.log(facesPts);
  17740. // console.log("triangles", triangles.length, triangles);
  17741. // Returns array of faces with 3 element each
  17742. return facesPts;
  17743. },
  17744. */
  17745. isClockWise: function ( pts ) {
  17746. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17747. },
  17748. // Bezier Curves formulas obtained from
  17749. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17750. // Quad Bezier Functions
  17751. b2p0: function ( t, p ) {
  17752. var k = 1 - t;
  17753. return k * k * p;
  17754. },
  17755. b2p1: function ( t, p ) {
  17756. return 2 * ( 1 - t ) * t * p;
  17757. },
  17758. b2p2: function ( t, p ) {
  17759. return t * t * p;
  17760. },
  17761. b2: function ( t, p0, p1, p2 ) {
  17762. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17763. },
  17764. // Cubic Bezier Functions
  17765. b3p0: function ( t, p ) {
  17766. var k = 1 - t;
  17767. return k * k * k * p;
  17768. },
  17769. b3p1: function ( t, p ) {
  17770. var k = 1 - t;
  17771. return 3 * k * k * t * p;
  17772. },
  17773. b3p2: function ( t, p ) {
  17774. var k = 1 - t;
  17775. return 3 * k * t * t * p;
  17776. },
  17777. b3p3: function ( t, p ) {
  17778. return t * t * t * p;
  17779. },
  17780. b3: function ( t, p0, p1, p2, p3 ) {
  17781. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17782. }
  17783. };
  17784. /**
  17785. * @author mikael emtinger / http://gomo.se/
  17786. */
  17787. THREE.AnimationHandler = (function() {
  17788. var playing = [];
  17789. var library = {};
  17790. var that = {};
  17791. //--- update ---
  17792. that.update = function( deltaTimeMS ) {
  17793. for( var i = 0; i < playing.length; i ++ )
  17794. playing[ i ].update( deltaTimeMS );
  17795. };
  17796. //--- add ---
  17797. that.addToUpdate = function( animation ) {
  17798. if ( playing.indexOf( animation ) === -1 )
  17799. playing.push( animation );
  17800. };
  17801. //--- remove ---
  17802. that.removeFromUpdate = function( animation ) {
  17803. var index = playing.indexOf( animation );
  17804. if( index !== -1 )
  17805. playing.splice( index, 1 );
  17806. };
  17807. //--- add ---
  17808. that.add = function( data ) {
  17809. if ( library[ data.name ] !== undefined )
  17810. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17811. library[ data.name ] = data;
  17812. initData( data );
  17813. };
  17814. //--- get ---
  17815. that.get = function( name ) {
  17816. if ( typeof name === "string" ) {
  17817. if ( library[ name ] ) {
  17818. return library[ name ];
  17819. } else {
  17820. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17821. return null;
  17822. }
  17823. } else {
  17824. // todo: add simple tween library
  17825. }
  17826. };
  17827. //--- parse ---
  17828. that.parse = function( root ) {
  17829. // setup hierarchy
  17830. var hierarchy = [];
  17831. if ( root instanceof THREE.SkinnedMesh ) {
  17832. for( var b = 0; b < root.bones.length; b++ ) {
  17833. hierarchy.push( root.bones[ b ] );
  17834. }
  17835. } else {
  17836. parseRecurseHierarchy( root, hierarchy );
  17837. }
  17838. return hierarchy;
  17839. };
  17840. var parseRecurseHierarchy = function( root, hierarchy ) {
  17841. hierarchy.push( root );
  17842. for( var c = 0; c < root.children.length; c++ )
  17843. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17844. }
  17845. //--- init data ---
  17846. var initData = function( data ) {
  17847. if( data.initialized === true )
  17848. return;
  17849. // loop through all keys
  17850. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17851. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17852. // remove minus times
  17853. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17854. data.hierarchy[ h ].keys[ k ].time = 0;
  17855. // create quaternions
  17856. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17857. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17858. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17859. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17860. }
  17861. }
  17862. // prepare morph target keys
  17863. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17864. // get all used
  17865. var usedMorphTargets = {};
  17866. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17867. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17868. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17869. usedMorphTargets[ morphTargetName ] = -1;
  17870. }
  17871. }
  17872. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17873. // set all used on all frames
  17874. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17875. var influences = {};
  17876. for ( var morphTargetName in usedMorphTargets ) {
  17877. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17878. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17879. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17880. break;
  17881. }
  17882. }
  17883. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17884. influences[ morphTargetName ] = 0;
  17885. }
  17886. }
  17887. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17888. }
  17889. }
  17890. // remove all keys that are on the same time
  17891. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17892. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17893. data.hierarchy[ h ].keys.splice( k, 1 );
  17894. k --;
  17895. }
  17896. }
  17897. // set index
  17898. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17899. data.hierarchy[ h ].keys[ k ].index = k;
  17900. }
  17901. }
  17902. // JIT
  17903. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17904. data.JIT = {};
  17905. data.JIT.hierarchy = [];
  17906. for( var h = 0; h < data.hierarchy.length; h ++ )
  17907. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17908. // done
  17909. data.initialized = true;
  17910. };
  17911. // interpolation types
  17912. that.LINEAR = 0;
  17913. that.CATMULLROM = 1;
  17914. that.CATMULLROM_FORWARD = 2;
  17915. return that;
  17916. }());
  17917. /**
  17918. * @author mikael emtinger / http://gomo.se/
  17919. * @author mrdoob / http://mrdoob.com/
  17920. * @author alteredq / http://alteredqualia.com/
  17921. */
  17922. THREE.Animation = function ( root, name, interpolationType ) {
  17923. this.root = root;
  17924. this.data = THREE.AnimationHandler.get( name );
  17925. this.hierarchy = THREE.AnimationHandler.parse( root );
  17926. this.currentTime = 0;
  17927. this.timeScale = 1;
  17928. this.isPlaying = false;
  17929. this.isPaused = true;
  17930. this.loop = true;
  17931. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17932. this.points = [];
  17933. this.target = new THREE.Vector3();
  17934. };
  17935. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17936. if ( this.isPlaying === false ) {
  17937. this.isPlaying = true;
  17938. this.loop = loop !== undefined ? loop : true;
  17939. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17940. // reset key cache
  17941. var h, hl = this.hierarchy.length,
  17942. object;
  17943. for ( h = 0; h < hl; h ++ ) {
  17944. object = this.hierarchy[ h ];
  17945. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17946. object.useQuaternion = true;
  17947. }
  17948. object.matrixAutoUpdate = true;
  17949. if ( object.animationCache === undefined ) {
  17950. object.animationCache = {};
  17951. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17952. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17953. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17954. }
  17955. var prevKey = object.animationCache.prevKey;
  17956. var nextKey = object.animationCache.nextKey;
  17957. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17958. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17959. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17960. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17961. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17962. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17963. }
  17964. this.update( 0 );
  17965. }
  17966. this.isPaused = false;
  17967. THREE.AnimationHandler.addToUpdate( this );
  17968. };
  17969. THREE.Animation.prototype.pause = function() {
  17970. if ( this.isPaused === true ) {
  17971. THREE.AnimationHandler.addToUpdate( this );
  17972. } else {
  17973. THREE.AnimationHandler.removeFromUpdate( this );
  17974. }
  17975. this.isPaused = !this.isPaused;
  17976. };
  17977. THREE.Animation.prototype.stop = function() {
  17978. this.isPlaying = false;
  17979. this.isPaused = false;
  17980. THREE.AnimationHandler.removeFromUpdate( this );
  17981. };
  17982. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17983. // early out
  17984. if ( this.isPlaying === false ) return;
  17985. // vars
  17986. var types = [ "pos", "rot", "scl" ];
  17987. var type;
  17988. var scale;
  17989. var vector;
  17990. var prevXYZ, nextXYZ;
  17991. var prevKey, nextKey;
  17992. var object;
  17993. var animationCache;
  17994. var frame;
  17995. var JIThierarchy = this.data.JIT.hierarchy;
  17996. var currentTime, unloopedCurrentTime;
  17997. var currentPoint, forwardPoint, angle;
  17998. this.currentTime += deltaTimeMS * this.timeScale;
  17999. unloopedCurrentTime = this.currentTime;
  18000. currentTime = this.currentTime = this.currentTime % this.data.length;
  18001. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18002. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18003. object = this.hierarchy[ h ];
  18004. animationCache = object.animationCache;
  18005. // loop through pos/rot/scl
  18006. for ( var t = 0; t < 3; t ++ ) {
  18007. // get keys
  18008. type = types[ t ];
  18009. prevKey = animationCache.prevKey[ type ];
  18010. nextKey = animationCache.nextKey[ type ];
  18011. // switch keys?
  18012. if ( nextKey.time <= unloopedCurrentTime ) {
  18013. // did we loop?
  18014. if ( currentTime < unloopedCurrentTime ) {
  18015. if ( this.loop ) {
  18016. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18017. nextKey = this.getNextKeyWith( type, h, 1 );
  18018. while( nextKey.time < currentTime ) {
  18019. prevKey = nextKey;
  18020. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18021. }
  18022. } else {
  18023. this.stop();
  18024. return;
  18025. }
  18026. } else {
  18027. do {
  18028. prevKey = nextKey;
  18029. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18030. } while( nextKey.time < currentTime )
  18031. }
  18032. animationCache.prevKey[ type ] = prevKey;
  18033. animationCache.nextKey[ type ] = nextKey;
  18034. }
  18035. object.matrixAutoUpdate = true;
  18036. object.matrixWorldNeedsUpdate = true;
  18037. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18038. prevXYZ = prevKey[ type ];
  18039. nextXYZ = nextKey[ type ];
  18040. // check scale error
  18041. if ( scale < 0 || scale > 1 ) {
  18042. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18043. scale = scale < 0 ? 0 : 1;
  18044. }
  18045. // interpolate
  18046. if ( type === "pos" ) {
  18047. vector = object.position;
  18048. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18049. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18050. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18051. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18052. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18053. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18054. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18055. this.points[ 1 ] = prevXYZ;
  18056. this.points[ 2 ] = nextXYZ;
  18057. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18058. scale = scale * 0.33 + 0.33;
  18059. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18060. vector.x = currentPoint[ 0 ];
  18061. vector.y = currentPoint[ 1 ];
  18062. vector.z = currentPoint[ 2 ];
  18063. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18064. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18065. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18066. this.target.subSelf( vector );
  18067. this.target.y = 0;
  18068. this.target.normalize();
  18069. angle = Math.atan2( this.target.x, this.target.z );
  18070. object.rotation.set( 0, angle, 0 );
  18071. }
  18072. }
  18073. } else if ( type === "rot" ) {
  18074. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18075. } else if ( type === "scl" ) {
  18076. vector = object.scale;
  18077. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18078. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18079. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18080. }
  18081. }
  18082. }
  18083. };
  18084. // Catmull-Rom spline
  18085. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18086. var c = [], v3 = [],
  18087. point, intPoint, weight, w2, w3,
  18088. pa, pb, pc, pd;
  18089. point = ( points.length - 1 ) * scale;
  18090. intPoint = Math.floor( point );
  18091. weight = point - intPoint;
  18092. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18093. c[ 1 ] = intPoint;
  18094. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18095. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18096. pa = points[ c[ 0 ] ];
  18097. pb = points[ c[ 1 ] ];
  18098. pc = points[ c[ 2 ] ];
  18099. pd = points[ c[ 3 ] ];
  18100. w2 = weight * weight;
  18101. w3 = weight * w2;
  18102. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18103. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18104. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18105. return v3;
  18106. };
  18107. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18108. var v0 = ( p2 - p0 ) * 0.5,
  18109. v1 = ( p3 - p1 ) * 0.5;
  18110. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18111. };
  18112. // Get next key with
  18113. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18114. var keys = this.data.hierarchy[ h ].keys;
  18115. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18116. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18117. key = key < keys.length - 1 ? key : keys.length - 1;
  18118. } else {
  18119. key = key % keys.length;
  18120. }
  18121. for ( ; key < keys.length; key++ ) {
  18122. if ( keys[ key ][ type ] !== undefined ) {
  18123. return keys[ key ];
  18124. }
  18125. }
  18126. return this.data.hierarchy[ h ].keys[ 0 ];
  18127. };
  18128. // Get previous key with
  18129. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18130. var keys = this.data.hierarchy[ h ].keys;
  18131. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18132. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18133. key = key > 0 ? key : 0;
  18134. } else {
  18135. key = key >= 0 ? key : key + keys.length;
  18136. }
  18137. for ( ; key >= 0; key -- ) {
  18138. if ( keys[ key ][ type ] !== undefined ) {
  18139. return keys[ key ];
  18140. }
  18141. }
  18142. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18143. };
  18144. /**
  18145. * @author mikael emtinger / http://gomo.se/
  18146. * @author mrdoob / http://mrdoob.com/
  18147. * @author alteredq / http://alteredqualia.com/
  18148. * @author khang duong
  18149. * @author erik kitson
  18150. */
  18151. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18152. this.root = root;
  18153. this.data = THREE.AnimationHandler.get( data );
  18154. this.hierarchy = THREE.AnimationHandler.parse( root );
  18155. this.currentTime = 0;
  18156. this.timeScale = 0.001;
  18157. this.isPlaying = false;
  18158. this.isPaused = true;
  18159. this.loop = true;
  18160. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18161. // initialize to first keyframes
  18162. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18163. var keys = this.data.hierarchy[h].keys,
  18164. sids = this.data.hierarchy[h].sids,
  18165. obj = this.hierarchy[h];
  18166. if ( keys.length && sids ) {
  18167. for ( var s = 0; s < sids.length; s++ ) {
  18168. var sid = sids[ s ],
  18169. next = this.getNextKeyWith( sid, h, 0 );
  18170. if ( next ) {
  18171. next.apply( sid );
  18172. }
  18173. }
  18174. obj.matrixAutoUpdate = false;
  18175. this.data.hierarchy[h].node.updateMatrix();
  18176. obj.matrixWorldNeedsUpdate = true;
  18177. }
  18178. }
  18179. };
  18180. // Play
  18181. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18182. if( !this.isPlaying ) {
  18183. this.isPlaying = true;
  18184. this.loop = loop !== undefined ? loop : true;
  18185. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18186. this.startTimeMs = startTimeMS;
  18187. this.startTime = 10000000;
  18188. this.endTime = -this.startTime;
  18189. // reset key cache
  18190. var h, hl = this.hierarchy.length,
  18191. object,
  18192. node;
  18193. for ( h = 0; h < hl; h++ ) {
  18194. object = this.hierarchy[ h ];
  18195. node = this.data.hierarchy[ h ];
  18196. object.useQuaternion = true;
  18197. if ( node.animationCache === undefined ) {
  18198. node.animationCache = {};
  18199. node.animationCache.prevKey = null;
  18200. node.animationCache.nextKey = null;
  18201. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18202. }
  18203. var keys = this.data.hierarchy[h].keys;
  18204. if (keys.length) {
  18205. node.animationCache.prevKey = keys[ 0 ];
  18206. node.animationCache.nextKey = keys[ 1 ];
  18207. this.startTime = Math.min( keys[0].time, this.startTime );
  18208. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18209. }
  18210. }
  18211. this.update( 0 );
  18212. }
  18213. this.isPaused = false;
  18214. THREE.AnimationHandler.addToUpdate( this );
  18215. };
  18216. // Pause
  18217. THREE.KeyFrameAnimation.prototype.pause = function() {
  18218. if( this.isPaused ) {
  18219. THREE.AnimationHandler.addToUpdate( this );
  18220. } else {
  18221. THREE.AnimationHandler.removeFromUpdate( this );
  18222. }
  18223. this.isPaused = !this.isPaused;
  18224. };
  18225. // Stop
  18226. THREE.KeyFrameAnimation.prototype.stop = function() {
  18227. this.isPlaying = false;
  18228. this.isPaused = false;
  18229. THREE.AnimationHandler.removeFromUpdate( this );
  18230. // reset JIT matrix and remove cache
  18231. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18232. var obj = this.hierarchy[ h ];
  18233. var node = this.data.hierarchy[ h ];
  18234. if ( node.animationCache !== undefined ) {
  18235. var original = node.animationCache.originalMatrix;
  18236. if( obj instanceof THREE.Bone ) {
  18237. original.copy( obj.skinMatrix );
  18238. obj.skinMatrix = original;
  18239. } else {
  18240. original.copy( obj.matrix );
  18241. obj.matrix = original;
  18242. }
  18243. delete node.animationCache;
  18244. }
  18245. }
  18246. };
  18247. // Update
  18248. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18249. // early out
  18250. if( !this.isPlaying ) return;
  18251. // vars
  18252. var prevKey, nextKey;
  18253. var object;
  18254. var node;
  18255. var frame;
  18256. var JIThierarchy = this.data.JIT.hierarchy;
  18257. var currentTime, unloopedCurrentTime;
  18258. var looped;
  18259. // update
  18260. this.currentTime += deltaTimeMS * this.timeScale;
  18261. unloopedCurrentTime = this.currentTime;
  18262. currentTime = this.currentTime = this.currentTime % this.data.length;
  18263. // if looped around, the current time should be based on the startTime
  18264. if ( currentTime < this.startTimeMs ) {
  18265. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18266. }
  18267. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18268. looped = currentTime < unloopedCurrentTime;
  18269. if ( looped && !this.loop ) {
  18270. // Set the animation to the last keyframes and stop
  18271. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18272. var keys = this.data.hierarchy[h].keys,
  18273. sids = this.data.hierarchy[h].sids,
  18274. end = keys.length-1,
  18275. obj = this.hierarchy[h];
  18276. if ( keys.length ) {
  18277. for ( var s = 0; s < sids.length; s++ ) {
  18278. var sid = sids[ s ],
  18279. prev = this.getPrevKeyWith( sid, h, end );
  18280. if ( prev ) {
  18281. prev.apply( sid );
  18282. }
  18283. }
  18284. this.data.hierarchy[h].node.updateMatrix();
  18285. obj.matrixWorldNeedsUpdate = true;
  18286. }
  18287. }
  18288. this.stop();
  18289. return;
  18290. }
  18291. // check pre-infinity
  18292. if ( currentTime < this.startTime ) {
  18293. return;
  18294. }
  18295. // update
  18296. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18297. object = this.hierarchy[ h ];
  18298. node = this.data.hierarchy[ h ];
  18299. var keys = node.keys,
  18300. animationCache = node.animationCache;
  18301. // use JIT?
  18302. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18303. if( object instanceof THREE.Bone ) {
  18304. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18305. object.matrixWorldNeedsUpdate = false;
  18306. } else {
  18307. object.matrix = JIThierarchy[ h ][ frame ];
  18308. object.matrixWorldNeedsUpdate = true;
  18309. }
  18310. // use interpolation
  18311. } else if ( keys.length ) {
  18312. // make sure so original matrix and not JIT matrix is set
  18313. if ( this.JITCompile && animationCache ) {
  18314. if( object instanceof THREE.Bone ) {
  18315. object.skinMatrix = animationCache.originalMatrix;
  18316. } else {
  18317. object.matrix = animationCache.originalMatrix;
  18318. }
  18319. }
  18320. prevKey = animationCache.prevKey;
  18321. nextKey = animationCache.nextKey;
  18322. if ( prevKey && nextKey ) {
  18323. // switch keys?
  18324. if ( nextKey.time <= unloopedCurrentTime ) {
  18325. // did we loop?
  18326. if ( looped && this.loop ) {
  18327. prevKey = keys[ 0 ];
  18328. nextKey = keys[ 1 ];
  18329. while ( nextKey.time < currentTime ) {
  18330. prevKey = nextKey;
  18331. nextKey = keys[ prevKey.index + 1 ];
  18332. }
  18333. } else if ( !looped ) {
  18334. var lastIndex = keys.length - 1;
  18335. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18336. prevKey = nextKey;
  18337. nextKey = keys[ prevKey.index + 1 ];
  18338. }
  18339. }
  18340. animationCache.prevKey = prevKey;
  18341. animationCache.nextKey = nextKey;
  18342. }
  18343. if(nextKey.time >= currentTime)
  18344. prevKey.interpolate( nextKey, currentTime );
  18345. else
  18346. prevKey.interpolate( nextKey, nextKey.time);
  18347. }
  18348. this.data.hierarchy[h].node.updateMatrix();
  18349. object.matrixWorldNeedsUpdate = true;
  18350. }
  18351. }
  18352. // update JIT?
  18353. if ( this.JITCompile ) {
  18354. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18355. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18356. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18357. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18358. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18359. } else {
  18360. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18361. }
  18362. }
  18363. }
  18364. }
  18365. };
  18366. // Get next key with
  18367. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18368. var keys = this.data.hierarchy[ h ].keys;
  18369. key = key % keys.length;
  18370. for ( ; key < keys.length; key++ ) {
  18371. if ( keys[ key ].hasTarget( sid ) ) {
  18372. return keys[ key ];
  18373. }
  18374. }
  18375. return keys[ 0 ];
  18376. };
  18377. // Get previous key with
  18378. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18379. var keys = this.data.hierarchy[ h ].keys;
  18380. key = key >= 0 ? key : key + keys.length;
  18381. for ( ; key >= 0; key-- ) {
  18382. if ( keys[ key ].hasTarget( sid ) ) {
  18383. return keys[ key ];
  18384. }
  18385. }
  18386. return keys[ keys.length - 1 ];
  18387. };
  18388. /**
  18389. * Camera for rendering cube maps
  18390. * - renders scene into axis-aligned cube
  18391. *
  18392. * @author alteredq / http://alteredqualia.com/
  18393. */
  18394. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18395. THREE.Object3D.call( this );
  18396. var fov = 90, aspect = 1;
  18397. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18398. cameraPX.up.set( 0, -1, 0 );
  18399. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18400. this.add( cameraPX );
  18401. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18402. cameraNX.up.set( 0, -1, 0 );
  18403. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18404. this.add( cameraNX );
  18405. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18406. cameraPY.up.set( 0, 0, 1 );
  18407. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18408. this.add( cameraPY );
  18409. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18410. cameraNY.up.set( 0, 0, -1 );
  18411. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18412. this.add( cameraNY );
  18413. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18414. cameraPZ.up.set( 0, -1, 0 );
  18415. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18416. this.add( cameraPZ );
  18417. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18418. cameraNZ.up.set( 0, -1, 0 );
  18419. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18420. this.add( cameraNZ );
  18421. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18422. this.updateCubeMap = function ( renderer, scene ) {
  18423. var renderTarget = this.renderTarget;
  18424. var generateMipmaps = renderTarget.generateMipmaps;
  18425. renderTarget.generateMipmaps = false;
  18426. renderTarget.activeCubeFace = 0;
  18427. renderer.render( scene, cameraPX, renderTarget );
  18428. renderTarget.activeCubeFace = 1;
  18429. renderer.render( scene, cameraNX, renderTarget );
  18430. renderTarget.activeCubeFace = 2;
  18431. renderer.render( scene, cameraPY, renderTarget );
  18432. renderTarget.activeCubeFace = 3;
  18433. renderer.render( scene, cameraNY, renderTarget );
  18434. renderTarget.activeCubeFace = 4;
  18435. renderer.render( scene, cameraPZ, renderTarget );
  18436. renderTarget.generateMipmaps = generateMipmaps;
  18437. renderTarget.activeCubeFace = 5;
  18438. renderer.render( scene, cameraNZ, renderTarget );
  18439. };
  18440. };
  18441. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18442. /*
  18443. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18444. *
  18445. * A general perpose camera, for setting FOV, Lens Focal Length,
  18446. * and switching between perspective and orthographic views easily.
  18447. * Use this only if you do not wish to manage
  18448. * both a Orthographic and Perspective Camera
  18449. *
  18450. */
  18451. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18452. THREE.Camera.call( this );
  18453. this.fov = fov;
  18454. this.left = -width / 2;
  18455. this.right = width / 2
  18456. this.top = height / 2;
  18457. this.bottom = -height / 2;
  18458. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18459. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18460. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18461. this.zoom = 1;
  18462. this.toPerspective();
  18463. var aspect = width/height;
  18464. };
  18465. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18466. THREE.CombinedCamera.prototype.toPerspective = function () {
  18467. // Switches to the Perspective Camera
  18468. this.near = this.cameraP.near;
  18469. this.far = this.cameraP.far;
  18470. this.cameraP.fov = this.fov / this.zoom ;
  18471. this.cameraP.updateProjectionMatrix();
  18472. this.projectionMatrix = this.cameraP.projectionMatrix;
  18473. this.inPerspectiveMode = true;
  18474. this.inOrthographicMode = false;
  18475. };
  18476. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18477. // Switches to the Orthographic camera estimating viewport from Perspective
  18478. var fov = this.fov;
  18479. var aspect = this.cameraP.aspect;
  18480. var near = this.cameraP.near;
  18481. var far = this.cameraP.far;
  18482. // The size that we set is the mid plane of the viewing frustum
  18483. var hyperfocus = ( near + far ) / 2;
  18484. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18485. var planeHeight = 2 * halfHeight;
  18486. var planeWidth = planeHeight * aspect;
  18487. var halfWidth = planeWidth / 2;
  18488. halfHeight /= this.zoom;
  18489. halfWidth /= this.zoom;
  18490. this.cameraO.left = -halfWidth;
  18491. this.cameraO.right = halfWidth;
  18492. this.cameraO.top = halfHeight;
  18493. this.cameraO.bottom = -halfHeight;
  18494. // this.cameraO.left = -farHalfWidth;
  18495. // this.cameraO.right = farHalfWidth;
  18496. // this.cameraO.top = farHalfHeight;
  18497. // this.cameraO.bottom = -farHalfHeight;
  18498. // this.cameraO.left = this.left / this.zoom;
  18499. // this.cameraO.right = this.right / this.zoom;
  18500. // this.cameraO.top = this.top / this.zoom;
  18501. // this.cameraO.bottom = this.bottom / this.zoom;
  18502. this.cameraO.updateProjectionMatrix();
  18503. this.near = this.cameraO.near;
  18504. this.far = this.cameraO.far;
  18505. this.projectionMatrix = this.cameraO.projectionMatrix;
  18506. this.inPerspectiveMode = false;
  18507. this.inOrthographicMode = true;
  18508. };
  18509. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18510. this.cameraP.aspect = width / height;
  18511. this.left = -width / 2;
  18512. this.right = width / 2
  18513. this.top = height / 2;
  18514. this.bottom = -height / 2;
  18515. };
  18516. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18517. this.fov = fov;
  18518. if ( this.inPerspectiveMode ) {
  18519. this.toPerspective();
  18520. } else {
  18521. this.toOrthographic();
  18522. }
  18523. };
  18524. // For mantaining similar API with PerspectiveCamera
  18525. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18526. if ( this.inPerspectiveMode ) {
  18527. this.toPerspective();
  18528. } else {
  18529. this.toPerspective();
  18530. this.toOrthographic();
  18531. }
  18532. };
  18533. /*
  18534. * Uses Focal Length (in mm) to estimate and set FOV
  18535. * 35mm (fullframe) camera is used if frame size is not specified;
  18536. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18537. */
  18538. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18539. if ( frameHeight === undefined ) frameHeight = 24;
  18540. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  18541. this.setFov( fov );
  18542. return fov;
  18543. };
  18544. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18545. this.zoom = zoom;
  18546. if ( this.inPerspectiveMode ) {
  18547. this.toPerspective();
  18548. } else {
  18549. this.toOrthographic();
  18550. }
  18551. };
  18552. THREE.CombinedCamera.prototype.toFrontView = function() {
  18553. this.rotation.x = 0;
  18554. this.rotation.y = 0;
  18555. this.rotation.z = 0;
  18556. // should we be modifing the matrix instead?
  18557. this.rotationAutoUpdate = false;
  18558. };
  18559. THREE.CombinedCamera.prototype.toBackView = function() {
  18560. this.rotation.x = 0;
  18561. this.rotation.y = Math.PI;
  18562. this.rotation.z = 0;
  18563. this.rotationAutoUpdate = false;
  18564. };
  18565. THREE.CombinedCamera.prototype.toLeftView = function() {
  18566. this.rotation.x = 0;
  18567. this.rotation.y = - Math.PI / 2;
  18568. this.rotation.z = 0;
  18569. this.rotationAutoUpdate = false;
  18570. };
  18571. THREE.CombinedCamera.prototype.toRightView = function() {
  18572. this.rotation.x = 0;
  18573. this.rotation.y = Math.PI / 2;
  18574. this.rotation.z = 0;
  18575. this.rotationAutoUpdate = false;
  18576. };
  18577. THREE.CombinedCamera.prototype.toTopView = function() {
  18578. this.rotation.x = - Math.PI / 2;
  18579. this.rotation.y = 0;
  18580. this.rotation.z = 0;
  18581. this.rotationAutoUpdate = false;
  18582. };
  18583. THREE.CombinedCamera.prototype.toBottomView = function() {
  18584. this.rotation.x = Math.PI / 2;
  18585. this.rotation.y = 0;
  18586. this.rotation.z = 0;
  18587. this.rotationAutoUpdate = false;
  18588. };
  18589. /**
  18590. * @author alteredq / http://alteredqualia.com/
  18591. *
  18592. * - 3d asterisk shape (for line pieces THREE.Line)
  18593. */
  18594. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  18595. THREE.Geometry.call( this );
  18596. var sd = innerRadius;
  18597. var ed = outerRadius;
  18598. var sd2 = 0.707 * sd;
  18599. var ed2 = 0.707 * ed;
  18600. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  18601. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  18602. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  18603. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  18604. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  18605. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  18606. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  18607. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  18608. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  18609. ];
  18610. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  18611. var x = rays[ i ][ 0 ];
  18612. var y = rays[ i ][ 1 ];
  18613. var z = rays[ i ][ 2 ];
  18614. this.vertices.push( new THREE.Vector3( x, y, z ) );
  18615. }
  18616. };
  18617. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  18618. * @author hughes
  18619. */
  18620. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18621. THREE.Geometry.call( this );
  18622. radius = radius || 50;
  18623. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18624. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18625. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18626. var i, uvs = [],
  18627. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18628. this.vertices.push(center);
  18629. uvs.push( centerUV );
  18630. for ( i = 0; i <= segments; i ++ ) {
  18631. var vertex = new THREE.Vector3();
  18632. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  18633. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  18634. this.vertices.push( vertex );
  18635. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  18636. }
  18637. var n = new THREE.Vector3( 0, 0, -1 );
  18638. for ( i = 1; i <= segments; i ++ ) {
  18639. var v1 = i;
  18640. var v2 = i + 1 ;
  18641. var v3 = 0;
  18642. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18643. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18644. }
  18645. this.computeCentroids();
  18646. this.computeFaceNormals();
  18647. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18648. };
  18649. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18650. /**
  18651. * @author mrdoob / http://mrdoob.com/
  18652. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18653. */
  18654. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18655. THREE.Geometry.call( this );
  18656. var scope = this;
  18657. this.width = width;
  18658. this.height = height;
  18659. this.depth = depth;
  18660. this.widthSegments = widthSegments || 1;
  18661. this.heightSegments = heightSegments || 1;
  18662. this.depthSegments = depthSegments || 1;
  18663. var width_half = this.width / 2;
  18664. var height_half = this.height / 2;
  18665. var depth_half = this.depth / 2;
  18666. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18667. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18668. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18669. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18670. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18671. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18672. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18673. var w, ix, iy,
  18674. gridX = scope.widthSegments,
  18675. gridY = scope.heightSegments,
  18676. width_half = width / 2,
  18677. height_half = height / 2,
  18678. offset = scope.vertices.length;
  18679. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18680. w = 'z';
  18681. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18682. w = 'y';
  18683. gridY = scope.depthSegments;
  18684. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18685. w = 'x';
  18686. gridX = scope.depthSegments;
  18687. }
  18688. var gridX1 = gridX + 1,
  18689. gridY1 = gridY + 1,
  18690. segment_width = width / gridX,
  18691. segment_height = height / gridY,
  18692. normal = new THREE.Vector3();
  18693. normal[ w ] = depth > 0 ? 1 : - 1;
  18694. for ( iy = 0; iy < gridY1; iy ++ ) {
  18695. for ( ix = 0; ix < gridX1; ix ++ ) {
  18696. var vector = new THREE.Vector3();
  18697. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18698. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18699. vector[ w ] = depth;
  18700. scope.vertices.push( vector );
  18701. }
  18702. }
  18703. for ( iy = 0; iy < gridY; iy++ ) {
  18704. for ( ix = 0; ix < gridX; ix++ ) {
  18705. var a = ix + gridX1 * iy;
  18706. var b = ix + gridX1 * ( iy + 1 );
  18707. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18708. var d = ( ix + 1 ) + gridX1 * iy;
  18709. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18710. face.normal.copy( normal );
  18711. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18712. face.materialIndex = materialIndex;
  18713. scope.faces.push( face );
  18714. scope.faceVertexUvs[ 0 ].push( [
  18715. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18716. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18717. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18718. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18719. ] );
  18720. }
  18721. }
  18722. }
  18723. this.computeCentroids();
  18724. this.mergeVertices();
  18725. };
  18726. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18727. /**
  18728. * @author mrdoob / http://mrdoob.com/
  18729. */
  18730. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18731. THREE.Geometry.call( this );
  18732. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18733. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18734. height = height !== undefined ? height : 100;
  18735. var heightHalf = height / 2;
  18736. var segmentsX = radiusSegments || 8;
  18737. var segmentsY = heightSegments || 1;
  18738. var x, y, vertices = [], uvs = [];
  18739. for ( y = 0; y <= segmentsY; y ++ ) {
  18740. var verticesRow = [];
  18741. var uvsRow = [];
  18742. var v = y / segmentsY;
  18743. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18744. for ( x = 0; x <= segmentsX; x ++ ) {
  18745. var u = x / segmentsX;
  18746. var vertex = new THREE.Vector3();
  18747. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18748. vertex.y = - v * height + heightHalf;
  18749. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18750. this.vertices.push( vertex );
  18751. verticesRow.push( this.vertices.length - 1 );
  18752. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18753. }
  18754. vertices.push( verticesRow );
  18755. uvs.push( uvsRow );
  18756. }
  18757. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18758. var na, nb;
  18759. for ( x = 0; x < segmentsX; x ++ ) {
  18760. if ( radiusTop !== 0 ) {
  18761. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18762. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18763. } else {
  18764. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18765. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18766. }
  18767. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18768. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18769. for ( y = 0; y < segmentsY; y ++ ) {
  18770. var v1 = vertices[ y ][ x ];
  18771. var v2 = vertices[ y + 1 ][ x ];
  18772. var v3 = vertices[ y + 1 ][ x + 1 ];
  18773. var v4 = vertices[ y ][ x + 1 ];
  18774. var n1 = na.clone();
  18775. var n2 = na.clone();
  18776. var n3 = nb.clone();
  18777. var n4 = nb.clone();
  18778. var uv1 = uvs[ y ][ x ].clone();
  18779. var uv2 = uvs[ y + 1 ][ x ].clone();
  18780. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18781. var uv4 = uvs[ y ][ x + 1 ].clone();
  18782. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18783. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18784. }
  18785. }
  18786. // top cap
  18787. if ( !openEnded && radiusTop > 0 ) {
  18788. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18789. for ( x = 0; x < segmentsX; x ++ ) {
  18790. var v1 = vertices[ 0 ][ x ];
  18791. var v2 = vertices[ 0 ][ x + 1 ];
  18792. var v3 = this.vertices.length - 1;
  18793. var n1 = new THREE.Vector3( 0, 1, 0 );
  18794. var n2 = new THREE.Vector3( 0, 1, 0 );
  18795. var n3 = new THREE.Vector3( 0, 1, 0 );
  18796. var uv1 = uvs[ 0 ][ x ].clone();
  18797. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18798. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18799. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18800. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18801. }
  18802. }
  18803. // bottom cap
  18804. if ( !openEnded && radiusBottom > 0 ) {
  18805. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18806. for ( x = 0; x < segmentsX; x ++ ) {
  18807. var v1 = vertices[ y ][ x + 1 ];
  18808. var v2 = vertices[ y ][ x ];
  18809. var v3 = this.vertices.length - 1;
  18810. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18811. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18812. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18813. var uv1 = uvs[ y ][ x + 1 ].clone();
  18814. var uv2 = uvs[ y ][ x ].clone();
  18815. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18816. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18817. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18818. }
  18819. }
  18820. this.computeCentroids();
  18821. this.computeFaceNormals();
  18822. }
  18823. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18824. /**
  18825. * @author zz85 / http://www.lab4games.net/zz85/blog
  18826. *
  18827. * Creates extruded geometry from a path shape.
  18828. *
  18829. * parameters = {
  18830. *
  18831. * size: <float>, // size of the text
  18832. * height: <float>, // thickness to extrude text
  18833. * curveSegments: <int>, // number of points on the curves
  18834. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18835. * amount: <int>, // Amount
  18836. *
  18837. * bevelEnabled: <bool>, // turn on bevel
  18838. * bevelThickness: <float>, // how deep into text bevel goes
  18839. * bevelSize: <float>, // how far from text outline is bevel
  18840. * bevelSegments: <int>, // number of bevel layers
  18841. *
  18842. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18843. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18844. *
  18845. * material: <int> // material index for front and back faces
  18846. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18847. * uvGenerator: <Object> // object that provides UV generator functions
  18848. *
  18849. * }
  18850. **/
  18851. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18852. if ( typeof( shapes ) === "undefined" ) {
  18853. shapes = [];
  18854. return;
  18855. }
  18856. THREE.Geometry.call( this );
  18857. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18858. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18859. this.addShapeList( shapes, options );
  18860. this.computeCentroids();
  18861. this.computeFaceNormals();
  18862. // can't really use automatic vertex normals
  18863. // as then front and back sides get smoothed too
  18864. // should do separate smoothing just for sides
  18865. //this.computeVertexNormals();
  18866. //console.log( "took", ( Date.now() - startTime ) );
  18867. };
  18868. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18869. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18870. var sl = shapes.length;
  18871. for ( var s = 0; s < sl; s ++ ) {
  18872. var shape = shapes[ s ];
  18873. this.addShape( shape, options );
  18874. }
  18875. };
  18876. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18877. var amount = options.amount !== undefined ? options.amount : 100;
  18878. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18879. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18880. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18881. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18882. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18883. var steps = options.steps !== undefined ? options.steps : 1;
  18884. var extrudePath = options.extrudePath;
  18885. var extrudePts, extrudeByPath = false;
  18886. var material = options.material;
  18887. var extrudeMaterial = options.extrudeMaterial;
  18888. // Use default WorldUVGenerator if no UV generators are specified.
  18889. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18890. var shapebb = this.shapebb;
  18891. //shapebb = shape.getBoundingBox();
  18892. var splineTube, binormal, normal, position2;
  18893. if ( extrudePath ) {
  18894. extrudePts = extrudePath.getSpacedPoints( steps );
  18895. extrudeByPath = true;
  18896. bevelEnabled = false; // bevels not supported for path extrusion
  18897. // SETUP TNB variables
  18898. // Reuse TNB from TubeGeomtry for now.
  18899. // TODO1 - have a .isClosed in spline?
  18900. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18901. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18902. binormal = new THREE.Vector3();
  18903. normal = new THREE.Vector3();
  18904. position2 = new THREE.Vector3();
  18905. }
  18906. // Safeguards if bevels are not enabled
  18907. if ( ! bevelEnabled ) {
  18908. bevelSegments = 0;
  18909. bevelThickness = 0;
  18910. bevelSize = 0;
  18911. }
  18912. // Variables initalization
  18913. var ahole, h, hl; // looping of holes
  18914. var scope = this;
  18915. var bevelPoints = [];
  18916. var shapesOffset = this.vertices.length;
  18917. var shapePoints = shape.extractPoints( curveSegments );
  18918. var vertices = shapePoints.shape;
  18919. var holes = shapePoints.holes;
  18920. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18921. if ( reverse ) {
  18922. vertices = vertices.reverse();
  18923. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18924. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18925. ahole = holes[ h ];
  18926. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18927. holes[ h ] = ahole.reverse();
  18928. }
  18929. }
  18930. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18931. }
  18932. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18933. /* Vertices */
  18934. var contour = vertices; // vertices has all points but contour has only points of circumference
  18935. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18936. ahole = holes[ h ];
  18937. vertices = vertices.concat( ahole );
  18938. }
  18939. function scalePt2 ( pt, vec, size ) {
  18940. if ( !vec ) console.log( "die" );
  18941. return vec.clone().multiplyScalar( size ).addSelf( pt );
  18942. }
  18943. var b, bs, t, z,
  18944. vert, vlen = vertices.length,
  18945. face, flen = faces.length,
  18946. cont, clen = contour.length;
  18947. // Find directions for point movement
  18948. var RAD_TO_DEGREES = 180 / Math.PI;
  18949. function getBevelVec( pt_i, pt_j, pt_k ) {
  18950. // Algorithm 2
  18951. return getBevelVec2( pt_i, pt_j, pt_k );
  18952. }
  18953. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18954. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18955. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18956. if ( anglea > angleb ) {
  18957. angleb += Math.PI * 2;
  18958. }
  18959. var anglec = ( anglea + angleb ) / 2;
  18960. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18961. var x = - Math.cos( anglec );
  18962. var y = - Math.sin( anglec );
  18963. var vec = new THREE.Vector2( x, y ); //.normalize();
  18964. return vec;
  18965. }
  18966. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18967. var a = THREE.ExtrudeGeometry.__v1,
  18968. b = THREE.ExtrudeGeometry.__v2,
  18969. v_hat = THREE.ExtrudeGeometry.__v3,
  18970. w_hat = THREE.ExtrudeGeometry.__v4,
  18971. p = THREE.ExtrudeGeometry.__v5,
  18972. q = THREE.ExtrudeGeometry.__v6,
  18973. v, w,
  18974. v_dot_w_hat, q_sub_p_dot_w_hat,
  18975. s, intersection;
  18976. // good reading for line-line intersection
  18977. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18978. // define a as vector j->i
  18979. // define b as vectot k->i
  18980. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18981. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18982. // get unit vectors
  18983. v = a.normalize();
  18984. w = b.normalize();
  18985. // normals from pt i
  18986. v_hat.set( -v.y, v.x );
  18987. w_hat.set( w.y, -w.x );
  18988. // pts from i
  18989. p.copy( pt_i ).addSelf( v_hat );
  18990. q.copy( pt_i ).addSelf( w_hat );
  18991. if ( p.equals( q ) ) {
  18992. //console.log("Warning: lines are straight");
  18993. return w_hat.clone();
  18994. }
  18995. // Points from j, k. helps prevents points cross overover most of the time
  18996. p.copy( pt_j ).addSelf( v_hat );
  18997. q.copy( pt_k ).addSelf( w_hat );
  18998. v_dot_w_hat = v.dot( w_hat );
  18999. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  19000. // We should not reach these conditions
  19001. if ( v_dot_w_hat === 0 ) {
  19002. console.log( "Either infinite or no solutions!" );
  19003. if ( q_sub_p_dot_w_hat === 0 ) {
  19004. console.log( "Its finite solutions." );
  19005. } else {
  19006. console.log( "Too bad, no solutions." );
  19007. }
  19008. }
  19009. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  19010. if ( s < 0 ) {
  19011. // in case of emergecy, revert to algorithm 1.
  19012. return getBevelVec1( pt_i, pt_j, pt_k );
  19013. }
  19014. intersection = v.multiplyScalar( s ).addSelf( p );
  19015. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  19016. }
  19017. var contourMovements = [];
  19018. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19019. if ( j === il ) j = 0;
  19020. if ( k === il ) k = 0;
  19021. // (j)---(i)---(k)
  19022. // console.log('i,j,k', i, j , k)
  19023. var pt_i = contour[ i ];
  19024. var pt_j = contour[ j ];
  19025. var pt_k = contour[ k ];
  19026. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19027. }
  19028. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19029. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19030. ahole = holes[ h ];
  19031. oneHoleMovements = [];
  19032. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19033. if ( j === il ) j = 0;
  19034. if ( k === il ) k = 0;
  19035. // (j)---(i)---(k)
  19036. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19037. }
  19038. holesMovements.push( oneHoleMovements );
  19039. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19040. }
  19041. // Loop bevelSegments, 1 for the front, 1 for the back
  19042. for ( b = 0; b < bevelSegments; b ++ ) {
  19043. //for ( b = bevelSegments; b > 0; b -- ) {
  19044. t = b / bevelSegments;
  19045. z = bevelThickness * ( 1 - t );
  19046. //z = bevelThickness * t;
  19047. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19048. //bs = bevelSize * t ; // linear
  19049. // contract shape
  19050. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19051. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19052. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19053. v( vert.x, vert.y, - z );
  19054. }
  19055. // expand holes
  19056. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19057. ahole = holes[ h ];
  19058. oneHoleMovements = holesMovements[ h ];
  19059. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19060. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19061. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19062. v( vert.x, vert.y, -z );
  19063. }
  19064. }
  19065. }
  19066. bs = bevelSize;
  19067. // Back facing vertices
  19068. for ( i = 0; i < vlen; i ++ ) {
  19069. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19070. if ( !extrudeByPath ) {
  19071. v( vert.x, vert.y, 0 );
  19072. } else {
  19073. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19074. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19075. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19076. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  19077. v( position2.x, position2.y, position2.z );
  19078. }
  19079. }
  19080. // Add stepped vertices...
  19081. // Including front facing vertices
  19082. var s;
  19083. for ( s = 1; s <= steps; s ++ ) {
  19084. for ( i = 0; i < vlen; i ++ ) {
  19085. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19086. if ( !extrudeByPath ) {
  19087. v( vert.x, vert.y, amount / steps * s );
  19088. } else {
  19089. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19090. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19091. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19092. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  19093. v( position2.x, position2.y, position2.z );
  19094. }
  19095. }
  19096. }
  19097. // Add bevel segments planes
  19098. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19099. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19100. t = b / bevelSegments;
  19101. z = bevelThickness * ( 1 - t );
  19102. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19103. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19104. // contract shape
  19105. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19106. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19107. v( vert.x, vert.y, amount + z );
  19108. }
  19109. // expand holes
  19110. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19111. ahole = holes[ h ];
  19112. oneHoleMovements = holesMovements[ h ];
  19113. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19114. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19115. if ( !extrudeByPath ) {
  19116. v( vert.x, vert.y, amount + z );
  19117. } else {
  19118. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19119. }
  19120. }
  19121. }
  19122. }
  19123. /* Faces */
  19124. // Top and bottom faces
  19125. buildLidFaces();
  19126. // Sides faces
  19127. buildSideFaces();
  19128. ///// Internal functions
  19129. function buildLidFaces() {
  19130. if ( bevelEnabled ) {
  19131. var layer = 0 ; // steps + 1
  19132. var offset = vlen * layer;
  19133. // Bottom faces
  19134. for ( i = 0; i < flen; i ++ ) {
  19135. face = faces[ i ];
  19136. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19137. }
  19138. layer = steps + bevelSegments * 2;
  19139. offset = vlen * layer;
  19140. // Top faces
  19141. for ( i = 0; i < flen; i ++ ) {
  19142. face = faces[ i ];
  19143. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19144. }
  19145. } else {
  19146. // Bottom faces
  19147. for ( i = 0; i < flen; i++ ) {
  19148. face = faces[ i ];
  19149. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19150. }
  19151. // Top faces
  19152. for ( i = 0; i < flen; i ++ ) {
  19153. face = faces[ i ];
  19154. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19155. }
  19156. }
  19157. }
  19158. // Create faces for the z-sides of the shape
  19159. function buildSideFaces() {
  19160. var layeroffset = 0;
  19161. sidewalls( contour, layeroffset );
  19162. layeroffset += contour.length;
  19163. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19164. ahole = holes[ h ];
  19165. sidewalls( ahole, layeroffset );
  19166. //, true
  19167. layeroffset += ahole.length;
  19168. }
  19169. }
  19170. function sidewalls( contour, layeroffset ) {
  19171. var j, k;
  19172. i = contour.length;
  19173. while ( --i >= 0 ) {
  19174. j = i;
  19175. k = i - 1;
  19176. if ( k < 0 ) k = contour.length - 1;
  19177. //console.log('b', i,j, i-1, k,vertices.length);
  19178. var s = 0, sl = steps + bevelSegments * 2;
  19179. for ( s = 0; s < sl; s ++ ) {
  19180. var slen1 = vlen * s;
  19181. var slen2 = vlen * ( s + 1 );
  19182. var a = layeroffset + j + slen1,
  19183. b = layeroffset + k + slen1,
  19184. c = layeroffset + k + slen2,
  19185. d = layeroffset + j + slen2;
  19186. f4( a, b, c, d, contour, s, sl, j, k );
  19187. }
  19188. }
  19189. }
  19190. function v( x, y, z ) {
  19191. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19192. }
  19193. function f3( a, b, c, isBottom ) {
  19194. a += shapesOffset;
  19195. b += shapesOffset;
  19196. c += shapesOffset;
  19197. // normal, color, material
  19198. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19199. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19200. scope.faceVertexUvs[ 0 ].push( uvs );
  19201. }
  19202. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19203. a += shapesOffset;
  19204. b += shapesOffset;
  19205. c += shapesOffset;
  19206. d += shapesOffset;
  19207. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19208. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19209. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19210. scope.faceVertexUvs[ 0 ].push( uvs );
  19211. }
  19212. };
  19213. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19214. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19215. var ax = geometry.vertices[ indexA ].x,
  19216. ay = geometry.vertices[ indexA ].y,
  19217. bx = geometry.vertices[ indexB ].x,
  19218. by = geometry.vertices[ indexB ].y,
  19219. cx = geometry.vertices[ indexC ].x,
  19220. cy = geometry.vertices[ indexC ].y;
  19221. return [
  19222. new THREE.Vector2( ax, ay ),
  19223. new THREE.Vector2( bx, by ),
  19224. new THREE.Vector2( cx, cy )
  19225. ];
  19226. },
  19227. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19228. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19229. },
  19230. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19231. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19232. contourIndex1, contourIndex2 ) {
  19233. var ax = geometry.vertices[ indexA ].x,
  19234. ay = geometry.vertices[ indexA ].y,
  19235. az = geometry.vertices[ indexA ].z,
  19236. bx = geometry.vertices[ indexB ].x,
  19237. by = geometry.vertices[ indexB ].y,
  19238. bz = geometry.vertices[ indexB ].z,
  19239. cx = geometry.vertices[ indexC ].x,
  19240. cy = geometry.vertices[ indexC ].y,
  19241. cz = geometry.vertices[ indexC ].z,
  19242. dx = geometry.vertices[ indexD ].x,
  19243. dy = geometry.vertices[ indexD ].y,
  19244. dz = geometry.vertices[ indexD ].z;
  19245. if ( Math.abs( ay - by ) < 0.01 ) {
  19246. return [
  19247. new THREE.Vector2( ax, 1 - az ),
  19248. new THREE.Vector2( bx, 1 - bz ),
  19249. new THREE.Vector2( cx, 1 - cz ),
  19250. new THREE.Vector2( dx, 1 - dz )
  19251. ];
  19252. } else {
  19253. return [
  19254. new THREE.Vector2( ay, 1 - az ),
  19255. new THREE.Vector2( by, 1 - bz ),
  19256. new THREE.Vector2( cy, 1 - cz ),
  19257. new THREE.Vector2( dy, 1 - dz )
  19258. ];
  19259. }
  19260. }
  19261. };
  19262. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19263. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19264. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19265. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19266. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19267. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19268. /**
  19269. * @author jonobr1 / http://jonobr1.com
  19270. *
  19271. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19272. * ExtrudeGeometry.
  19273. *
  19274. * parameters = {
  19275. *
  19276. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19277. *
  19278. * material: <int> // material index for front and back faces
  19279. * uvGenerator: <Object> // object that provides UV generator functions
  19280. *
  19281. * }
  19282. **/
  19283. THREE.ShapeGeometry = function ( shapes, options ) {
  19284. THREE.Geometry.call( this );
  19285. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19286. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19287. this.addShapeList( shapes, options );
  19288. this.computeCentroids();
  19289. this.computeFaceNormals();
  19290. };
  19291. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19292. /**
  19293. * Add an array of shapes to THREE.ShapeGeometry.
  19294. */
  19295. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19296. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19297. this.addShape( shapes[ i ], options );
  19298. }
  19299. return this;
  19300. };
  19301. /**
  19302. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19303. */
  19304. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19305. if ( options === undefined ) options = {};
  19306. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19307. var material = options.material;
  19308. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19309. var shapebb = this.shapebb;
  19310. //
  19311. var i, l, hole, s;
  19312. var shapesOffset = this.vertices.length;
  19313. var shapePoints = shape.extractPoints( curveSegments );
  19314. var vertices = shapePoints.shape;
  19315. var holes = shapePoints.holes;
  19316. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19317. if ( reverse ) {
  19318. vertices = vertices.reverse();
  19319. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19320. for ( i = 0, l = holes.length; i < l; i++ ) {
  19321. hole = holes[ i ];
  19322. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19323. holes[ i ] = hole.reverse();
  19324. }
  19325. }
  19326. reverse = false;
  19327. }
  19328. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19329. // Vertices
  19330. var contour = vertices;
  19331. for ( i = 0, l = holes.length; i < l; i++ ) {
  19332. hole = holes[ i ];
  19333. vertices = vertices.concat( hole );
  19334. }
  19335. //
  19336. var vert, vlen = vertices.length;
  19337. var face, flen = faces.length;
  19338. var cont, clen = contour.length;
  19339. for ( i = 0; i < vlen; i++ ) {
  19340. vert = vertices[ i ];
  19341. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19342. }
  19343. for ( i = 0; i < flen; i++ ) {
  19344. face = faces[ i ];
  19345. var a = face[ 0 ] + shapesOffset;
  19346. var b = face[ 1 ] + shapesOffset;
  19347. var c = face[ 2 ] + shapesOffset;
  19348. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19349. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19350. }
  19351. };
  19352. /**
  19353. * @author astrodud / http://astrodud.isgreat.org/
  19354. * @author zz85 / https://github.com/zz85
  19355. */
  19356. THREE.LatheGeometry = function ( points, steps, angle ) {
  19357. THREE.Geometry.call( this );
  19358. var _steps = steps || 12;
  19359. var _angle = angle || 2 * Math.PI;
  19360. var _newV = [];
  19361. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  19362. for ( var j = 0; j < points.length; j ++ ) {
  19363. _newV[ j ] = points[ j ].clone();
  19364. this.vertices.push( _newV[ j ] );
  19365. }
  19366. var i, il = _steps + 1;
  19367. for ( i = 0; i < il; i ++ ) {
  19368. for ( var j = 0; j < _newV.length; j ++ ) {
  19369. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  19370. this.vertices.push( _newV[ j ] );
  19371. }
  19372. }
  19373. for ( i = 0; i < _steps; i ++ ) {
  19374. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  19375. var a = i * kl + k;
  19376. var b = ( ( i + 1 ) % il ) * kl + k;
  19377. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  19378. var d = i * kl + ( k + 1 ) % kl;
  19379. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19380. this.faceVertexUvs[ 0 ].push( [
  19381. new THREE.Vector2( 1 - i / _steps, k / kl ),
  19382. new THREE.Vector2( 1 - ( i + 1 ) / _steps, k / kl ),
  19383. new THREE.Vector2( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  19384. new THREE.Vector2( 1 - i / _steps, ( k + 1 ) / kl )
  19385. ] );
  19386. }
  19387. }
  19388. this.computeCentroids();
  19389. this.computeFaceNormals();
  19390. this.computeVertexNormals();
  19391. };
  19392. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19393. /**
  19394. * @author mrdoob / http://mrdoob.com/
  19395. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19396. */
  19397. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19398. THREE.Geometry.call( this );
  19399. this.width = width;
  19400. this.height = height;
  19401. this.widthSegments = widthSegments || 1;
  19402. this.heightSegments = heightSegments || 1;
  19403. var ix, iz;
  19404. var width_half = width / 2;
  19405. var height_half = height / 2;
  19406. var gridX = this.widthSegments;
  19407. var gridZ = this.heightSegments;
  19408. var gridX1 = gridX + 1;
  19409. var gridZ1 = gridZ + 1;
  19410. var segment_width = this.width / gridX;
  19411. var segment_height = this.height / gridZ;
  19412. var normal = new THREE.Vector3( 0, 0, 1 );
  19413. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19414. for ( ix = 0; ix < gridX1; ix ++ ) {
  19415. var x = ix * segment_width - width_half;
  19416. var y = iz * segment_height - height_half;
  19417. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19418. }
  19419. }
  19420. for ( iz = 0; iz < gridZ; iz ++ ) {
  19421. for ( ix = 0; ix < gridX; ix ++ ) {
  19422. var a = ix + gridX1 * iz;
  19423. var b = ix + gridX1 * ( iz + 1 );
  19424. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19425. var d = ( ix + 1 ) + gridX1 * iz;
  19426. var face = new THREE.Face4( a, b, c, d );
  19427. face.normal.copy( normal );
  19428. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19429. this.faces.push( face );
  19430. this.faceVertexUvs[ 0 ].push( [
  19431. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19432. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19433. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19434. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19435. ] );
  19436. }
  19437. }
  19438. this.computeCentroids();
  19439. };
  19440. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19441. /**
  19442. * @author mrdoob / http://mrdoob.com/
  19443. */
  19444. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19445. THREE.Geometry.call( this );
  19446. this.radius = radius || 50;
  19447. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19448. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19449. phiStart = phiStart !== undefined ? phiStart : 0;
  19450. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19451. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19452. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19453. var x, y, vertices = [], uvs = [];
  19454. for ( y = 0; y <= this.heightSegments; y ++ ) {
  19455. var verticesRow = [];
  19456. var uvsRow = [];
  19457. for ( x = 0; x <= this.widthSegments; x ++ ) {
  19458. var u = x / this.widthSegments;
  19459. var v = y / this.heightSegments;
  19460. var vertex = new THREE.Vector3();
  19461. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19462. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  19463. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19464. this.vertices.push( vertex );
  19465. verticesRow.push( this.vertices.length - 1 );
  19466. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19467. }
  19468. vertices.push( verticesRow );
  19469. uvs.push( uvsRow );
  19470. }
  19471. for ( y = 0; y < this.heightSegments; y ++ ) {
  19472. for ( x = 0; x < this.widthSegments; x ++ ) {
  19473. var v1 = vertices[ y ][ x + 1 ];
  19474. var v2 = vertices[ y ][ x ];
  19475. var v3 = vertices[ y + 1 ][ x ];
  19476. var v4 = vertices[ y + 1 ][ x + 1 ];
  19477. var n1 = this.vertices[ v1 ].clone().normalize();
  19478. var n2 = this.vertices[ v2 ].clone().normalize();
  19479. var n3 = this.vertices[ v3 ].clone().normalize();
  19480. var n4 = this.vertices[ v4 ].clone().normalize();
  19481. var uv1 = uvs[ y ][ x + 1 ].clone();
  19482. var uv2 = uvs[ y ][ x ].clone();
  19483. var uv3 = uvs[ y + 1 ][ x ].clone();
  19484. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19485. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19486. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19487. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19488. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19489. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19490. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19491. } else {
  19492. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19493. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19494. }
  19495. }
  19496. }
  19497. this.computeCentroids();
  19498. this.computeFaceNormals();
  19499. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19500. };
  19501. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19502. /**
  19503. * @author zz85 / http://www.lab4games.net/zz85/blog
  19504. * @author alteredq / http://alteredqualia.com/
  19505. *
  19506. * For creating 3D text geometry in three.js
  19507. *
  19508. * Text = 3D Text
  19509. *
  19510. * parameters = {
  19511. * size: <float>, // size of the text
  19512. * height: <float>, // thickness to extrude text
  19513. * curveSegments: <int>, // number of points on the curves
  19514. *
  19515. * font: <string>, // font name
  19516. * weight: <string>, // font weight (normal, bold)
  19517. * style: <string>, // font style (normal, italics)
  19518. *
  19519. * bevelEnabled: <bool>, // turn on bevel
  19520. * bevelThickness: <float>, // how deep into text bevel goes
  19521. * bevelSize: <float>, // how far from text outline is bevel
  19522. * }
  19523. *
  19524. */
  19525. /* Usage Examples
  19526. // TextGeometry wrapper
  19527. var text3d = new TextGeometry( text, options );
  19528. // Complete manner
  19529. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19530. var text3d = new ExtrudeGeometry( textShapes, options );
  19531. */
  19532. THREE.TextGeometry = function ( text, parameters ) {
  19533. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19534. // translate parameters to ExtrudeGeometry API
  19535. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19536. // defaults
  19537. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19538. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19539. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19540. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19541. };
  19542. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19543. /**
  19544. * @author oosmoxiecode
  19545. * @author mrdoob / http://mrdoob.com/
  19546. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19547. */
  19548. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19549. THREE.Geometry.call( this );
  19550. var scope = this;
  19551. this.radius = radius || 100;
  19552. this.tube = tube || 40;
  19553. this.radialSegments = radialSegments || 8;
  19554. this.tubularSegments = tubularSegments || 6;
  19555. this.arc = arc || Math.PI * 2;
  19556. var center = new THREE.Vector3(), uvs = [], normals = [];
  19557. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19558. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19559. var u = i / this.tubularSegments * this.arc;
  19560. var v = j / this.radialSegments * Math.PI * 2;
  19561. center.x = this.radius * Math.cos( u );
  19562. center.y = this.radius * Math.sin( u );
  19563. var vertex = new THREE.Vector3();
  19564. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19565. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19566. vertex.z = this.tube * Math.sin( v );
  19567. this.vertices.push( vertex );
  19568. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19569. normals.push( vertex.clone().subSelf( center ).normalize() );
  19570. }
  19571. }
  19572. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19573. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19574. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19575. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19576. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19577. var d = ( this.tubularSegments + 1 ) * j + i;
  19578. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19579. face.normal.addSelf( normals[ a ] );
  19580. face.normal.addSelf( normals[ b ] );
  19581. face.normal.addSelf( normals[ c ] );
  19582. face.normal.addSelf( normals[ d ] );
  19583. face.normal.normalize();
  19584. this.faces.push( face );
  19585. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19586. }
  19587. }
  19588. this.computeCentroids();
  19589. };
  19590. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19591. /**
  19592. * @author oosmoxiecode
  19593. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19594. */
  19595. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19596. THREE.Geometry.call( this );
  19597. var scope = this;
  19598. this.radius = radius || 100;
  19599. this.tube = tube || 40;
  19600. this.radialSegments = radialSegments || 64;
  19601. this.tubularSegments = tubularSegments || 8;
  19602. this.p = p || 2;
  19603. this.q = q || 3;
  19604. this.heightScale = heightScale || 1;
  19605. this.grid = new Array( this.radialSegments );
  19606. var tang = new THREE.Vector3();
  19607. var n = new THREE.Vector3();
  19608. var bitan = new THREE.Vector3();
  19609. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19610. this.grid[ i ] = new Array( this.tubularSegments );
  19611. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19612. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19613. var v = j / this.tubularSegments * 2 * Math.PI;
  19614. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19615. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19616. var cx, cy;
  19617. tang.sub( p2, p1 );
  19618. n.add( p2, p1 );
  19619. bitan.cross( tang, n );
  19620. n.cross( bitan, tang );
  19621. bitan.normalize();
  19622. n.normalize();
  19623. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19624. cy = this.tube * Math.sin( v );
  19625. p1.x += cx * n.x + cy * bitan.x;
  19626. p1.y += cx * n.y + cy * bitan.y;
  19627. p1.z += cx * n.z + cy * bitan.z;
  19628. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19629. }
  19630. }
  19631. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19632. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19633. var ip = ( i + 1 ) % this.radialSegments;
  19634. var jp = ( j + 1 ) % this.tubularSegments;
  19635. var a = this.grid[ i ][ j ];
  19636. var b = this.grid[ ip ][ j ];
  19637. var c = this.grid[ ip ][ jp ];
  19638. var d = this.grid[ i ][ jp ];
  19639. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19640. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19641. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19642. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19643. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19644. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19645. }
  19646. }
  19647. this.computeCentroids();
  19648. this.computeFaceNormals();
  19649. this.computeVertexNormals();
  19650. function vert( x, y, z ) {
  19651. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19652. }
  19653. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19654. var cu = Math.cos( u );
  19655. var cv = Math.cos( v );
  19656. var su = Math.sin( u );
  19657. var quOverP = in_q / in_p * u;
  19658. var cs = Math.cos( quOverP );
  19659. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19660. var ty = radius * ( 2 + cs ) * su * 0.5;
  19661. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19662. return new THREE.Vector3( tx, ty, tz );
  19663. }
  19664. };
  19665. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19666. /**
  19667. * @author WestLangley / https://github.com/WestLangley
  19668. * @author zz85 / https://github.com/zz85
  19669. * @author miningold / https://github.com/miningold
  19670. *
  19671. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19672. *
  19673. * Creates a tube which extrudes along a 3d spline
  19674. *
  19675. * Uses parallel transport frames as described in
  19676. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19677. */
  19678. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19679. THREE.Geometry.call( this );
  19680. this.path = path;
  19681. this.segments = segments || 64;
  19682. this.radius = radius || 1;
  19683. this.radiusSegments = radiusSegments || 8;
  19684. this.closed = closed || false;
  19685. if ( debug ) this.debug = new THREE.Object3D();
  19686. this.grid = [];
  19687. var scope = this,
  19688. tangent,
  19689. normal,
  19690. binormal,
  19691. numpoints = this.segments + 1,
  19692. x, y, z,
  19693. tx, ty, tz,
  19694. u, v,
  19695. cx, cy,
  19696. pos, pos2 = new THREE.Vector3(),
  19697. i, j,
  19698. ip, jp,
  19699. a, b, c, d,
  19700. uva, uvb, uvc, uvd;
  19701. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19702. tangents = frames.tangents,
  19703. normals = frames.normals,
  19704. binormals = frames.binormals;
  19705. // proxy internals
  19706. this.tangents = tangents;
  19707. this.normals = normals;
  19708. this.binormals = binormals;
  19709. function vert( x, y, z ) {
  19710. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19711. }
  19712. // consruct the grid
  19713. for ( i = 0; i < numpoints; i++ ) {
  19714. this.grid[ i ] = [];
  19715. u = i / ( numpoints - 1 );
  19716. pos = path.getPointAt( u );
  19717. tangent = tangents[ i ];
  19718. normal = normals[ i ];
  19719. binormal = binormals[ i ];
  19720. if ( this.debug ) {
  19721. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19722. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19723. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19724. }
  19725. for ( j = 0; j < this.radiusSegments; j++ ) {
  19726. v = j / this.radiusSegments * 2 * Math.PI;
  19727. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19728. cy = this.radius * Math.sin( v );
  19729. pos2.copy( pos );
  19730. pos2.x += cx * normal.x + cy * binormal.x;
  19731. pos2.y += cx * normal.y + cy * binormal.y;
  19732. pos2.z += cx * normal.z + cy * binormal.z;
  19733. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19734. }
  19735. }
  19736. // construct the mesh
  19737. for ( i = 0; i < this.segments; i++ ) {
  19738. for ( j = 0; j < this.radiusSegments; j++ ) {
  19739. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19740. jp = (j + 1) % this.radiusSegments;
  19741. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19742. b = this.grid[ ip ][ j ];
  19743. c = this.grid[ ip ][ jp ];
  19744. d = this.grid[ i ][ jp ];
  19745. uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
  19746. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19747. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19748. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19749. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19750. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19751. }
  19752. }
  19753. this.computeCentroids();
  19754. this.computeFaceNormals();
  19755. this.computeVertexNormals();
  19756. };
  19757. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19758. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19759. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19760. var tangent = new THREE.Vector3(),
  19761. normal = new THREE.Vector3(),
  19762. binormal = new THREE.Vector3(),
  19763. tangents = [],
  19764. normals = [],
  19765. binormals = [],
  19766. vec = new THREE.Vector3(),
  19767. mat = new THREE.Matrix4(),
  19768. numpoints = segments + 1,
  19769. theta,
  19770. epsilon = 0.0001,
  19771. smallest,
  19772. tx, ty, tz,
  19773. i, u, v;
  19774. // expose internals
  19775. this.tangents = tangents;
  19776. this.normals = normals;
  19777. this.binormals = binormals;
  19778. // compute the tangent vectors for each segment on the path
  19779. for ( i = 0; i < numpoints; i++ ) {
  19780. u = i / ( numpoints - 1 );
  19781. tangents[ i ] = path.getTangentAt( u );
  19782. tangents[ i ].normalize();
  19783. }
  19784. initialNormal3();
  19785. function initialNormal1(lastBinormal) {
  19786. // fixed start binormal. Has dangers of 0 vectors
  19787. normals[ 0 ] = new THREE.Vector3();
  19788. binormals[ 0 ] = new THREE.Vector3();
  19789. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19790. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  19791. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  19792. }
  19793. function initialNormal2() {
  19794. // This uses the Frenet-Serret formula for deriving binormal
  19795. var t2 = path.getTangentAt( epsilon );
  19796. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  19797. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  19798. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19799. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  19800. }
  19801. function initialNormal3() {
  19802. // select an initial normal vector perpenicular to the first tangent vector,
  19803. // and in the direction of the smallest tangent xyz component
  19804. normals[ 0 ] = new THREE.Vector3();
  19805. binormals[ 0 ] = new THREE.Vector3();
  19806. smallest = Number.MAX_VALUE;
  19807. tx = Math.abs( tangents[ 0 ].x );
  19808. ty = Math.abs( tangents[ 0 ].y );
  19809. tz = Math.abs( tangents[ 0 ].z );
  19810. if ( tx <= smallest ) {
  19811. smallest = tx;
  19812. normal.set( 1, 0, 0 );
  19813. }
  19814. if ( ty <= smallest ) {
  19815. smallest = ty;
  19816. normal.set( 0, 1, 0 );
  19817. }
  19818. if ( tz <= smallest ) {
  19819. normal.set( 0, 0, 1 );
  19820. }
  19821. vec.cross( tangents[ 0 ], normal ).normalize();
  19822. normals[ 0 ].cross( tangents[ 0 ], vec );
  19823. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  19824. }
  19825. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19826. for ( i = 1; i < numpoints; i++ ) {
  19827. normals[ i ] = normals[ i-1 ].clone();
  19828. binormals[ i ] = binormals[ i-1 ].clone();
  19829. vec.cross( tangents[ i-1 ], tangents[ i ] );
  19830. if ( vec.length() > epsilon ) {
  19831. vec.normalize();
  19832. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19833. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  19834. }
  19835. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19836. }
  19837. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19838. if ( closed ) {
  19839. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19840. theta /= ( numpoints - 1 );
  19841. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19842. theta = -theta;
  19843. }
  19844. for ( i = 1; i < numpoints; i++ ) {
  19845. // twist a little...
  19846. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  19847. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19848. }
  19849. }
  19850. };
  19851. /**
  19852. * @author clockworkgeek / https://github.com/clockworkgeek
  19853. * @author timothypratley / https://github.com/timothypratley
  19854. */
  19855. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19856. THREE.Geometry.call( this );
  19857. radius = radius || 1;
  19858. detail = detail || 0;
  19859. var that = this;
  19860. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19861. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19862. }
  19863. var midpoints = [], p = this.vertices;
  19864. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19865. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19866. }
  19867. this.mergeVertices();
  19868. // Apply radius
  19869. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19870. this.vertices[ i ].multiplyScalar( radius );
  19871. }
  19872. // Project vector onto sphere's surface
  19873. function prepare( vector ) {
  19874. var vertex = vector.normalize().clone();
  19875. vertex.index = that.vertices.push( vertex ) - 1;
  19876. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19877. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19878. var v = inclination( vector ) / Math.PI + 0.5;
  19879. vertex.uv = new THREE.Vector2( u, 1 - v );
  19880. return vertex;
  19881. }
  19882. // Approximate a curved face with recursively sub-divided triangles.
  19883. function make( v1, v2, v3, detail ) {
  19884. if ( detail < 1 ) {
  19885. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19886. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  19887. face.normal = face.centroid.clone().normalize();
  19888. that.faces.push( face );
  19889. var azi = azimuth( face.centroid );
  19890. that.faceVertexUvs[ 0 ].push( [
  19891. correctUV( v1.uv, v1, azi ),
  19892. correctUV( v2.uv, v2, azi ),
  19893. correctUV( v3.uv, v3, azi )
  19894. ] );
  19895. } else {
  19896. detail -= 1;
  19897. // split triangle into 4 smaller triangles
  19898. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19899. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19900. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19901. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19902. }
  19903. }
  19904. function midpoint( v1, v2 ) {
  19905. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19906. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19907. var mid = midpoints[ v1.index ][ v2.index ];
  19908. if ( mid === undefined ) {
  19909. // generate mean point and project to surface with prepare()
  19910. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19911. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  19912. );
  19913. }
  19914. return mid;
  19915. }
  19916. // Angle around the Y axis, counter-clockwise when looking from above.
  19917. function azimuth( vector ) {
  19918. return Math.atan2( vector.z, -vector.x );
  19919. }
  19920. // Angle above the XZ plane.
  19921. function inclination( vector ) {
  19922. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19923. }
  19924. // Texture fixing helper. Spheres have some odd behaviours.
  19925. function correctUV( uv, vector, azimuth ) {
  19926. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19927. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19928. return uv;
  19929. }
  19930. this.computeCentroids();
  19931. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19932. };
  19933. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19934. /**
  19935. * @author timothypratley / https://github.com/timothypratley
  19936. */
  19937. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19938. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19939. var vertices = [
  19940. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19941. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19942. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19943. ];
  19944. var faces = [
  19945. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19946. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19947. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19948. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19949. ];
  19950. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19951. };
  19952. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19953. /**
  19954. * @author timothypratley / https://github.com/timothypratley
  19955. */
  19956. THREE.OctahedronGeometry = function ( radius, detail ) {
  19957. var vertices = [
  19958. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19959. ];
  19960. var faces = [
  19961. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19962. ];
  19963. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19964. };
  19965. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19966. /**
  19967. * @author timothypratley / https://github.com/timothypratley
  19968. */
  19969. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19970. var vertices = [
  19971. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19972. ];
  19973. var faces = [
  19974. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19975. ];
  19976. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19977. };
  19978. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19979. /**
  19980. * @author zz85 / https://github.com/zz85
  19981. * Parametric Surfaces Geometry
  19982. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19983. *
  19984. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19985. *
  19986. */
  19987. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19988. THREE.Geometry.call( this );
  19989. var verts = this.vertices;
  19990. var faces = this.faces;
  19991. var uvs = this.faceVertexUvs[ 0 ];
  19992. useTris = (useTris === undefined) ? false : useTris;
  19993. var i, il, j, p;
  19994. var u, v;
  19995. var stackCount = stacks + 1;
  19996. var sliceCount = slices + 1;
  19997. for ( i = 0; i <= stacks; i ++ ) {
  19998. v = i / stacks;
  19999. for ( j = 0; j <= slices; j ++ ) {
  20000. u = j / slices;
  20001. p = func( u, v );
  20002. verts.push( p );
  20003. }
  20004. }
  20005. var a, b, c, d;
  20006. var uva, uvb, uvc, uvd;
  20007. for ( i = 0; i < stacks; i ++ ) {
  20008. for ( j = 0; j < slices; j ++ ) {
  20009. a = i * sliceCount + j;
  20010. b = i * sliceCount + j + 1;
  20011. c = (i + 1) * sliceCount + j;
  20012. d = (i + 1) * sliceCount + j + 1;
  20013. uva = new THREE.Vector2( j / slices, i / stacks );
  20014. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20015. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20016. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20017. if ( useTris ) {
  20018. faces.push( new THREE.Face3( a, b, c ) );
  20019. faces.push( new THREE.Face3( b, d, c ) );
  20020. uvs.push( [ uva, uvb, uvc ] );
  20021. uvs.push( [ uvb, uvd, uvc ] );
  20022. } else {
  20023. faces.push( new THREE.Face4( a, b, d, c ) );
  20024. uvs.push( [ uva, uvb, uvd, uvc ] );
  20025. }
  20026. }
  20027. }
  20028. // console.log(this);
  20029. // magic bullet
  20030. // var diff = this.mergeVertices();
  20031. // console.log('removed ', diff, ' vertices by merging');
  20032. this.computeCentroids();
  20033. this.computeFaceNormals();
  20034. this.computeVertexNormals();
  20035. };
  20036. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20037. /**
  20038. * @author qiao / https://github.com/qiao
  20039. * @fileoverview This is a convex hull generator using the incremental method.
  20040. * The complexity is O(n^2) where n is the number of vertices.
  20041. * O(nlogn) algorithms do exist, but they are much more complicated.
  20042. *
  20043. * Benchmark:
  20044. *
  20045. * Platform: CPU: P7350 @2.00GHz Engine: V8
  20046. *
  20047. * Num Vertices Time(ms)
  20048. *
  20049. * 10 1
  20050. * 20 3
  20051. * 30 19
  20052. * 40 48
  20053. * 50 107
  20054. */
  20055. THREE.ConvexGeometry = function( vertices ) {
  20056. THREE.Geometry.call( this );
  20057. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  20058. for ( var i = 3; i < vertices.length; i++ ) {
  20059. addPoint( i );
  20060. }
  20061. function addPoint( vertexId ) {
  20062. var vertex = vertices[ vertexId ].clone();
  20063. var mag = vertex.length();
  20064. vertex.x += mag * randomOffset();
  20065. vertex.y += mag * randomOffset();
  20066. vertex.z += mag * randomOffset();
  20067. var hole = [];
  20068. for ( var f = 0; f < faces.length; ) {
  20069. var face = faces[ f ];
  20070. // for each face, if the vertex can see it,
  20071. // then we try to add the face's edges into the hole.
  20072. if ( visible( face, vertex ) ) {
  20073. for ( var e = 0; e < 3; e++ ) {
  20074. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  20075. var boundary = true;
  20076. // remove duplicated edges.
  20077. for ( var h = 0; h < hole.length; h++ ) {
  20078. if ( equalEdge( hole[ h ], edge ) ) {
  20079. hole[ h ] = hole[ hole.length - 1 ];
  20080. hole.pop();
  20081. boundary = false;
  20082. break;
  20083. }
  20084. }
  20085. if ( boundary ) {
  20086. hole.push( edge );
  20087. }
  20088. }
  20089. // remove faces[ f ]
  20090. faces[ f ] = faces[ faces.length - 1 ];
  20091. faces.pop();
  20092. } else { // not visible
  20093. f++;
  20094. }
  20095. }
  20096. // construct the new faces formed by the edges of the hole and the vertex
  20097. for ( var h = 0; h < hole.length; h++ ) {
  20098. faces.push( [
  20099. hole[ h ][ 0 ],
  20100. hole[ h ][ 1 ],
  20101. vertexId
  20102. ] );
  20103. }
  20104. }
  20105. /**
  20106. * Whether the face is visible from the vertex
  20107. */
  20108. function visible( face, vertex ) {
  20109. var va = vertices[ face[ 0 ] ];
  20110. var vb = vertices[ face[ 1 ] ];
  20111. var vc = vertices[ face[ 2 ] ];
  20112. var n = normal( va, vb, vc );
  20113. // distance from face to origin
  20114. var dist = n.dot( va );
  20115. return n.dot( vertex ) >= dist;
  20116. }
  20117. /**
  20118. * Face normal
  20119. */
  20120. function normal( va, vb, vc ) {
  20121. var cb = new THREE.Vector3();
  20122. var ab = new THREE.Vector3();
  20123. cb.sub( vc, vb );
  20124. ab.sub( va, vb );
  20125. cb.crossSelf( ab );
  20126. cb.normalize();
  20127. return cb;
  20128. }
  20129. /**
  20130. * Detect whether two edges are equal.
  20131. * Note that when constructing the convex hull, two same edges can only
  20132. * be of the negative direction.
  20133. */
  20134. function equalEdge( ea, eb ) {
  20135. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20136. }
  20137. /**
  20138. * Create a random offset between -1e-6 and 1e-6.
  20139. */
  20140. function randomOffset() {
  20141. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20142. }
  20143. /**
  20144. * XXX: Not sure if this is the correct approach. Need someone to review.
  20145. */
  20146. function vertexUv( vertex ) {
  20147. var mag = vertex.length();
  20148. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  20149. }
  20150. // Push vertices into `this.vertices`, skipping those inside the hull
  20151. var id = 0;
  20152. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20153. for ( var i = 0; i < faces.length; i++ ) {
  20154. var face = faces[ i ];
  20155. for ( var j = 0; j < 3; j++ ) {
  20156. if ( newId[ face[ j ] ] === undefined ) {
  20157. newId[ face[ j ] ] = id++;
  20158. this.vertices.push( vertices[ face[ j ] ] );
  20159. }
  20160. face[ j ] = newId[ face[ j ] ];
  20161. }
  20162. }
  20163. // Convert faces into instances of THREE.Face3
  20164. for ( var i = 0; i < faces.length; i++ ) {
  20165. this.faces.push( new THREE.Face3(
  20166. faces[ i ][ 0 ],
  20167. faces[ i ][ 1 ],
  20168. faces[ i ][ 2 ]
  20169. ) );
  20170. }
  20171. // Compute UVs
  20172. for ( var i = 0; i < this.faces.length; i++ ) {
  20173. var face = this.faces[ i ];
  20174. this.faceVertexUvs[ 0 ].push( [
  20175. vertexUv( this.vertices[ face.a ] ),
  20176. vertexUv( this.vertices[ face.b ] ),
  20177. vertexUv( this.vertices[ face.c ])
  20178. ] );
  20179. }
  20180. this.computeCentroids();
  20181. this.computeFaceNormals();
  20182. this.computeVertexNormals();
  20183. };
  20184. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20185. /**
  20186. * @author sroucheray / http://sroucheray.org/
  20187. * @author mrdoob / http://mrdoob.com/
  20188. */
  20189. THREE.AxisHelper = function ( size ) {
  20190. var geometry = new THREE.Geometry();
  20191. geometry.vertices.push(
  20192. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  20193. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  20194. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  20195. );
  20196. geometry.colors.push(
  20197. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20198. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20199. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20200. );
  20201. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20202. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20203. };
  20204. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20205. /**
  20206. * @author WestLangley / http://github.com/WestLangley
  20207. * @author zz85 / https://github.com/zz85
  20208. *
  20209. * Creates an arrow for visualizing directions
  20210. *
  20211. * Parameters:
  20212. * dir - Vector3
  20213. * origin - Vector3
  20214. * length - Number
  20215. * hex - color in hex value
  20216. */
  20217. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20218. THREE.Object3D.call( this );
  20219. if ( hex === undefined ) hex = 0xffff00;
  20220. if ( length === undefined ) length = 20;
  20221. var lineGeometry = new THREE.Geometry();
  20222. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20223. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20224. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20225. this.add( this.line );
  20226. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20227. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20228. this.cone.position.set( 0, 1, 0 );
  20229. this.add( this.cone );
  20230. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  20231. this.setDirection( dir );
  20232. this.setLength( length );
  20233. };
  20234. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20235. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  20236. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  20237. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  20238. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  20239. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  20240. };
  20241. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20242. this.scale.set( length, length, length );
  20243. };
  20244. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20245. this.line.material.color.setHex( hex );
  20246. this.cone.material.color.setHex( hex );
  20247. };
  20248. /**
  20249. * @author alteredq / http://alteredqualia.com/
  20250. *
  20251. * - shows frustum, line of sight and up of the camera
  20252. * - suitable for fast updates
  20253. * - based on frustum visualization in lightgl.js shadowmap example
  20254. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20255. */
  20256. THREE.CameraHelper = function ( camera ) {
  20257. THREE.Line.call( this );
  20258. var scope = this;
  20259. this.geometry = new THREE.Geometry();
  20260. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20261. this.type = THREE.LinePieces;
  20262. this.matrixWorld = camera.matrixWorld;
  20263. this.matrixAutoUpdate = false;
  20264. this.pointMap = {};
  20265. // colors
  20266. var hexFrustum = 0xffaa00;
  20267. var hexCone = 0xff0000;
  20268. var hexUp = 0x00aaff;
  20269. var hexTarget = 0xffffff;
  20270. var hexCross = 0x333333;
  20271. // near
  20272. addLine( "n1", "n2", hexFrustum );
  20273. addLine( "n2", "n4", hexFrustum );
  20274. addLine( "n4", "n3", hexFrustum );
  20275. addLine( "n3", "n1", hexFrustum );
  20276. // far
  20277. addLine( "f1", "f2", hexFrustum );
  20278. addLine( "f2", "f4", hexFrustum );
  20279. addLine( "f4", "f3", hexFrustum );
  20280. addLine( "f3", "f1", hexFrustum );
  20281. // sides
  20282. addLine( "n1", "f1", hexFrustum );
  20283. addLine( "n2", "f2", hexFrustum );
  20284. addLine( "n3", "f3", hexFrustum );
  20285. addLine( "n4", "f4", hexFrustum );
  20286. // cone
  20287. addLine( "p", "n1", hexCone );
  20288. addLine( "p", "n2", hexCone );
  20289. addLine( "p", "n3", hexCone );
  20290. addLine( "p", "n4", hexCone );
  20291. // up
  20292. addLine( "u1", "u2", hexUp );
  20293. addLine( "u2", "u3", hexUp );
  20294. addLine( "u3", "u1", hexUp );
  20295. // target
  20296. addLine( "c", "t", hexTarget );
  20297. addLine( "p", "c", hexCross );
  20298. // cross
  20299. addLine( "cn1", "cn2", hexCross );
  20300. addLine( "cn3", "cn4", hexCross );
  20301. addLine( "cf1", "cf2", hexCross );
  20302. addLine( "cf3", "cf4", hexCross );
  20303. this.camera = camera;
  20304. function addLine( a, b, hex ) {
  20305. addPoint( a, hex );
  20306. addPoint( b, hex );
  20307. }
  20308. function addPoint( id, hex ) {
  20309. scope.geometry.vertices.push( new THREE.Vector3() );
  20310. scope.geometry.colors.push( new THREE.Color( hex ) );
  20311. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  20312. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  20313. }
  20314. this.update( camera );
  20315. };
  20316. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20317. THREE.CameraHelper.prototype.update = function () {
  20318. var scope = this;
  20319. var w = 1, h = 1;
  20320. // we need just camera projection matrix
  20321. // world matrix must be identity
  20322. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  20323. // center / target
  20324. setPoint( "c", 0, 0, -1 );
  20325. setPoint( "t", 0, 0, 1 );
  20326. // near
  20327. setPoint( "n1", -w, -h, -1 );
  20328. setPoint( "n2", w, -h, -1 );
  20329. setPoint( "n3", -w, h, -1 );
  20330. setPoint( "n4", w, h, -1 );
  20331. // far
  20332. setPoint( "f1", -w, -h, 1 );
  20333. setPoint( "f2", w, -h, 1 );
  20334. setPoint( "f3", -w, h, 1 );
  20335. setPoint( "f4", w, h, 1 );
  20336. // up
  20337. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20338. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20339. setPoint( "u3", 0, h * 2, -1 );
  20340. // cross
  20341. setPoint( "cf1", -w, 0, 1 );
  20342. setPoint( "cf2", w, 0, 1 );
  20343. setPoint( "cf3", 0, -h, 1 );
  20344. setPoint( "cf4", 0, h, 1 );
  20345. setPoint( "cn1", -w, 0, -1 );
  20346. setPoint( "cn2", w, 0, -1 );
  20347. setPoint( "cn3", 0, -h, -1 );
  20348. setPoint( "cn4", 0, h, -1 );
  20349. function setPoint( point, x, y, z ) {
  20350. THREE.CameraHelper.__v.set( x, y, z );
  20351. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  20352. var points = scope.pointMap[ point ];
  20353. if ( points !== undefined ) {
  20354. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20355. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  20356. }
  20357. }
  20358. }
  20359. this.geometry.verticesNeedUpdate = true;
  20360. };
  20361. THREE.CameraHelper.__projector = new THREE.Projector();
  20362. THREE.CameraHelper.__v = new THREE.Vector3();
  20363. THREE.CameraHelper.__c = new THREE.Camera();
  20364. /**
  20365. * @author alteredq / http://alteredqualia.com/
  20366. *
  20367. * - shows directional light color, intensity, position, orientation and target
  20368. */
  20369. THREE.DirectionalLightHelper = function ( light, sphereSize, arrowLength ) {
  20370. THREE.Object3D.call( this );
  20371. this.light = light;
  20372. // position
  20373. this.position = light.position;
  20374. // direction
  20375. this.direction = new THREE.Vector3();
  20376. this.direction.sub( light.target.position, light.position );
  20377. // color
  20378. this.color = light.color.clone();
  20379. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20380. this.color.r *= intensity;
  20381. this.color.g *= intensity;
  20382. this.color.b *= intensity;
  20383. var hexColor = this.color.getHex();
  20384. // light helper
  20385. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20386. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20387. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20388. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20389. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  20390. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20391. this.lightArrow.cone.material.fog = false;
  20392. this.lightArrow.line.material.fog = false;
  20393. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20394. this.add( this.lightArrow );
  20395. this.add( this.lightSphere );
  20396. this.add( this.lightRays );
  20397. this.lightSphere.properties.isGizmo = true;
  20398. this.lightSphere.properties.gizmoSubject = light;
  20399. this.lightSphere.properties.gizmoRoot = this;
  20400. // light target helper
  20401. this.targetSphere = null;
  20402. if ( light.target.properties.targetInverse ) {
  20403. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20404. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20405. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20406. this.targetSphere.position = light.target.position;
  20407. this.targetSphere.properties.isGizmo = true;
  20408. this.targetSphere.properties.gizmoSubject = light.target;
  20409. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20410. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20411. var lineGeometry = new THREE.Geometry();
  20412. lineGeometry.vertices.push( this.position.clone() );
  20413. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20414. lineGeometry.computeLineDistances();
  20415. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20416. this.targetLine.properties.isGizmo = true;
  20417. }
  20418. //
  20419. this.properties.isGizmo = true;
  20420. }
  20421. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20422. THREE.DirectionalLightHelper.prototype.update = function () {
  20423. // update arrow orientation
  20424. // pointing from light to target
  20425. this.direction.sub( this.light.target.position, this.light.position );
  20426. this.lightArrow.setDirection( this.direction );
  20427. // update arrow, spheres, rays and line colors to light color * light intensity
  20428. this.color.copy( this.light.color );
  20429. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20430. this.color.r *= intensity;
  20431. this.color.g *= intensity;
  20432. this.color.b *= intensity;
  20433. this.lightArrow.setColor( this.color.getHex() );
  20434. this.lightSphere.material.color.copy( this.color );
  20435. this.lightRays.material.color.copy( this.color );
  20436. this.targetSphere.material.color.copy( this.color );
  20437. this.targetLine.material.color.copy( this.color );
  20438. // update target line vertices
  20439. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20440. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20441. this.targetLine.geometry.computeLineDistances();
  20442. this.targetLine.geometry.verticesNeedUpdate = true;
  20443. }
  20444. /**
  20445. * @author alteredq / http://alteredqualia.com/
  20446. *
  20447. * - shows hemisphere light intensity, sky and ground colors and directions
  20448. */
  20449. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20450. THREE.Object3D.call( this );
  20451. this.light = light;
  20452. // position
  20453. this.position = light.position;
  20454. //
  20455. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20456. // sky color
  20457. this.color = light.color.clone();
  20458. this.color.r *= intensity;
  20459. this.color.g *= intensity;
  20460. this.color.b *= intensity;
  20461. var hexColor = this.color.getHex();
  20462. // ground color
  20463. this.groundColor = light.groundColor.clone();
  20464. this.groundColor.r *= intensity;
  20465. this.groundColor.g *= intensity;
  20466. this.groundColor.b *= intensity;
  20467. var hexColorGround = this.groundColor.getHex();
  20468. // double colored light bulb
  20469. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  20470. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  20471. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20472. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  20473. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  20474. bulbGeometry.faces[ i ].materialIndex = 0;
  20475. }
  20476. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  20477. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  20478. }
  20479. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  20480. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  20481. // arrows for sky and ground light directions
  20482. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  20483. this.lightArrow.rotation.x = Math.PI;
  20484. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  20485. var joint = new THREE.Object3D();
  20486. joint.rotation.x = -Math.PI * 0.5;
  20487. joint.add( this.lightSphere );
  20488. joint.add( this.lightArrow );
  20489. joint.add( this.lightArrowGround );
  20490. this.add( joint );
  20491. //
  20492. this.lightSphere.properties.isGizmo = true;
  20493. this.lightSphere.properties.gizmoSubject = light;
  20494. this.lightSphere.properties.gizmoRoot = this;
  20495. //
  20496. this.properties.isGizmo = true;
  20497. //
  20498. this.target = new THREE.Vector3();
  20499. this.lookAt( this.target );
  20500. }
  20501. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20502. THREE.HemisphereLightHelper.prototype.update = function () {
  20503. // update sphere sky and ground colors to light color * light intensity
  20504. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20505. this.color.copy( this.light.color );
  20506. this.groundColor.copy( this.light.groundColor );
  20507. this.color.r *= intensity;
  20508. this.color.g *= intensity;
  20509. this.color.b *= intensity;
  20510. this.groundColor.r *= intensity;
  20511. this.groundColor.g *= intensity;
  20512. this.groundColor.b *= intensity;
  20513. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  20514. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  20515. this.lightArrow.setColor( this.color.getHex() );
  20516. this.lightArrowGround.setColor( this.groundColor.getHex() );
  20517. this.lookAt( this.target );
  20518. }
  20519. /**
  20520. * @author alteredq / http://alteredqualia.com/
  20521. *
  20522. * - shows point light color, intensity, position and distance
  20523. */
  20524. THREE.PointLightHelper = function ( light, sphereSize ) {
  20525. THREE.Object3D.call( this );
  20526. this.light = light;
  20527. // position
  20528. this.position = light.position;
  20529. // color
  20530. this.color = light.color.clone();
  20531. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20532. this.color.r *= intensity;
  20533. this.color.g *= intensity;
  20534. this.color.b *= intensity;
  20535. var hexColor = this.color.getHex();
  20536. // light helper
  20537. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20538. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20539. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20540. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20541. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20542. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20543. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20544. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20545. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20546. var d = light.distance;
  20547. if ( d === 0.0 ) {
  20548. this.lightDistance.visible = false;
  20549. } else {
  20550. this.lightDistance.scale.set( d, d, d );
  20551. }
  20552. this.add( this.lightSphere );
  20553. this.add( this.lightRays );
  20554. this.add( this.lightDistance );
  20555. //
  20556. this.lightSphere.properties.isGizmo = true;
  20557. this.lightSphere.properties.gizmoSubject = light;
  20558. this.lightSphere.properties.gizmoRoot = this;
  20559. //
  20560. this.properties.isGizmo = true;
  20561. }
  20562. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20563. THREE.PointLightHelper.prototype.update = function () {
  20564. // update sphere and rays colors to light color * light intensity
  20565. this.color.copy( this.light.color );
  20566. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20567. this.color.r *= intensity;
  20568. this.color.g *= intensity;
  20569. this.color.b *= intensity;
  20570. this.lightSphere.material.color.copy( this.color );
  20571. this.lightRays.material.color.copy( this.color );
  20572. this.lightDistance.material.color.copy( this.color );
  20573. //
  20574. var d = this.light.distance;
  20575. if ( d === 0.0 ) {
  20576. this.lightDistance.visible = false;
  20577. } else {
  20578. this.lightDistance.visible = true;
  20579. this.lightDistance.scale.set( d, d, d );
  20580. }
  20581. }
  20582. /**
  20583. * @author alteredq / http://alteredqualia.com/
  20584. *
  20585. * - shows spot light color, intensity, position, orientation, light cone and target
  20586. */
  20587. THREE.SpotLightHelper = function ( light, sphereSize, arrowLength ) {
  20588. THREE.Object3D.call( this );
  20589. this.light = light;
  20590. // position
  20591. this.position = light.position;
  20592. // direction
  20593. this.direction = new THREE.Vector3();
  20594. this.direction.sub( light.target.position, light.position );
  20595. // color
  20596. this.color = light.color.clone();
  20597. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20598. this.color.r *= intensity;
  20599. this.color.g *= intensity;
  20600. this.color.b *= intensity;
  20601. var hexColor = this.color.getHex();
  20602. // light helper
  20603. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20604. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20605. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20606. var coneMatrix = new THREE.Matrix4();
  20607. coneMatrix.rotateX( -Math.PI/2 );
  20608. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  20609. coneGeometry.applyMatrix( coneMatrix );
  20610. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20611. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20612. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20613. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  20614. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20615. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  20616. var coneLength = light.distance ? light.distance : 10000;
  20617. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  20618. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20619. this.lightArrow.cone.material.fog = false;
  20620. this.lightArrow.line.material.fog = false;
  20621. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20622. this.gyroscope = new THREE.Gyroscope();
  20623. this.gyroscope.add( this.lightArrow );
  20624. this.gyroscope.add( this.lightSphere );
  20625. this.gyroscope.add( this.lightRays );
  20626. this.add( this.gyroscope );
  20627. this.add( this.lightCone );
  20628. this.lookAt( light.target.position );
  20629. this.lightSphere.properties.isGizmo = true;
  20630. this.lightSphere.properties.gizmoSubject = light;
  20631. this.lightSphere.properties.gizmoRoot = this;
  20632. // light target helper
  20633. this.targetSphere = null;
  20634. if ( light.target.properties.targetInverse ) {
  20635. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20636. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20637. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20638. this.targetSphere.position = light.target.position;
  20639. this.targetSphere.properties.isGizmo = true;
  20640. this.targetSphere.properties.gizmoSubject = light.target;
  20641. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20642. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20643. var lineGeometry = new THREE.Geometry();
  20644. lineGeometry.vertices.push( this.position.clone() );
  20645. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20646. lineGeometry.computeLineDistances();
  20647. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20648. this.targetLine.properties.isGizmo = true;
  20649. }
  20650. //
  20651. this.properties.isGizmo = true;
  20652. }
  20653. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20654. THREE.SpotLightHelper.prototype.update = function () {
  20655. // update arrow orientation
  20656. // pointing from light to target
  20657. this.direction.sub( this.light.target.position, this.light.position );
  20658. this.lightArrow.setDirection( this.direction );
  20659. // update light cone orientation and size
  20660. this.lookAt( this.light.target.position );
  20661. var coneLength = this.light.distance ? this.light.distance : 10000;
  20662. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  20663. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20664. // update arrow, spheres, rays and line colors to light color * light intensity
  20665. this.color.copy( this.light.color );
  20666. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20667. this.color.r *= intensity;
  20668. this.color.g *= intensity;
  20669. this.color.b *= intensity;
  20670. this.lightArrow.setColor( this.color.getHex() );
  20671. this.lightSphere.material.color.copy( this.color );
  20672. this.lightRays.material.color.copy( this.color );
  20673. this.lightCone.material.color.copy( this.color );
  20674. this.targetSphere.material.color.copy( this.color );
  20675. this.targetLine.material.color.copy( this.color );
  20676. // update target line vertices
  20677. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20678. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20679. this.targetLine.geometry.computeLineDistances();
  20680. this.targetLine.geometry.verticesNeedUpdate = true;
  20681. }
  20682. /**
  20683. * @author alteredq / http://alteredqualia.com/
  20684. */
  20685. THREE.ImmediateRenderObject = function ( ) {
  20686. THREE.Object3D.call( this );
  20687. this.render = function ( renderCallback ) { };
  20688. };
  20689. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20690. /**
  20691. * @author mikael emtinger / http://gomo.se/
  20692. * @author alteredq / http://alteredqualia.com/
  20693. */
  20694. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20695. THREE.Object3D.call( this );
  20696. this.lensFlares = [];
  20697. this.positionScreen = new THREE.Vector3();
  20698. this.customUpdateCallback = undefined;
  20699. if( texture !== undefined ) {
  20700. this.add( texture, size, distance, blending, color );
  20701. }
  20702. };
  20703. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20704. /*
  20705. * Add: adds another flare
  20706. */
  20707. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20708. if( size === undefined ) size = -1;
  20709. if( distance === undefined ) distance = 0;
  20710. if( opacity === undefined ) opacity = 1;
  20711. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20712. if( blending === undefined ) blending = THREE.NormalBlending;
  20713. distance = Math.min( distance, Math.max( 0, distance ) );
  20714. this.lensFlares.push( { texture: texture, // THREE.Texture
  20715. size: size, // size in pixels (-1 = use texture.width)
  20716. distance: distance, // distance (0-1) from light source (0=at light source)
  20717. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20718. scale: 1, // scale
  20719. rotation: 1, // rotation
  20720. opacity: opacity, // opacity
  20721. color: color, // color
  20722. blending: blending } ); // blending
  20723. };
  20724. /*
  20725. * Update lens flares update positions on all flares based on the screen position
  20726. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20727. */
  20728. THREE.LensFlare.prototype.updateLensFlares = function () {
  20729. var f, fl = this.lensFlares.length;
  20730. var flare;
  20731. var vecX = -this.positionScreen.x * 2;
  20732. var vecY = -this.positionScreen.y * 2;
  20733. for( f = 0; f < fl; f ++ ) {
  20734. flare = this.lensFlares[ f ];
  20735. flare.x = this.positionScreen.x + vecX * flare.distance;
  20736. flare.y = this.positionScreen.y + vecY * flare.distance;
  20737. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20738. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20739. }
  20740. };
  20741. /**
  20742. * @author alteredq / http://alteredqualia.com/
  20743. */
  20744. THREE.MorphBlendMesh = function( geometry, material ) {
  20745. THREE.Mesh.call( this, geometry, material );
  20746. this.animationsMap = {};
  20747. this.animationsList = [];
  20748. // prepare default animation
  20749. // (all frames played together in 1 second)
  20750. var numFrames = this.geometry.morphTargets.length;
  20751. var name = "__default";
  20752. var startFrame = 0;
  20753. var endFrame = numFrames - 1;
  20754. var fps = numFrames / 1;
  20755. this.createAnimation( name, startFrame, endFrame, fps );
  20756. this.setAnimationWeight( name, 1 );
  20757. };
  20758. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20759. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20760. var animation = {
  20761. startFrame: start,
  20762. endFrame: end,
  20763. length: end - start + 1,
  20764. fps: fps,
  20765. duration: ( end - start ) / fps,
  20766. lastFrame: 0,
  20767. currentFrame: 0,
  20768. active: false,
  20769. time: 0,
  20770. direction: 1,
  20771. weight: 1,
  20772. directionBackwards: false,
  20773. mirroredLoop: false
  20774. };
  20775. this.animationsMap[ name ] = animation;
  20776. this.animationsList.push( animation );
  20777. };
  20778. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20779. var pattern = /([a-z]+)(\d+)/;
  20780. var firstAnimation, frameRanges = {};
  20781. var geometry = this.geometry;
  20782. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20783. var morph = geometry.morphTargets[ i ];
  20784. var chunks = morph.name.match( pattern );
  20785. if ( chunks && chunks.length > 1 ) {
  20786. var name = chunks[ 1 ];
  20787. var num = chunks[ 2 ];
  20788. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20789. var range = frameRanges[ name ];
  20790. if ( i < range.start ) range.start = i;
  20791. if ( i > range.end ) range.end = i;
  20792. if ( ! firstAnimation ) firstAnimation = name;
  20793. }
  20794. }
  20795. for ( var name in frameRanges ) {
  20796. var range = frameRanges[ name ];
  20797. this.createAnimation( name, range.start, range.end, fps );
  20798. }
  20799. this.firstAnimation = firstAnimation;
  20800. };
  20801. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20802. var animation = this.animationsMap[ name ];
  20803. if ( animation ) {
  20804. animation.direction = 1;
  20805. animation.directionBackwards = false;
  20806. }
  20807. };
  20808. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20809. var animation = this.animationsMap[ name ];
  20810. if ( animation ) {
  20811. animation.direction = -1;
  20812. animation.directionBackwards = true;
  20813. }
  20814. };
  20815. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20816. var animation = this.animationsMap[ name ];
  20817. if ( animation ) {
  20818. animation.fps = fps;
  20819. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20820. }
  20821. };
  20822. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20823. var animation = this.animationsMap[ name ];
  20824. if ( animation ) {
  20825. animation.duration = duration;
  20826. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20827. }
  20828. };
  20829. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20830. var animation = this.animationsMap[ name ];
  20831. if ( animation ) {
  20832. animation.weight = weight;
  20833. }
  20834. };
  20835. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20836. var animation = this.animationsMap[ name ];
  20837. if ( animation ) {
  20838. animation.time = time;
  20839. }
  20840. };
  20841. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20842. var time = 0;
  20843. var animation = this.animationsMap[ name ];
  20844. if ( animation ) {
  20845. time = animation.time;
  20846. }
  20847. return time;
  20848. };
  20849. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20850. var duration = -1;
  20851. var animation = this.animationsMap[ name ];
  20852. if ( animation ) {
  20853. duration = animation.duration;
  20854. }
  20855. return duration;
  20856. };
  20857. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20858. var animation = this.animationsMap[ name ];
  20859. if ( animation ) {
  20860. animation.time = 0;
  20861. animation.active = true;
  20862. } else {
  20863. console.warn( "animation[" + name + "] undefined" );
  20864. }
  20865. };
  20866. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20867. var animation = this.animationsMap[ name ];
  20868. if ( animation ) {
  20869. animation.active = false;
  20870. }
  20871. };
  20872. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20873. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20874. var animation = this.animationsList[ i ];
  20875. if ( ! animation.active ) continue;
  20876. var frameTime = animation.duration / animation.length;
  20877. animation.time += animation.direction * delta;
  20878. if ( animation.mirroredLoop ) {
  20879. if ( animation.time > animation.duration || animation.time < 0 ) {
  20880. animation.direction *= -1;
  20881. if ( animation.time > animation.duration ) {
  20882. animation.time = animation.duration;
  20883. animation.directionBackwards = true;
  20884. }
  20885. if ( animation.time < 0 ) {
  20886. animation.time = 0;
  20887. animation.directionBackwards = false;
  20888. }
  20889. }
  20890. } else {
  20891. animation.time = animation.time % animation.duration;
  20892. if ( animation.time < 0 ) animation.time += animation.duration;
  20893. }
  20894. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20895. var weight = animation.weight;
  20896. if ( keyframe !== animation.currentFrame ) {
  20897. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20898. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20899. this.morphTargetInfluences[ keyframe ] = 0;
  20900. animation.lastFrame = animation.currentFrame;
  20901. animation.currentFrame = keyframe;
  20902. }
  20903. var mix = ( animation.time % frameTime ) / frameTime;
  20904. if ( animation.directionBackwards ) mix = 1 - mix;
  20905. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20906. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20907. }
  20908. };
  20909. /**
  20910. * @author mikael emtinger / http://gomo.se/
  20911. * @author alteredq / http://alteredqualia.com/
  20912. */
  20913. THREE.LensFlarePlugin = function ( ) {
  20914. var _gl, _renderer, _lensFlare = {};
  20915. this.init = function ( renderer ) {
  20916. _gl = renderer.context;
  20917. _renderer = renderer;
  20918. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20919. _lensFlare.faces = new Uint16Array( 6 );
  20920. var i = 0;
  20921. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20922. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20923. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20924. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20925. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20926. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20927. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20928. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20929. i = 0;
  20930. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20931. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20932. // buffers
  20933. _lensFlare.vertexBuffer = _gl.createBuffer();
  20934. _lensFlare.elementBuffer = _gl.createBuffer();
  20935. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20936. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20937. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20938. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20939. // textures
  20940. _lensFlare.tempTexture = _gl.createTexture();
  20941. _lensFlare.occlusionTexture = _gl.createTexture();
  20942. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20943. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20944. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20945. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20946. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20947. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20948. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20949. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20950. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20951. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20952. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20953. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20954. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20955. _lensFlare.hasVertexTexture = false;
  20956. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  20957. } else {
  20958. _lensFlare.hasVertexTexture = true;
  20959. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  20960. }
  20961. _lensFlare.attributes = {};
  20962. _lensFlare.uniforms = {};
  20963. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20964. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20965. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20966. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20967. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20968. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20969. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20970. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20971. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20972. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20973. };
  20974. /*
  20975. * Render lens flares
  20976. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20977. * reads these back and calculates occlusion.
  20978. * Then _lensFlare.update_lensFlares() is called to re-position and
  20979. * update transparency of flares. Then they are rendered.
  20980. *
  20981. */
  20982. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20983. var flares = scene.__webglFlares,
  20984. nFlares = flares.length;
  20985. if ( ! nFlares ) return;
  20986. var tempPosition = new THREE.Vector3();
  20987. var invAspect = viewportHeight / viewportWidth,
  20988. halfViewportWidth = viewportWidth * 0.5,
  20989. halfViewportHeight = viewportHeight * 0.5;
  20990. var size = 16 / viewportHeight,
  20991. scale = new THREE.Vector2( size * invAspect, size );
  20992. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20993. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20994. var uniforms = _lensFlare.uniforms,
  20995. attributes = _lensFlare.attributes;
  20996. // set _lensFlare program and reset blending
  20997. _gl.useProgram( _lensFlare.program );
  20998. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20999. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21000. // loop through all lens flares to update their occlusion and positions
  21001. // setup gl and common used attribs/unforms
  21002. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21003. _gl.uniform1i( uniforms.map, 1 );
  21004. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21005. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21006. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21007. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21008. _gl.disable( _gl.CULL_FACE );
  21009. _gl.depthMask( false );
  21010. var i, j, jl, flare, sprite;
  21011. for ( i = 0; i < nFlares; i ++ ) {
  21012. size = 16 / viewportHeight;
  21013. scale.set( size * invAspect, size );
  21014. // calc object screen position
  21015. flare = flares[ i ];
  21016. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21017. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  21018. camera.projectionMatrix.multiplyVector3( tempPosition );
  21019. // setup arrays for gl programs
  21020. screenPosition.copy( tempPosition )
  21021. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21022. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21023. // screen cull
  21024. if ( _lensFlare.hasVertexTexture || (
  21025. screenPositionPixels.x > 0 &&
  21026. screenPositionPixels.x < viewportWidth &&
  21027. screenPositionPixels.y > 0 &&
  21028. screenPositionPixels.y < viewportHeight ) ) {
  21029. // save current RGB to temp texture
  21030. _gl.activeTexture( _gl.TEXTURE1 );
  21031. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21032. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21033. // render pink quad
  21034. _gl.uniform1i( uniforms.renderType, 0 );
  21035. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21036. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21037. _gl.disable( _gl.BLEND );
  21038. _gl.enable( _gl.DEPTH_TEST );
  21039. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21040. // copy result to occlusionMap
  21041. _gl.activeTexture( _gl.TEXTURE0 );
  21042. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21043. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21044. // restore graphics
  21045. _gl.uniform1i( uniforms.renderType, 1 );
  21046. _gl.disable( _gl.DEPTH_TEST );
  21047. _gl.activeTexture( _gl.TEXTURE1 );
  21048. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21049. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21050. // update object positions
  21051. flare.positionScreen.copy( screenPosition )
  21052. if ( flare.customUpdateCallback ) {
  21053. flare.customUpdateCallback( flare );
  21054. } else {
  21055. flare.updateLensFlares();
  21056. }
  21057. // render flares
  21058. _gl.uniform1i( uniforms.renderType, 2 );
  21059. _gl.enable( _gl.BLEND );
  21060. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21061. sprite = flare.lensFlares[ j ];
  21062. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21063. screenPosition.x = sprite.x;
  21064. screenPosition.y = sprite.y;
  21065. screenPosition.z = sprite.z;
  21066. size = sprite.size * sprite.scale / viewportHeight;
  21067. scale.x = size * invAspect;
  21068. scale.y = size;
  21069. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21070. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21071. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21072. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21073. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21074. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21075. _renderer.setTexture( sprite.texture, 1 );
  21076. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21077. }
  21078. }
  21079. }
  21080. }
  21081. // restore gl
  21082. _gl.enable( _gl.CULL_FACE );
  21083. _gl.enable( _gl.DEPTH_TEST );
  21084. _gl.depthMask( true );
  21085. };
  21086. function createProgram ( shader ) {
  21087. var program = _gl.createProgram();
  21088. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21089. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21090. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21091. _gl.shaderSource( vertexShader, shader.vertexShader );
  21092. _gl.compileShader( fragmentShader );
  21093. _gl.compileShader( vertexShader );
  21094. _gl.attachShader( program, fragmentShader );
  21095. _gl.attachShader( program, vertexShader );
  21096. _gl.linkProgram( program );
  21097. return program;
  21098. };
  21099. };/**
  21100. * @author alteredq / http://alteredqualia.com/
  21101. */
  21102. THREE.ShadowMapPlugin = function ( ) {
  21103. var _gl,
  21104. _renderer,
  21105. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21106. _frustum = new THREE.Frustum(),
  21107. _projScreenMatrix = new THREE.Matrix4(),
  21108. _min = new THREE.Vector3(),
  21109. _max = new THREE.Vector3();
  21110. this.init = function ( renderer ) {
  21111. _gl = renderer.context;
  21112. _renderer = renderer;
  21113. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21114. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21115. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21116. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21117. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21118. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21119. _depthMaterial._shadowPass = true;
  21120. _depthMaterialMorph._shadowPass = true;
  21121. _depthMaterialSkin._shadowPass = true;
  21122. _depthMaterialMorphSkin._shadowPass = true;
  21123. };
  21124. this.render = function ( scene, camera ) {
  21125. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21126. this.update( scene, camera );
  21127. };
  21128. this.update = function ( scene, camera ) {
  21129. var i, il, j, jl, n,
  21130. shadowMap, shadowMatrix, shadowCamera,
  21131. program, buffer, material,
  21132. webglObject, object, light,
  21133. renderList,
  21134. lights = [],
  21135. k = 0,
  21136. fog = null;
  21137. // set GL state for depth map
  21138. _gl.clearColor( 1, 1, 1, 1 );
  21139. _gl.disable( _gl.BLEND );
  21140. _gl.enable( _gl.CULL_FACE );
  21141. _gl.frontFace( _gl.CCW );
  21142. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21143. _gl.cullFace( _gl.FRONT );
  21144. } else {
  21145. _gl.cullFace( _gl.BACK );
  21146. }
  21147. _renderer.setDepthTest( true );
  21148. // preprocess lights
  21149. // - skip lights that are not casting shadows
  21150. // - create virtual lights for cascaded shadow maps
  21151. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21152. light = scene.__lights[ i ];
  21153. if ( ! light.castShadow ) continue;
  21154. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21155. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21156. var virtualLight;
  21157. if ( ! light.shadowCascadeArray[ n ] ) {
  21158. virtualLight = createVirtualLight( light, n );
  21159. virtualLight.originalCamera = camera;
  21160. var gyro = new THREE.Gyroscope();
  21161. gyro.position = light.shadowCascadeOffset;
  21162. gyro.add( virtualLight );
  21163. gyro.add( virtualLight.target );
  21164. camera.add( gyro );
  21165. light.shadowCascadeArray[ n ] = virtualLight;
  21166. console.log( "Created virtualLight", virtualLight );
  21167. } else {
  21168. virtualLight = light.shadowCascadeArray[ n ];
  21169. }
  21170. updateVirtualLight( light, n );
  21171. lights[ k ] = virtualLight;
  21172. k ++;
  21173. }
  21174. } else {
  21175. lights[ k ] = light;
  21176. k ++;
  21177. }
  21178. }
  21179. // render depth map
  21180. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21181. light = lights[ i ];
  21182. if ( ! light.shadowMap ) {
  21183. var shadowFilter = THREE.LinearFilter;
  21184. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21185. shadowFilter = THREE.NearestFilter;
  21186. }
  21187. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21188. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21189. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21190. light.shadowMatrix = new THREE.Matrix4();
  21191. }
  21192. if ( ! light.shadowCamera ) {
  21193. if ( light instanceof THREE.SpotLight ) {
  21194. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21195. } else if ( light instanceof THREE.DirectionalLight ) {
  21196. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21197. } else {
  21198. console.error( "Unsupported light type for shadow" );
  21199. continue;
  21200. }
  21201. scene.add( light.shadowCamera );
  21202. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21203. }
  21204. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21205. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21206. light.shadowCamera.add( light.cameraHelper );
  21207. }
  21208. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21209. updateShadowCamera( camera, light );
  21210. }
  21211. shadowMap = light.shadowMap;
  21212. shadowMatrix = light.shadowMatrix;
  21213. shadowCamera = light.shadowCamera;
  21214. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  21215. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  21216. shadowCamera.updateMatrixWorld();
  21217. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21218. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21219. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21220. // compute shadow matrix
  21221. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21222. 0.0, 0.5, 0.0, 0.5,
  21223. 0.0, 0.0, 0.5, 0.5,
  21224. 0.0, 0.0, 0.0, 1.0 );
  21225. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  21226. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  21227. // update camera matrices and frustum
  21228. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21229. _frustum.setFromMatrix( _projScreenMatrix );
  21230. // render shadow map
  21231. _renderer.setRenderTarget( shadowMap );
  21232. _renderer.clear();
  21233. // set object matrices & frustum culling
  21234. renderList = scene.__webglObjects;
  21235. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21236. webglObject = renderList[ j ];
  21237. object = webglObject.object;
  21238. webglObject.render = false;
  21239. if ( object.visible && object.castShadow ) {
  21240. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21241. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21242. webglObject.render = true;
  21243. }
  21244. }
  21245. }
  21246. // render regular objects
  21247. var objectMaterial, useMorphing, useSkinning;
  21248. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21249. webglObject = renderList[ j ];
  21250. if ( webglObject.render ) {
  21251. object = webglObject.object;
  21252. buffer = webglObject.buffer;
  21253. // culling is overriden globally for all objects
  21254. // while rendering depth map
  21255. // need to deal with MeshFaceMaterial somehow
  21256. // in that case just use the first of material.materials for now
  21257. // (proper solution would require to break objects by materials
  21258. // similarly to regular rendering and then set corresponding
  21259. // depth materials per each chunk instead of just once per object)
  21260. objectMaterial = getObjectMaterial( object );
  21261. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21262. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21263. if ( object.customDepthMaterial ) {
  21264. material = object.customDepthMaterial;
  21265. } else if ( useSkinning ) {
  21266. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21267. } else if ( useMorphing ) {
  21268. material = _depthMaterialMorph;
  21269. } else {
  21270. material = _depthMaterial;
  21271. }
  21272. if ( buffer instanceof THREE.BufferGeometry ) {
  21273. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21274. } else {
  21275. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21276. }
  21277. }
  21278. }
  21279. // set matrices and render immediate objects
  21280. renderList = scene.__webglObjectsImmediate;
  21281. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21282. webglObject = renderList[ j ];
  21283. object = webglObject.object;
  21284. if ( object.visible && object.castShadow ) {
  21285. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21286. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21287. }
  21288. }
  21289. }
  21290. // restore GL state
  21291. var clearColor = _renderer.getClearColor(),
  21292. clearAlpha = _renderer.getClearAlpha();
  21293. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21294. _gl.enable( _gl.BLEND );
  21295. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21296. _gl.cullFace( _gl.BACK );
  21297. }
  21298. };
  21299. function createVirtualLight( light, cascade ) {
  21300. var virtualLight = new THREE.DirectionalLight();
  21301. virtualLight.isVirtual = true;
  21302. virtualLight.onlyShadow = true;
  21303. virtualLight.castShadow = true;
  21304. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21305. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21306. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21307. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21308. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21309. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21310. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21311. virtualLight.shadowDarkness = light.shadowDarkness;
  21312. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21313. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21314. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21315. virtualLight.pointsWorld = [];
  21316. virtualLight.pointsFrustum = [];
  21317. var pointsWorld = virtualLight.pointsWorld,
  21318. pointsFrustum = virtualLight.pointsFrustum;
  21319. for ( var i = 0; i < 8; i ++ ) {
  21320. pointsWorld[ i ] = new THREE.Vector3();
  21321. pointsFrustum[ i ] = new THREE.Vector3();
  21322. }
  21323. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21324. var farZ = light.shadowCascadeFarZ[ cascade ];
  21325. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21326. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21327. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21328. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21329. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21330. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21331. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21332. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21333. return virtualLight;
  21334. }
  21335. // Synchronize virtual light with the original light
  21336. function updateVirtualLight( light, cascade ) {
  21337. var virtualLight = light.shadowCascadeArray[ cascade ];
  21338. virtualLight.position.copy( light.position );
  21339. virtualLight.target.position.copy( light.target.position );
  21340. virtualLight.lookAt( virtualLight.target );
  21341. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21342. virtualLight.shadowDarkness = light.shadowDarkness;
  21343. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21344. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21345. var farZ = light.shadowCascadeFarZ[ cascade ];
  21346. var pointsFrustum = virtualLight.pointsFrustum;
  21347. pointsFrustum[ 0 ].z = nearZ;
  21348. pointsFrustum[ 1 ].z = nearZ;
  21349. pointsFrustum[ 2 ].z = nearZ;
  21350. pointsFrustum[ 3 ].z = nearZ;
  21351. pointsFrustum[ 4 ].z = farZ;
  21352. pointsFrustum[ 5 ].z = farZ;
  21353. pointsFrustum[ 6 ].z = farZ;
  21354. pointsFrustum[ 7 ].z = farZ;
  21355. }
  21356. // Fit shadow camera's ortho frustum to camera frustum
  21357. function updateShadowCamera( camera, light ) {
  21358. var shadowCamera = light.shadowCamera,
  21359. pointsFrustum = light.pointsFrustum,
  21360. pointsWorld = light.pointsWorld;
  21361. _min.set( Infinity, Infinity, Infinity );
  21362. _max.set( -Infinity, -Infinity, -Infinity );
  21363. for ( var i = 0; i < 8; i ++ ) {
  21364. var p = pointsWorld[ i ];
  21365. p.copy( pointsFrustum[ i ] );
  21366. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21367. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  21368. if ( p.x < _min.x ) _min.x = p.x;
  21369. if ( p.x > _max.x ) _max.x = p.x;
  21370. if ( p.y < _min.y ) _min.y = p.y;
  21371. if ( p.y > _max.y ) _max.y = p.y;
  21372. if ( p.z < _min.z ) _min.z = p.z;
  21373. if ( p.z > _max.z ) _max.z = p.z;
  21374. }
  21375. shadowCamera.left = _min.x;
  21376. shadowCamera.right = _max.x;
  21377. shadowCamera.top = _max.y;
  21378. shadowCamera.bottom = _min.y;
  21379. // can't really fit near/far
  21380. //shadowCamera.near = _min.z;
  21381. //shadowCamera.far = _max.z;
  21382. shadowCamera.updateProjectionMatrix();
  21383. }
  21384. // For the moment just ignore objects that have multiple materials with different animation methods
  21385. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21386. function getObjectMaterial( object ) {
  21387. return object.material instanceof THREE.MeshFaceMaterial
  21388. ? object.material.materials[ 0 ]
  21389. : object.material;
  21390. };
  21391. };
  21392. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21393. /**
  21394. * @author mikael emtinger / http://gomo.se/
  21395. * @author alteredq / http://alteredqualia.com/
  21396. */
  21397. THREE.SpritePlugin = function ( ) {
  21398. var _gl, _renderer, _sprite = {};
  21399. this.init = function ( renderer ) {
  21400. _gl = renderer.context;
  21401. _renderer = renderer;
  21402. _sprite.vertices = new Float32Array( 8 + 8 );
  21403. _sprite.faces = new Uint16Array( 6 );
  21404. var i = 0;
  21405. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21406. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21407. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21408. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21409. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21410. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21411. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21412. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21413. i = 0;
  21414. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21415. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21416. _sprite.vertexBuffer = _gl.createBuffer();
  21417. _sprite.elementBuffer = _gl.createBuffer();
  21418. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21419. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21420. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21421. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21422. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  21423. _sprite.attributes = {};
  21424. _sprite.uniforms = {};
  21425. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21426. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21427. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21428. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21429. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21430. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21431. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21432. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21433. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21434. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21435. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21436. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21437. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21438. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21439. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21440. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21441. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21442. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21443. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21444. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21445. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21446. };
  21447. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21448. var sprites = scene.__webglSprites,
  21449. nSprites = sprites.length;
  21450. if ( ! nSprites ) return;
  21451. var attributes = _sprite.attributes,
  21452. uniforms = _sprite.uniforms;
  21453. var invAspect = viewportHeight / viewportWidth;
  21454. var halfViewportWidth = viewportWidth * 0.5,
  21455. halfViewportHeight = viewportHeight * 0.5;
  21456. // setup gl
  21457. _gl.useProgram( _sprite.program );
  21458. _gl.enableVertexAttribArray( attributes.position );
  21459. _gl.enableVertexAttribArray( attributes.uv );
  21460. _gl.disable( _gl.CULL_FACE );
  21461. _gl.enable( _gl.BLEND );
  21462. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21463. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21464. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21465. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21466. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21467. _gl.activeTexture( _gl.TEXTURE0 );
  21468. _gl.uniform1i( uniforms.map, 0 );
  21469. var oldFogType = 0;
  21470. var sceneFogType = 0;
  21471. var fog = scene.fog;
  21472. if ( fog ) {
  21473. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21474. if ( fog instanceof THREE.Fog ) {
  21475. _gl.uniform1f( uniforms.fogNear, fog.near );
  21476. _gl.uniform1f( uniforms.fogFar, fog.far );
  21477. _gl.uniform1i( uniforms.fogType, 1 );
  21478. oldFogType = 1;
  21479. sceneFogType = 1;
  21480. } else if ( fog instanceof THREE.FogExp2 ) {
  21481. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21482. _gl.uniform1i( uniforms.fogType, 2 );
  21483. oldFogType = 2;
  21484. sceneFogType = 2;
  21485. }
  21486. } else {
  21487. _gl.uniform1i( uniforms.fogType, 0 );
  21488. oldFogType = 0;
  21489. sceneFogType = 0;
  21490. }
  21491. // update positions and sort
  21492. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21493. for( i = 0; i < nSprites; i ++ ) {
  21494. sprite = sprites[ i ];
  21495. material = sprite.material;
  21496. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21497. if ( ! material.useScreenCoordinates ) {
  21498. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  21499. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21500. } else {
  21501. sprite.z = - sprite.position.z;
  21502. }
  21503. }
  21504. sprites.sort( painterSortStable );
  21505. // render all sprites
  21506. for( i = 0; i < nSprites; i ++ ) {
  21507. sprite = sprites[ i ];
  21508. material = sprite.material;
  21509. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21510. if ( material.map && material.map.image && material.map.image.width ) {
  21511. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21512. if ( material.useScreenCoordinates ) {
  21513. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21514. _gl.uniform3f(
  21515. uniforms.screenPosition,
  21516. ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  21517. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  21518. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21519. );
  21520. } else {
  21521. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21522. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21523. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21524. }
  21525. if ( scene.fog && material.fog ) {
  21526. fogType = sceneFogType;
  21527. } else {
  21528. fogType = 0;
  21529. }
  21530. if ( oldFogType !== fogType ) {
  21531. _gl.uniform1i( uniforms.fogType, fogType );
  21532. oldFogType = fogType;
  21533. }
  21534. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21535. scale[ 0 ] = size * invAspect * sprite.scale.x;
  21536. scale[ 1 ] = size * sprite.scale.y;
  21537. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21538. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21539. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21540. _gl.uniform1f( uniforms.opacity, material.opacity );
  21541. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21542. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21543. _gl.uniform2fv( uniforms.scale, scale );
  21544. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21545. _renderer.setDepthTest( material.depthTest );
  21546. _renderer.setDepthWrite( material.depthWrite );
  21547. _renderer.setTexture( material.map, 0 );
  21548. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21549. }
  21550. }
  21551. // restore gl
  21552. _gl.enable( _gl.CULL_FACE );
  21553. };
  21554. function createProgram ( shader ) {
  21555. var program = _gl.createProgram();
  21556. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21557. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21558. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21559. _gl.shaderSource( vertexShader, shader.vertexShader );
  21560. _gl.compileShader( fragmentShader );
  21561. _gl.compileShader( vertexShader );
  21562. _gl.attachShader( program, fragmentShader );
  21563. _gl.attachShader( program, vertexShader );
  21564. _gl.linkProgram( program );
  21565. return program;
  21566. };
  21567. function painterSortStable ( a, b ) {
  21568. if ( a.z !== b.z ) {
  21569. return b.z - a.z;
  21570. } else {
  21571. return b.id - a.id;
  21572. }
  21573. };
  21574. };/**
  21575. * @author alteredq / http://alteredqualia.com/
  21576. */
  21577. THREE.DepthPassPlugin = function ( ) {
  21578. this.enabled = false;
  21579. this.renderTarget = null;
  21580. var _gl,
  21581. _renderer,
  21582. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21583. _frustum = new THREE.Frustum(),
  21584. _projScreenMatrix = new THREE.Matrix4();
  21585. this.init = function ( renderer ) {
  21586. _gl = renderer.context;
  21587. _renderer = renderer;
  21588. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21589. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21590. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21591. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21592. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21593. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21594. _depthMaterial._shadowPass = true;
  21595. _depthMaterialMorph._shadowPass = true;
  21596. _depthMaterialSkin._shadowPass = true;
  21597. _depthMaterialMorphSkin._shadowPass = true;
  21598. };
  21599. this.render = function ( scene, camera ) {
  21600. if ( ! this.enabled ) return;
  21601. this.update( scene, camera );
  21602. };
  21603. this.update = function ( scene, camera ) {
  21604. var i, il, j, jl, n,
  21605. program, buffer, material,
  21606. webglObject, object, light,
  21607. renderList,
  21608. fog = null;
  21609. // set GL state for depth map
  21610. _gl.clearColor( 1, 1, 1, 1 );
  21611. _gl.disable( _gl.BLEND );
  21612. _renderer.setDepthTest( true );
  21613. // update scene
  21614. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21615. // update camera matrices and frustum
  21616. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21617. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21618. _frustum.setFromMatrix( _projScreenMatrix );
  21619. // render depth map
  21620. _renderer.setRenderTarget( this.renderTarget );
  21621. _renderer.clear();
  21622. // set object matrices & frustum culling
  21623. renderList = scene.__webglObjects;
  21624. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21625. webglObject = renderList[ j ];
  21626. object = webglObject.object;
  21627. webglObject.render = false;
  21628. if ( object.visible ) {
  21629. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21630. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21631. webglObject.render = true;
  21632. }
  21633. }
  21634. }
  21635. // render regular objects
  21636. var objectMaterial, useMorphing, useSkinning;
  21637. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21638. webglObject = renderList[ j ];
  21639. if ( webglObject.render ) {
  21640. object = webglObject.object;
  21641. buffer = webglObject.buffer;
  21642. // todo: create proper depth material for particles
  21643. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21644. objectMaterial = getObjectMaterial( object );
  21645. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21646. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21647. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21648. if ( object.customDepthMaterial ) {
  21649. material = object.customDepthMaterial;
  21650. } else if ( useSkinning ) {
  21651. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21652. } else if ( useMorphing ) {
  21653. material = _depthMaterialMorph;
  21654. } else {
  21655. material = _depthMaterial;
  21656. }
  21657. if ( buffer instanceof THREE.BufferGeometry ) {
  21658. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21659. } else {
  21660. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21661. }
  21662. }
  21663. }
  21664. // set matrices and render immediate objects
  21665. renderList = scene.__webglObjectsImmediate;
  21666. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21667. webglObject = renderList[ j ];
  21668. object = webglObject.object;
  21669. if ( object.visible ) {
  21670. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21671. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21672. }
  21673. }
  21674. // restore GL state
  21675. var clearColor = _renderer.getClearColor(),
  21676. clearAlpha = _renderer.getClearAlpha();
  21677. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21678. _gl.enable( _gl.BLEND );
  21679. };
  21680. // For the moment just ignore objects that have multiple materials with different animation methods
  21681. // Only the first material will be taken into account for deciding which depth material to use
  21682. function getObjectMaterial( object ) {
  21683. return object.material instanceof THREE.MeshFaceMaterial
  21684. ? object.material.materials[ 0 ]
  21685. : object.material;
  21686. };
  21687. };
  21688. /**
  21689. * @author mikael emtinger / http://gomo.se/
  21690. *
  21691. */
  21692. THREE.ShaderFlares = {
  21693. 'lensFlareVertexTexture': {
  21694. vertexShader: [
  21695. "uniform vec3 screenPosition;",
  21696. "uniform vec2 scale;",
  21697. "uniform float rotation;",
  21698. "uniform int renderType;",
  21699. "uniform sampler2D occlusionMap;",
  21700. "attribute vec2 position;",
  21701. "attribute vec2 uv;",
  21702. "varying vec2 vUV;",
  21703. "varying float vVisibility;",
  21704. "void main() {",
  21705. "vUV = uv;",
  21706. "vec2 pos = position;",
  21707. "if( renderType == 2 ) {",
  21708. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21709. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21710. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21711. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21712. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21713. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21714. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21715. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21716. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21717. "vVisibility = ( visibility.r / 9.0 ) *",
  21718. "( 1.0 - visibility.g / 9.0 ) *",
  21719. "( visibility.b / 9.0 ) *",
  21720. "( 1.0 - visibility.a / 9.0 );",
  21721. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21722. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21723. "}",
  21724. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21725. "}"
  21726. ].join( "\n" ),
  21727. fragmentShader: [
  21728. "precision mediump float;",
  21729. "uniform sampler2D map;",
  21730. "uniform float opacity;",
  21731. "uniform int renderType;",
  21732. "uniform vec3 color;",
  21733. "varying vec2 vUV;",
  21734. "varying float vVisibility;",
  21735. "void main() {",
  21736. // pink square
  21737. "if( renderType == 0 ) {",
  21738. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21739. // restore
  21740. "} else if( renderType == 1 ) {",
  21741. "gl_FragColor = texture2D( map, vUV );",
  21742. // flare
  21743. "} else {",
  21744. "vec4 texture = texture2D( map, vUV );",
  21745. "texture.a *= opacity * vVisibility;",
  21746. "gl_FragColor = texture;",
  21747. "gl_FragColor.rgb *= color;",
  21748. "}",
  21749. "}"
  21750. ].join( "\n" )
  21751. },
  21752. 'lensFlare': {
  21753. vertexShader: [
  21754. "uniform vec3 screenPosition;",
  21755. "uniform vec2 scale;",
  21756. "uniform float rotation;",
  21757. "uniform int renderType;",
  21758. "attribute vec2 position;",
  21759. "attribute vec2 uv;",
  21760. "varying vec2 vUV;",
  21761. "void main() {",
  21762. "vUV = uv;",
  21763. "vec2 pos = position;",
  21764. "if( renderType == 2 ) {",
  21765. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21766. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21767. "}",
  21768. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21769. "}"
  21770. ].join( "\n" ),
  21771. fragmentShader: [
  21772. "precision mediump float;",
  21773. "uniform sampler2D map;",
  21774. "uniform sampler2D occlusionMap;",
  21775. "uniform float opacity;",
  21776. "uniform int renderType;",
  21777. "uniform vec3 color;",
  21778. "varying vec2 vUV;",
  21779. "void main() {",
  21780. // pink square
  21781. "if( renderType == 0 ) {",
  21782. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21783. // restore
  21784. "} else if( renderType == 1 ) {",
  21785. "gl_FragColor = texture2D( map, vUV );",
  21786. // flare
  21787. "} else {",
  21788. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21789. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21790. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21791. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21792. "visibility = ( 1.0 - visibility / 4.0 );",
  21793. "vec4 texture = texture2D( map, vUV );",
  21794. "texture.a *= opacity * visibility;",
  21795. "gl_FragColor = texture;",
  21796. "gl_FragColor.rgb *= color;",
  21797. "}",
  21798. "}"
  21799. ].join( "\n" )
  21800. }
  21801. };
  21802. /**
  21803. * @author mikael emtinger / http://gomo.se/
  21804. * @author alteredq / http://alteredqualia.com/
  21805. *
  21806. */
  21807. THREE.ShaderSprite = {
  21808. 'sprite': {
  21809. vertexShader: [
  21810. "uniform int useScreenCoordinates;",
  21811. "uniform int sizeAttenuation;",
  21812. "uniform vec3 screenPosition;",
  21813. "uniform mat4 modelViewMatrix;",
  21814. "uniform mat4 projectionMatrix;",
  21815. "uniform float rotation;",
  21816. "uniform vec2 scale;",
  21817. "uniform vec2 alignment;",
  21818. "uniform vec2 uvOffset;",
  21819. "uniform vec2 uvScale;",
  21820. "attribute vec2 position;",
  21821. "attribute vec2 uv;",
  21822. "varying vec2 vUV;",
  21823. "void main() {",
  21824. "vUV = uvOffset + uv * uvScale;",
  21825. "vec2 alignedPosition = position + alignment;",
  21826. "vec2 rotatedPosition;",
  21827. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21828. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21829. "vec4 finalPosition;",
  21830. "if( useScreenCoordinates != 0 ) {",
  21831. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21832. "} else {",
  21833. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21834. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21835. "}",
  21836. "gl_Position = finalPosition;",
  21837. "}"
  21838. ].join( "\n" ),
  21839. fragmentShader: [
  21840. "precision mediump float;",
  21841. "uniform vec3 color;",
  21842. "uniform sampler2D map;",
  21843. "uniform float opacity;",
  21844. "uniform int fogType;",
  21845. "uniform vec3 fogColor;",
  21846. "uniform float fogDensity;",
  21847. "uniform float fogNear;",
  21848. "uniform float fogFar;",
  21849. "uniform float alphaTest;",
  21850. "varying vec2 vUV;",
  21851. "void main() {",
  21852. "vec4 texture = texture2D( map, vUV );",
  21853. "if ( texture.a < alphaTest ) discard;",
  21854. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21855. "if ( fogType > 0 ) {",
  21856. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21857. "float fogFactor = 0.0;",
  21858. "if ( fogType == 1 ) {",
  21859. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21860. "} else {",
  21861. "const float LOG2 = 1.442695;",
  21862. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21863. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21864. "}",
  21865. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21866. "}",
  21867. "}"
  21868. ].join( "\n" )
  21869. }
  21870. };