three.js 831 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602
  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. // MATERIAL CONSTANTS
  60. // side
  61. THREE.FrontSide = 0;
  62. THREE.BackSide = 1;
  63. THREE.DoubleSide = 2;
  64. // shading
  65. THREE.NoShading = 0;
  66. THREE.FlatShading = 1;
  67. THREE.SmoothShading = 2;
  68. // colors
  69. THREE.NoColors = 0;
  70. THREE.FaceColors = 1;
  71. THREE.VertexColors = 2;
  72. // blending modes
  73. THREE.NoBlending = 0;
  74. THREE.NormalBlending = 1;
  75. THREE.AdditiveBlending = 2;
  76. THREE.SubtractiveBlending = 3;
  77. THREE.MultiplyBlending = 4;
  78. THREE.CustomBlending = 5;
  79. // custom blending equations
  80. // (numbers start from 100 not to clash with other
  81. // mappings to OpenGL constants defined in Texture.js)
  82. THREE.AddEquation = 100;
  83. THREE.SubtractEquation = 101;
  84. THREE.ReverseSubtractEquation = 102;
  85. // custom blending destination factors
  86. THREE.ZeroFactor = 200;
  87. THREE.OneFactor = 201;
  88. THREE.SrcColorFactor = 202;
  89. THREE.OneMinusSrcColorFactor = 203;
  90. THREE.SrcAlphaFactor = 204;
  91. THREE.OneMinusSrcAlphaFactor = 205;
  92. THREE.DstAlphaFactor = 206;
  93. THREE.OneMinusDstAlphaFactor = 207;
  94. // custom blending source factors
  95. //THREE.ZeroFactor = 200;
  96. //THREE.OneFactor = 201;
  97. //THREE.SrcAlphaFactor = 204;
  98. //THREE.OneMinusSrcAlphaFactor = 205;
  99. //THREE.DstAlphaFactor = 206;
  100. //THREE.OneMinusDstAlphaFactor = 207;
  101. THREE.DstColorFactor = 208;
  102. THREE.OneMinusDstColorFactor = 209;
  103. THREE.SrcAlphaSaturateFactor = 210;
  104. // TEXTURE CONSTANTS
  105. THREE.MultiplyOperation = 0;
  106. THREE.MixOperation = 1;
  107. THREE.AddOperation = 2;
  108. // Mapping modes
  109. THREE.UVMapping = function () {};
  110. THREE.CubeReflectionMapping = function () {};
  111. THREE.CubeRefractionMapping = function () {};
  112. THREE.SphericalReflectionMapping = function () {};
  113. THREE.SphericalRefractionMapping = function () {};
  114. // Wrapping modes
  115. THREE.RepeatWrapping = 1000;
  116. THREE.ClampToEdgeWrapping = 1001;
  117. THREE.MirroredRepeatWrapping = 1002;
  118. // Filters
  119. THREE.NearestFilter = 1003;
  120. THREE.NearestMipMapNearestFilter = 1004;
  121. THREE.NearestMipMapLinearFilter = 1005;
  122. THREE.LinearFilter = 1006;
  123. THREE.LinearMipMapNearestFilter = 1007;
  124. THREE.LinearMipMapLinearFilter = 1008;
  125. // Data types
  126. THREE.UnsignedByteType = 1009;
  127. THREE.ByteType = 1010;
  128. THREE.ShortType = 1011;
  129. THREE.UnsignedShortType = 1012;
  130. THREE.IntType = 1013;
  131. THREE.UnsignedIntType = 1014;
  132. THREE.FloatType = 1015;
  133. // Pixel types
  134. //THREE.UnsignedByteType = 1009;
  135. THREE.UnsignedShort4444Type = 1016;
  136. THREE.UnsignedShort5551Type = 1017;
  137. THREE.UnsignedShort565Type = 1018;
  138. // Pixel formats
  139. THREE.AlphaFormat = 1019;
  140. THREE.RGBFormat = 1020;
  141. THREE.RGBAFormat = 1021;
  142. THREE.LuminanceFormat = 1022;
  143. THREE.LuminanceAlphaFormat = 1023;
  144. // Compressed texture formats
  145. THREE.RGB_S3TC_DXT1_Format = 2001;
  146. THREE.RGBA_S3TC_DXT1_Format = 2002;
  147. THREE.RGBA_S3TC_DXT3_Format = 2003;
  148. THREE.RGBA_S3TC_DXT5_Format = 2004;
  149. /*
  150. // Potential future PVRTC compressed texture formats
  151. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  152. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  153. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  154. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  155. */
  156. /**
  157. * @author alteredq / http://alteredqualia.com/
  158. */
  159. THREE.Clock = function ( autoStart ) {
  160. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  161. this.startTime = 0;
  162. this.oldTime = 0;
  163. this.elapsedTime = 0;
  164. this.running = false;
  165. };
  166. THREE.Clock.prototype.start = function () {
  167. this.startTime = Date.now();
  168. this.oldTime = this.startTime;
  169. this.running = true;
  170. };
  171. THREE.Clock.prototype.stop = function () {
  172. this.getElapsedTime();
  173. this.running = false;
  174. };
  175. THREE.Clock.prototype.getElapsedTime = function () {
  176. this.getDelta();
  177. return this.elapsedTime;
  178. };
  179. THREE.Clock.prototype.getDelta = function () {
  180. var diff = 0;
  181. if ( this.autoStart && ! this.running ) {
  182. this.start();
  183. }
  184. if ( this.running ) {
  185. var newTime = Date.now();
  186. diff = 0.001 * ( newTime - this.oldTime );
  187. this.oldTime = newTime;
  188. this.elapsedTime += diff;
  189. }
  190. return diff;
  191. };/**
  192. * @author mrdoob / http://mrdoob.com/
  193. */
  194. THREE.Color = function ( value ) {
  195. if ( value !== undefined ) this.set( value );
  196. return this;
  197. };
  198. THREE.Color.prototype = {
  199. constructor: THREE.Color,
  200. r: 1, g: 1, b: 1,
  201. copy: function ( color ) {
  202. this.r = color.r;
  203. this.g = color.g;
  204. this.b = color.b;
  205. return this;
  206. },
  207. copyGammaToLinear: function ( color ) {
  208. this.r = color.r * color.r;
  209. this.g = color.g * color.g;
  210. this.b = color.b * color.b;
  211. return this;
  212. },
  213. copyLinearToGamma: function ( color ) {
  214. this.r = Math.sqrt( color.r );
  215. this.g = Math.sqrt( color.g );
  216. this.b = Math.sqrt( color.b );
  217. return this;
  218. },
  219. convertGammaToLinear: function () {
  220. var r = this.r, g = this.g, b = this.b;
  221. this.r = r * r;
  222. this.g = g * g;
  223. this.b = b * b;
  224. return this;
  225. },
  226. convertLinearToGamma: function () {
  227. this.r = Math.sqrt( this.r );
  228. this.g = Math.sqrt( this.g );
  229. this.b = Math.sqrt( this.b );
  230. return this;
  231. },
  232. set: function ( value ) {
  233. switch ( typeof value ) {
  234. case "number":
  235. this.setHex( value );
  236. break;
  237. case "string":
  238. this.setStyle( value );
  239. break;
  240. }
  241. },
  242. setRGB: function ( r, g, b ) {
  243. this.r = r;
  244. this.g = g;
  245. this.b = b;
  246. return this;
  247. },
  248. setHSV: function ( h, s, v ) {
  249. // based on MochiKit implementation by Bob Ippolito
  250. // h,s,v ranges are < 0.0 - 1.0 >
  251. var i, f, p, q, t;
  252. if ( v === 0 ) {
  253. this.r = this.g = this.b = 0;
  254. } else {
  255. i = Math.floor( h * 6 );
  256. f = ( h * 6 ) - i;
  257. p = v * ( 1 - s );
  258. q = v * ( 1 - ( s * f ) );
  259. t = v * ( 1 - ( s * ( 1 - f ) ) );
  260. if ( i === 0 ) {
  261. this.r = v;
  262. this.g = t;
  263. this.b = p;
  264. } else if ( i === 1 ) {
  265. this.r = q;
  266. this.g = v;
  267. this.b = p;
  268. } else if ( i === 2 ) {
  269. this.r = p;
  270. this.g = v;
  271. this.b = t;
  272. } else if ( i === 3 ) {
  273. this.r = p;
  274. this.g = q;
  275. this.b = v;
  276. } else if ( i === 4 ) {
  277. this.r = t;
  278. this.g = p;
  279. this.b = v;
  280. } else if ( i === 5 ) {
  281. this.r = v;
  282. this.g = p;
  283. this.b = q;
  284. }
  285. }
  286. return this;
  287. },
  288. getHex: function () {
  289. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  290. },
  291. setHex: function ( hex ) {
  292. hex = Math.floor( hex );
  293. this.r = ( hex >> 16 & 255 ) / 255;
  294. this.g = ( hex >> 8 & 255 ) / 255;
  295. this.b = ( hex & 255 ) / 255;
  296. return this;
  297. },
  298. getHexString: function () {
  299. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  300. },
  301. getStyle: function () {
  302. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  303. },
  304. setStyle: function ( style ) {
  305. // rgb(255,0,0)
  306. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  307. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  308. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  309. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  310. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  311. return this;
  312. }
  313. // rgb(100%,0%,0%)
  314. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  315. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  316. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  317. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  318. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  319. return this;
  320. }
  321. // #ff0000
  322. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  323. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  324. this.setHex( parseInt( color[ 1 ], 16 ) );
  325. return this;
  326. }
  327. // #f00
  328. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  329. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  330. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  331. return this;
  332. }
  333. // red
  334. if ( /^(\w+)$/i.test( style ) ) {
  335. this.setHex( THREE.ColorKeywords[ style ] );
  336. return this;
  337. }
  338. },
  339. getHSV: function ( hsv ) {
  340. // based on MochiKit implementation by Bob Ippolito
  341. // h,s,v ranges are < 0.0 - 1.0 >
  342. var r = this.r;
  343. var g = this.g;
  344. var b = this.b;
  345. var max = Math.max( Math.max( r, g ), b );
  346. var min = Math.min( Math.min( r, g ), b );
  347. var hue;
  348. var saturation;
  349. var value = max;
  350. if ( min === max ) {
  351. hue = 0;
  352. saturation = 0;
  353. } else {
  354. var delta = ( max - min );
  355. saturation = delta / max;
  356. if ( r === max ) {
  357. hue = ( g - b ) / delta;
  358. } else if ( g === max ) {
  359. hue = 2 + ( ( b - r ) / delta );
  360. } else {
  361. hue = 4 + ( ( r - g ) / delta );
  362. }
  363. hue /= 6;
  364. if ( hue < 0 ) {
  365. hue += 1;
  366. }
  367. if ( hue > 1 ) {
  368. hue -= 1;
  369. }
  370. }
  371. if ( hsv === undefined ) {
  372. hsv = { h: 0, s: 0, v: 0 };
  373. }
  374. hsv.h = hue;
  375. hsv.s = saturation;
  376. hsv.v = value;
  377. return hsv;
  378. },
  379. lerpSelf: function ( color, alpha ) {
  380. this.r += ( color.r - this.r ) * alpha;
  381. this.g += ( color.g - this.g ) * alpha;
  382. this.b += ( color.b - this.b ) * alpha;
  383. return this;
  384. },
  385. clone: function () {
  386. return new THREE.Color().setRGB( this.r, this.g, this.b );
  387. }
  388. };
  389. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF, "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2, "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50, "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B, "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B, "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F, "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3, "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222, "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700, "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4, "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00, "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3, "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA, "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32, "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3, "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC, "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD, "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6, "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9, "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F, "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE, "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA, "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0, "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  390. /**
  391. * @author mrdoob / http://mrdoob.com/
  392. * @author philogb / http://blog.thejit.org/
  393. * @author egraether / http://egraether.com/
  394. * @author zz85 / http://www.lab4games.net/zz85/blog
  395. */
  396. THREE.Vector2 = function ( x, y ) {
  397. this.x = x || 0;
  398. this.y = y || 0;
  399. };
  400. THREE.Vector2.prototype = {
  401. constructor: THREE.Vector2,
  402. set: function ( x, y ) {
  403. this.x = x;
  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. add: function ( a, b ) {
  413. this.x = a.x + b.x;
  414. this.y = a.y + b.y;
  415. return this;
  416. },
  417. addSelf: function ( v ) {
  418. this.x += v.x;
  419. this.y += v.y;
  420. return this;
  421. },
  422. sub: function ( a, b ) {
  423. this.x = a.x - b.x;
  424. this.y = a.y - b.y;
  425. return this;
  426. },
  427. subSelf: function ( v ) {
  428. this.x -= v.x;
  429. this.y -= v.y;
  430. return this;
  431. },
  432. multiplyScalar: function ( s ) {
  433. this.x *= s;
  434. this.y *= s;
  435. return this;
  436. },
  437. divideScalar: function ( s ) {
  438. if ( s ) {
  439. this.x /= s;
  440. this.y /= s;
  441. } else {
  442. this.set( 0, 0 );
  443. }
  444. return this;
  445. },
  446. negate: function() {
  447. return this.multiplyScalar( - 1 );
  448. },
  449. dot: function ( v ) {
  450. return this.x * v.x + this.y * v.y;
  451. },
  452. lengthSq: function () {
  453. return this.x * this.x + this.y * this.y;
  454. },
  455. length: function () {
  456. return Math.sqrt( this.lengthSq() );
  457. },
  458. normalize: function () {
  459. return this.divideScalar( this.length() );
  460. },
  461. distanceTo: function ( v ) {
  462. return Math.sqrt( this.distanceToSquared( v ) );
  463. },
  464. distanceToSquared: function ( v ) {
  465. var dx = this.x - v.x, dy = this.y - v.y;
  466. return dx * dx + dy * dy;
  467. },
  468. setLength: function ( l ) {
  469. return this.normalize().multiplyScalar( l );
  470. },
  471. lerpSelf: function ( v, alpha ) {
  472. this.x += ( v.x - this.x ) * alpha;
  473. this.y += ( v.y - this.y ) * alpha;
  474. return this;
  475. },
  476. equals: function( v ) {
  477. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  478. },
  479. clone: function () {
  480. return new THREE.Vector2( this.x, this.y );
  481. }
  482. };
  483. /**
  484. * @author mrdoob / http://mrdoob.com/
  485. * @author kile / http://kile.stravaganza.org/
  486. * @author philogb / http://blog.thejit.org/
  487. * @author mikael emtinger / http://gomo.se/
  488. * @author egraether / http://egraether.com/
  489. * @author WestLangley / http://github.com/WestLangley
  490. */
  491. THREE.Vector3 = function ( x, y, z ) {
  492. this.x = x || 0;
  493. this.y = y || 0;
  494. this.z = z || 0;
  495. };
  496. THREE.Vector3.prototype = {
  497. constructor: THREE.Vector3,
  498. set: function ( x, y, z ) {
  499. this.x = x;
  500. this.y = y;
  501. this.z = z;
  502. return this;
  503. },
  504. setX: function ( x ) {
  505. this.x = x;
  506. return this;
  507. },
  508. setY: function ( y ) {
  509. this.y = y;
  510. return this;
  511. },
  512. setZ: function ( z ) {
  513. this.z = z;
  514. return this;
  515. },
  516. copy: function ( v ) {
  517. this.x = v.x;
  518. this.y = v.y;
  519. this.z = v.z;
  520. return this;
  521. },
  522. add: function ( a, b ) {
  523. this.x = a.x + b.x;
  524. this.y = a.y + b.y;
  525. this.z = a.z + b.z;
  526. return this;
  527. },
  528. addSelf: function ( v ) {
  529. this.x += v.x;
  530. this.y += v.y;
  531. this.z += v.z;
  532. return this;
  533. },
  534. addScalar: function ( s ) {
  535. this.x += s;
  536. this.y += s;
  537. this.z += s;
  538. return this;
  539. },
  540. sub: function ( a, b ) {
  541. this.x = a.x - b.x;
  542. this.y = a.y - b.y;
  543. this.z = a.z - b.z;
  544. return this;
  545. },
  546. subSelf: function ( v ) {
  547. this.x -= v.x;
  548. this.y -= v.y;
  549. this.z -= v.z;
  550. return this;
  551. },
  552. multiply: function ( a, b ) {
  553. this.x = a.x * b.x;
  554. this.y = a.y * b.y;
  555. this.z = a.z * b.z;
  556. return this;
  557. },
  558. multiplySelf: function ( v ) {
  559. this.x *= v.x;
  560. this.y *= v.y;
  561. this.z *= v.z;
  562. return this;
  563. },
  564. multiplyScalar: function ( s ) {
  565. this.x *= s;
  566. this.y *= s;
  567. this.z *= s;
  568. return this;
  569. },
  570. divideSelf: function ( v ) {
  571. this.x /= v.x;
  572. this.y /= v.y;
  573. this.z /= v.z;
  574. return this;
  575. },
  576. divideScalar: function ( s ) {
  577. if ( s ) {
  578. this.x /= s;
  579. this.y /= s;
  580. this.z /= s;
  581. } else {
  582. this.x = 0;
  583. this.y = 0;
  584. this.z = 0;
  585. }
  586. return this;
  587. },
  588. negate: function() {
  589. return this.multiplyScalar( - 1 );
  590. },
  591. dot: function ( v ) {
  592. return this.x * v.x + this.y * v.y + this.z * v.z;
  593. },
  594. lengthSq: function () {
  595. return this.x * this.x + this.y * this.y + this.z * this.z;
  596. },
  597. length: function () {
  598. return Math.sqrt( this.lengthSq() );
  599. },
  600. lengthManhattan: function () {
  601. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  602. },
  603. normalize: function () {
  604. return this.divideScalar( this.length() );
  605. },
  606. setLength: function ( l ) {
  607. return this.normalize().multiplyScalar( l );
  608. },
  609. lerpSelf: function ( v, alpha ) {
  610. this.x += ( v.x - this.x ) * alpha;
  611. this.y += ( v.y - this.y ) * alpha;
  612. this.z += ( v.z - this.z ) * alpha;
  613. return this;
  614. },
  615. cross: function ( a, b ) {
  616. this.x = a.y * b.z - a.z * b.y;
  617. this.y = a.z * b.x - a.x * b.z;
  618. this.z = a.x * b.y - a.y * b.x;
  619. return this;
  620. },
  621. crossSelf: function ( v ) {
  622. var x = this.x, y = this.y, z = this.z;
  623. this.x = y * v.z - z * v.y;
  624. this.y = z * v.x - x * v.z;
  625. this.z = x * v.y - y * v.x;
  626. return this;
  627. },
  628. angleTo: function ( v ) {
  629. return Math.acos( this.dot( v ) / this.length() / v.length() );
  630. },
  631. distanceTo: function ( v ) {
  632. return Math.sqrt( this.distanceToSquared( v ) );
  633. },
  634. distanceToSquared: function ( v ) {
  635. return new THREE.Vector3().sub( this, v ).lengthSq();
  636. },
  637. getPositionFromMatrix: function ( m ) {
  638. this.x = m.elements[12];
  639. this.y = m.elements[13];
  640. this.z = m.elements[14];
  641. return this;
  642. },
  643. setEulerFromRotationMatrix: function ( m, order ) {
  644. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  645. // clamp, to handle numerical problems
  646. function clamp( x ) {
  647. return Math.min( Math.max( x, -1 ), 1 );
  648. }
  649. var te = m.elements;
  650. var m11 = te[0], m12 = te[4], m13 = te[8];
  651. var m21 = te[1], m22 = te[5], m23 = te[9];
  652. var m31 = te[2], m32 = te[6], m33 = te[10];
  653. if ( order === undefined || order === 'XYZ' ) {
  654. this.y = Math.asin( clamp( m13 ) );
  655. if ( Math.abs( m13 ) < 0.99999 ) {
  656. this.x = Math.atan2( - m23, m33 );
  657. this.z = Math.atan2( - m12, m11 );
  658. } else {
  659. this.x = Math.atan2( m32, m22 );
  660. this.z = 0;
  661. }
  662. } else if ( order === 'YXZ' ) {
  663. this.x = Math.asin( - clamp( m23 ) );
  664. if ( Math.abs( m23 ) < 0.99999 ) {
  665. this.y = Math.atan2( m13, m33 );
  666. this.z = Math.atan2( m21, m22 );
  667. } else {
  668. this.y = Math.atan2( - m31, m11 );
  669. this.z = 0;
  670. }
  671. } else if ( order === 'ZXY' ) {
  672. this.x = Math.asin( clamp( m32 ) );
  673. if ( Math.abs( m32 ) < 0.99999 ) {
  674. this.y = Math.atan2( - m31, m33 );
  675. this.z = Math.atan2( - m12, m22 );
  676. } else {
  677. this.y = 0;
  678. this.z = Math.atan2( m21, m11 );
  679. }
  680. } else if ( order === 'ZYX' ) {
  681. this.y = Math.asin( - clamp( m31 ) );
  682. if ( Math.abs( m31 ) < 0.99999 ) {
  683. this.x = Math.atan2( m32, m33 );
  684. this.z = Math.atan2( m21, m11 );
  685. } else {
  686. this.x = 0;
  687. this.z = Math.atan2( - m12, m22 );
  688. }
  689. } else if ( order === 'YZX' ) {
  690. this.z = Math.asin( clamp( m21 ) );
  691. if ( Math.abs( m21 ) < 0.99999 ) {
  692. this.x = Math.atan2( - m23, m22 );
  693. this.y = Math.atan2( - m31, m11 );
  694. } else {
  695. this.x = 0;
  696. this.y = Math.atan2( m13, m33 );
  697. }
  698. } else if ( order === 'XZY' ) {
  699. this.z = Math.asin( - clamp( m12 ) );
  700. if ( Math.abs( m12 ) < 0.99999 ) {
  701. this.x = Math.atan2( m32, m22 );
  702. this.y = Math.atan2( m13, m11 );
  703. } else {
  704. this.x = Math.atan2( - m23, m33 );
  705. this.y = 0;
  706. }
  707. }
  708. return this;
  709. },
  710. setEulerFromQuaternion: function ( q, order ) {
  711. // q is assumed to be normalized
  712. // clamp, to handle numerical problems
  713. function clamp( x ) {
  714. return Math.min( Math.max( x, -1 ), 1 );
  715. }
  716. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  717. var sqx = q.x * q.x;
  718. var sqy = q.y * q.y;
  719. var sqz = q.z * q.z;
  720. var sqw = q.w * q.w;
  721. if ( order === undefined || order === 'XYZ' ) {
  722. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  723. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  724. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  725. } else if ( order === 'YXZ' ) {
  726. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  727. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  728. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  729. } else if ( order === 'ZXY' ) {
  730. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  731. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  732. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  733. } else if ( order === 'ZYX' ) {
  734. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  735. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  736. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  737. } else if ( order === 'YZX' ) {
  738. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  739. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  740. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  741. } else if ( order === 'XZY' ) {
  742. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  743. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  744. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  745. }
  746. return this;
  747. },
  748. getScaleFromMatrix: function ( m ) {
  749. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  750. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  751. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  752. this.x = sx;
  753. this.y = sy;
  754. this.z = sz;
  755. return this;
  756. },
  757. equals: function ( v ) {
  758. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  759. },
  760. clone: function () {
  761. return new THREE.Vector3( this.x, this.y, this.z );
  762. }
  763. };
  764. /**
  765. * @author supereggbert / http://www.paulbrunt.co.uk/
  766. * @author philogb / http://blog.thejit.org/
  767. * @author mikael emtinger / http://gomo.se/
  768. * @author egraether / http://egraether.com/
  769. * @author WestLangley / http://github.com/WestLangley
  770. */
  771. THREE.Vector4 = function ( x, y, z, w ) {
  772. this.x = x || 0;
  773. this.y = y || 0;
  774. this.z = z || 0;
  775. this.w = ( w !== undefined ) ? w : 1;
  776. };
  777. THREE.Vector4.prototype = {
  778. constructor: THREE.Vector4,
  779. set: function ( x, y, z, w ) {
  780. this.x = x;
  781. this.y = y;
  782. this.z = z;
  783. this.w = w;
  784. return this;
  785. },
  786. copy: function ( v ) {
  787. this.x = v.x;
  788. this.y = v.y;
  789. this.z = v.z;
  790. this.w = ( v.w !== undefined ) ? v.w : 1;
  791. return this;
  792. },
  793. add: function ( a, b ) {
  794. this.x = a.x + b.x;
  795. this.y = a.y + b.y;
  796. this.z = a.z + b.z;
  797. this.w = a.w + b.w;
  798. return this;
  799. },
  800. addSelf: function ( v ) {
  801. this.x += v.x;
  802. this.y += v.y;
  803. this.z += v.z;
  804. this.w += v.w;
  805. return this;
  806. },
  807. sub: function ( a, b ) {
  808. this.x = a.x - b.x;
  809. this.y = a.y - b.y;
  810. this.z = a.z - b.z;
  811. this.w = a.w - b.w;
  812. return this;
  813. },
  814. subSelf: function ( v ) {
  815. this.x -= v.x;
  816. this.y -= v.y;
  817. this.z -= v.z;
  818. this.w -= v.w;
  819. return this;
  820. },
  821. multiplyScalar: function ( s ) {
  822. this.x *= s;
  823. this.y *= s;
  824. this.z *= s;
  825. this.w *= s;
  826. return this;
  827. },
  828. divideScalar: function ( s ) {
  829. if ( s ) {
  830. this.x /= s;
  831. this.y /= s;
  832. this.z /= s;
  833. this.w /= s;
  834. } else {
  835. this.x = 0;
  836. this.y = 0;
  837. this.z = 0;
  838. this.w = 1;
  839. }
  840. return this;
  841. },
  842. negate: function() {
  843. return this.multiplyScalar( -1 );
  844. },
  845. dot: function ( v ) {
  846. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  847. },
  848. lengthSq: function () {
  849. return this.dot( this );
  850. },
  851. length: function () {
  852. return Math.sqrt( this.lengthSq() );
  853. },
  854. lengthManhattan: function () {
  855. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  856. },
  857. normalize: function () {
  858. return this.divideScalar( this.length() );
  859. },
  860. setLength: function ( l ) {
  861. return this.normalize().multiplyScalar( l );
  862. },
  863. lerpSelf: function ( v, alpha ) {
  864. this.x += ( v.x - this.x ) * alpha;
  865. this.y += ( v.y - this.y ) * alpha;
  866. this.z += ( v.z - this.z ) * alpha;
  867. this.w += ( v.w - this.w ) * alpha;
  868. return this;
  869. },
  870. clone: function () {
  871. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  872. },
  873. setAxisAngleFromQuaternion: function ( q ) {
  874. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  875. // q is assumed to be normalized
  876. this.w = 2 * Math.acos( q.w );
  877. var s = Math.sqrt( 1 - q.w * q.w );
  878. if ( s < 0.0001 ) {
  879. this.x = 1;
  880. this.y = 0;
  881. this.z = 0;
  882. } else {
  883. this.x = q.x / s;
  884. this.y = q.y / s;
  885. this.z = q.z / s;
  886. }
  887. return this;
  888. },
  889. setAxisAngleFromRotationMatrix: function ( m ) {
  890. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  891. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  892. var angle, x, y, z, // variables for result
  893. epsilon = 0.01, // margin to allow for rounding errors
  894. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  895. te = m.elements,
  896. m11 = te[0], m12 = te[4], m13 = te[8],
  897. m21 = te[1], m22 = te[5], m23 = te[9],
  898. m31 = te[2], m32 = te[6], m33 = te[10];
  899. if ( ( Math.abs( m12 - m21 ) < epsilon )
  900. && ( Math.abs( m13 - m31 ) < epsilon )
  901. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  902. // singularity found
  903. // first check for identity matrix which must have +1 for all terms
  904. // in leading diagonal and zero in other terms
  905. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  906. && ( Math.abs( m13 + m31 ) < epsilon2 )
  907. && ( Math.abs( m23 + m32 ) < epsilon2 )
  908. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  909. // this singularity is identity matrix so angle = 0
  910. this.set( 1, 0, 0, 0 );
  911. return this; // zero angle, arbitrary axis
  912. }
  913. // otherwise this singularity is angle = 180
  914. angle = Math.PI;
  915. var xx = ( m11 + 1 ) / 2;
  916. var yy = ( m22 + 1 ) / 2;
  917. var zz = ( m33 + 1 ) / 2;
  918. var xy = ( m12 + m21 ) / 4;
  919. var xz = ( m13 + m31 ) / 4;
  920. var yz = ( m23 + m32 ) / 4;
  921. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  922. if ( xx < epsilon ) {
  923. x = 0;
  924. y = 0.707106781;
  925. z = 0.707106781;
  926. } else {
  927. x = Math.sqrt( xx );
  928. y = xy / x;
  929. z = xz / x;
  930. }
  931. } else if ( yy > zz ) { // m22 is the largest diagonal term
  932. if ( yy < epsilon ) {
  933. x = 0.707106781;
  934. y = 0;
  935. z = 0.707106781;
  936. } else {
  937. y = Math.sqrt( yy );
  938. x = xy / y;
  939. z = yz / y;
  940. }
  941. } else { // m33 is the largest diagonal term so base result on this
  942. if ( zz < epsilon ) {
  943. x = 0.707106781;
  944. y = 0.707106781;
  945. z = 0;
  946. } else {
  947. z = Math.sqrt( zz );
  948. x = xz / z;
  949. y = yz / z;
  950. }
  951. }
  952. this.set( x, y, z, angle );
  953. return this; // return 180 deg rotation
  954. }
  955. // as we have reached here there are no singularities so we can handle normally
  956. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  957. + ( m13 - m31 ) * ( m13 - m31 )
  958. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  959. if ( Math.abs( s ) < 0.001 ) s = 1;
  960. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  961. // caught by singularity test above, but I've left it in just in case
  962. this.x = ( m32 - m23 ) / s;
  963. this.y = ( m13 - m31 ) / s;
  964. this.z = ( m21 - m12 ) / s;
  965. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  966. return this;
  967. }
  968. };
  969. /**
  970. * @author alteredq / http://alteredqualia.com/
  971. * @author WestLangley / http://github.com/WestLangley
  972. */
  973. THREE.Matrix3 = function () {
  974. this.elements = new Float32Array(9);
  975. };
  976. THREE.Matrix3.prototype = {
  977. constructor: THREE.Matrix3,
  978. multiplyVector3: function ( v ) {
  979. var te = this.elements;
  980. var vx = v.x, vy = v.y, vz = v.z;
  981. v.x = te[0] * vx + te[3] * vy + te[6] * vz;
  982. v.y = te[1] * vx + te[4] * vy + te[7] * vz;
  983. v.z = te[2] * vx + te[5] * vy + te[8] * vz;
  984. return v;
  985. },
  986. multiplyVector3Array: function ( a ) {
  987. var tmp = THREE.Matrix3.__v1;
  988. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  989. tmp.x = a[ i ];
  990. tmp.y = a[ i + 1 ];
  991. tmp.z = a[ i + 2 ];
  992. this.multiplyVector3( tmp );
  993. a[ i ] = tmp.x;
  994. a[ i + 1 ] = tmp.y;
  995. a[ i + 2 ] = tmp.z;
  996. }
  997. return a;
  998. },
  999. getInverse: function ( matrix ) {
  1000. // input: THREE.Matrix4
  1001. // ( based on http://code.google.com/p/webgl-mjs/ )
  1002. var me = matrix.elements;
  1003. var a11 = me[10] * me[5] - me[6] * me[9];
  1004. var a21 = - me[10] * me[1] + me[2] * me[9];
  1005. var a31 = me[6] * me[1] - me[2] * me[5];
  1006. var a12 = - me[10] * me[4] + me[6] * me[8];
  1007. var a22 = me[10] * me[0] - me[2] * me[8];
  1008. var a32 = - me[6] * me[0] + me[2] * me[4];
  1009. var a13 = me[9] * me[4] - me[5] * me[8];
  1010. var a23 = - me[9] * me[0] + me[1] * me[8];
  1011. var a33 = me[5] * me[0] - me[1] * me[4];
  1012. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  1013. // no inverse
  1014. if ( det === 0 ) {
  1015. console.warn( "Matrix3.getInverse(): determinant == 0" );
  1016. }
  1017. var idet = 1.0 / det;
  1018. var m = this.elements;
  1019. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  1020. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  1021. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  1022. return this;
  1023. },
  1024. transpose: function () {
  1025. var tmp, m = this.elements;
  1026. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  1027. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  1028. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  1029. return this;
  1030. },
  1031. transposeIntoArray: function ( r ) {
  1032. var m = this.elements;
  1033. r[ 0 ] = m[ 0 ];
  1034. r[ 1 ] = m[ 3 ];
  1035. r[ 2 ] = m[ 6 ];
  1036. r[ 3 ] = m[ 1 ];
  1037. r[ 4 ] = m[ 4 ];
  1038. r[ 5 ] = m[ 7 ];
  1039. r[ 6 ] = m[ 2 ];
  1040. r[ 7 ] = m[ 5 ];
  1041. r[ 8 ] = m[ 8 ];
  1042. return this;
  1043. }
  1044. };
  1045. THREE.Matrix3.__v1 = new THREE.Vector3();/**
  1046. * @author mrdoob / http://mrdoob.com/
  1047. * @author supereggbert / http://www.paulbrunt.co.uk/
  1048. * @author philogb / http://blog.thejit.org/
  1049. * @author jordi_ros / http://plattsoft.com
  1050. * @author D1plo1d / http://github.com/D1plo1d
  1051. * @author alteredq / http://alteredqualia.com/
  1052. * @author mikael emtinger / http://gomo.se/
  1053. * @author timknip / http://www.floorplanner.com/
  1054. */
  1055. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1056. this.elements = new Float32Array( 16 );
  1057. this.set(
  1058. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  1059. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  1060. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  1061. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  1062. );
  1063. };
  1064. THREE.Matrix4.prototype = {
  1065. constructor: THREE.Matrix4,
  1066. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1067. var te = this.elements;
  1068. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  1069. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1070. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1071. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1072. return this;
  1073. },
  1074. identity: function () {
  1075. this.set(
  1076. 1, 0, 0, 0,
  1077. 0, 1, 0, 0,
  1078. 0, 0, 1, 0,
  1079. 0, 0, 0, 1
  1080. );
  1081. return this;
  1082. },
  1083. copy: function ( m ) {
  1084. var me = m.elements;
  1085. this.set(
  1086. me[0], me[4], me[8], me[12],
  1087. me[1], me[5], me[9], me[13],
  1088. me[2], me[6], me[10], me[14],
  1089. me[3], me[7], me[11], me[15]
  1090. );
  1091. return this;
  1092. },
  1093. lookAt: function ( eye, target, up ) {
  1094. var te = this.elements;
  1095. var x = THREE.Matrix4.__v1;
  1096. var y = THREE.Matrix4.__v2;
  1097. var z = THREE.Matrix4.__v3;
  1098. z.sub( eye, target ).normalize();
  1099. if ( z.length() === 0 ) {
  1100. z.z = 1;
  1101. }
  1102. x.cross( up, z ).normalize();
  1103. if ( x.length() === 0 ) {
  1104. z.x += 0.0001;
  1105. x.cross( up, z ).normalize();
  1106. }
  1107. y.cross( z, x );
  1108. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1109. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1110. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1111. return this;
  1112. },
  1113. multiply: function ( a, b ) {
  1114. var ae = a.elements;
  1115. var be = b.elements;
  1116. var te = this.elements;
  1117. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1118. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1119. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1120. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1121. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1122. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1123. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1124. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1125. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1126. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1127. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1128. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1129. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1130. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1131. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1132. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1133. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1134. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1135. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1136. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1137. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1138. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1139. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1140. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1141. return this;
  1142. },
  1143. multiplySelf: function ( m ) {
  1144. return this.multiply( this, m );
  1145. },
  1146. multiplyToArray: function ( a, b, r ) {
  1147. var te = this.elements;
  1148. this.multiply( a, b );
  1149. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1150. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1151. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1152. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1153. return this;
  1154. },
  1155. multiplyScalar: function ( s ) {
  1156. var te = this.elements;
  1157. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1158. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1159. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1160. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1161. return this;
  1162. },
  1163. multiplyVector3: function ( v ) {
  1164. var te = this.elements;
  1165. var vx = v.x, vy = v.y, vz = v.z;
  1166. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1167. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1168. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1169. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1170. return v;
  1171. },
  1172. multiplyVector4: function ( v ) {
  1173. var te = this.elements;
  1174. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1175. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1176. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1177. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1178. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1179. return v;
  1180. },
  1181. multiplyVector3Array: function ( a ) {
  1182. var tmp = THREE.Matrix4.__v1;
  1183. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1184. tmp.x = a[ i ];
  1185. tmp.y = a[ i + 1 ];
  1186. tmp.z = a[ i + 2 ];
  1187. this.multiplyVector3( tmp );
  1188. a[ i ] = tmp.x;
  1189. a[ i + 1 ] = tmp.y;
  1190. a[ i + 2 ] = tmp.z;
  1191. }
  1192. return a;
  1193. },
  1194. rotateAxis: function ( v ) {
  1195. var te = this.elements;
  1196. var vx = v.x, vy = v.y, vz = v.z;
  1197. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1198. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1199. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1200. v.normalize();
  1201. return v;
  1202. },
  1203. crossVector: function ( a ) {
  1204. var te = this.elements;
  1205. var v = new THREE.Vector4();
  1206. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1207. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1208. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1209. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1210. return v;
  1211. },
  1212. determinant: function () {
  1213. var te = this.elements;
  1214. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1215. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1216. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1217. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1218. //TODO: make this more efficient
  1219. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1220. return (
  1221. n14 * n23 * n32 * n41-
  1222. n13 * n24 * n32 * n41-
  1223. n14 * n22 * n33 * n41+
  1224. n12 * n24 * n33 * n41+
  1225. n13 * n22 * n34 * n41-
  1226. n12 * n23 * n34 * n41-
  1227. n14 * n23 * n31 * n42+
  1228. n13 * n24 * n31 * n42+
  1229. n14 * n21 * n33 * n42-
  1230. n11 * n24 * n33 * n42-
  1231. n13 * n21 * n34 * n42+
  1232. n11 * n23 * n34 * n42+
  1233. n14 * n22 * n31 * n43-
  1234. n12 * n24 * n31 * n43-
  1235. n14 * n21 * n32 * n43+
  1236. n11 * n24 * n32 * n43+
  1237. n12 * n21 * n34 * n43-
  1238. n11 * n22 * n34 * n43-
  1239. n13 * n22 * n31 * n44+
  1240. n12 * n23 * n31 * n44+
  1241. n13 * n21 * n32 * n44-
  1242. n11 * n23 * n32 * n44-
  1243. n12 * n21 * n33 * n44+
  1244. n11 * n22 * n33 * n44
  1245. );
  1246. },
  1247. transpose: function () {
  1248. var te = this.elements;
  1249. var tmp;
  1250. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1251. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1252. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1253. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1254. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1255. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1256. return this;
  1257. },
  1258. flattenToArray: function ( flat ) {
  1259. var te = this.elements;
  1260. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1261. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1262. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1263. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1264. return flat;
  1265. },
  1266. flattenToArrayOffset: function( flat, offset ) {
  1267. var te = this.elements;
  1268. flat[ offset ] = te[0];
  1269. flat[ offset + 1 ] = te[1];
  1270. flat[ offset + 2 ] = te[2];
  1271. flat[ offset + 3 ] = te[3];
  1272. flat[ offset + 4 ] = te[4];
  1273. flat[ offset + 5 ] = te[5];
  1274. flat[ offset + 6 ] = te[6];
  1275. flat[ offset + 7 ] = te[7];
  1276. flat[ offset + 8 ] = te[8];
  1277. flat[ offset + 9 ] = te[9];
  1278. flat[ offset + 10 ] = te[10];
  1279. flat[ offset + 11 ] = te[11];
  1280. flat[ offset + 12 ] = te[12];
  1281. flat[ offset + 13 ] = te[13];
  1282. flat[ offset + 14 ] = te[14];
  1283. flat[ offset + 15 ] = te[15];
  1284. return flat;
  1285. },
  1286. getPosition: function () {
  1287. var te = this.elements;
  1288. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1289. },
  1290. setPosition: function ( v ) {
  1291. var te = this.elements;
  1292. te[12] = v.x;
  1293. te[13] = v.y;
  1294. te[14] = v.z;
  1295. return this;
  1296. },
  1297. getColumnX: function () {
  1298. var te = this.elements;
  1299. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1300. },
  1301. getColumnY: function () {
  1302. var te = this.elements;
  1303. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1304. },
  1305. getColumnZ: function() {
  1306. var te = this.elements;
  1307. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1308. },
  1309. getInverse: function ( m ) {
  1310. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1311. var te = this.elements;
  1312. var me = m.elements;
  1313. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1314. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1315. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1316. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1317. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1318. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1319. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1320. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1321. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1322. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1323. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1324. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1325. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1326. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1327. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1328. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1329. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1330. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1331. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1332. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1333. this.multiplyScalar( 1 / m.determinant() );
  1334. return this;
  1335. },
  1336. setRotationFromEuler: function ( v, order ) {
  1337. var te = this.elements;
  1338. var x = v.x, y = v.y, z = v.z;
  1339. var a = Math.cos( x ), b = Math.sin( x );
  1340. var c = Math.cos( y ), d = Math.sin( y );
  1341. var e = Math.cos( z ), f = Math.sin( z );
  1342. if ( order === undefined || order === 'XYZ' ) {
  1343. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1344. te[0] = c * e;
  1345. te[4] = - c * f;
  1346. te[8] = d;
  1347. te[1] = af + be * d;
  1348. te[5] = ae - bf * d;
  1349. te[9] = - b * c;
  1350. te[2] = bf - ae * d;
  1351. te[6] = be + af * d;
  1352. te[10] = a * c;
  1353. } else if ( order === 'YXZ' ) {
  1354. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1355. te[0] = ce + df * b;
  1356. te[4] = de * b - cf;
  1357. te[8] = a * d;
  1358. te[1] = a * f;
  1359. te[5] = a * e;
  1360. te[9] = - b;
  1361. te[2] = cf * b - de;
  1362. te[6] = df + ce * b;
  1363. te[10] = a * c;
  1364. } else if ( order === 'ZXY' ) {
  1365. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1366. te[0] = ce - df * b;
  1367. te[4] = - a * f;
  1368. te[8] = de + cf * b;
  1369. te[1] = cf + de * b;
  1370. te[5] = a * e;
  1371. te[9] = df - ce * b;
  1372. te[2] = - a * d;
  1373. te[6] = b;
  1374. te[10] = a * c;
  1375. } else if ( order === 'ZYX' ) {
  1376. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1377. te[0] = c * e;
  1378. te[4] = be * d - af;
  1379. te[8] = ae * d + bf;
  1380. te[1] = c * f;
  1381. te[5] = bf * d + ae;
  1382. te[9] = af * d - be;
  1383. te[2] = - d;
  1384. te[6] = b * c;
  1385. te[10] = a * c;
  1386. } else if ( order === 'YZX' ) {
  1387. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1388. te[0] = c * e;
  1389. te[4] = bd - ac * f;
  1390. te[8] = bc * f + ad;
  1391. te[1] = f;
  1392. te[5] = a * e;
  1393. te[9] = - b * e;
  1394. te[2] = - d * e;
  1395. te[6] = ad * f + bc;
  1396. te[10] = ac - bd * f;
  1397. } else if ( order === 'XZY' ) {
  1398. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1399. te[0] = c * e;
  1400. te[4] = - f;
  1401. te[8] = d * e;
  1402. te[1] = ac * f + bd;
  1403. te[5] = a * e;
  1404. te[9] = ad * f - bc;
  1405. te[2] = bc * f - ad;
  1406. te[6] = b * e;
  1407. te[10] = bd * f + ac;
  1408. }
  1409. return this;
  1410. },
  1411. setRotationFromQuaternion: function ( q ) {
  1412. var te = this.elements;
  1413. var x = q.x, y = q.y, z = q.z, w = q.w;
  1414. var x2 = x + x, y2 = y + y, z2 = z + z;
  1415. var xx = x * x2, xy = x * y2, xz = x * z2;
  1416. var yy = y * y2, yz = y * z2, zz = z * z2;
  1417. var wx = w * x2, wy = w * y2, wz = w * z2;
  1418. te[0] = 1 - ( yy + zz );
  1419. te[4] = xy - wz;
  1420. te[8] = xz + wy;
  1421. te[1] = xy + wz;
  1422. te[5] = 1 - ( xx + zz );
  1423. te[9] = yz - wx;
  1424. te[2] = xz - wy;
  1425. te[6] = yz + wx;
  1426. te[10] = 1 - ( xx + yy );
  1427. return this;
  1428. },
  1429. compose: function ( translation, rotation, scale ) {
  1430. var te = this.elements;
  1431. var mRotation = THREE.Matrix4.__m1;
  1432. var mScale = THREE.Matrix4.__m2;
  1433. mRotation.identity();
  1434. mRotation.setRotationFromQuaternion( rotation );
  1435. mScale.makeScale( scale.x, scale.y, scale.z );
  1436. this.multiply( mRotation, mScale );
  1437. te[12] = translation.x;
  1438. te[13] = translation.y;
  1439. te[14] = translation.z;
  1440. return this;
  1441. },
  1442. decompose: function ( translation, rotation, scale ) {
  1443. var te = this.elements;
  1444. // grab the axis vectors
  1445. var x = THREE.Matrix4.__v1;
  1446. var y = THREE.Matrix4.__v2;
  1447. var z = THREE.Matrix4.__v3;
  1448. x.set( te[0], te[1], te[2] );
  1449. y.set( te[4], te[5], te[6] );
  1450. z.set( te[8], te[9], te[10] );
  1451. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1452. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1453. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1454. scale.x = x.length();
  1455. scale.y = y.length();
  1456. scale.z = z.length();
  1457. translation.x = te[12];
  1458. translation.y = te[13];
  1459. translation.z = te[14];
  1460. // scale the rotation part
  1461. var matrix = THREE.Matrix4.__m1;
  1462. matrix.copy( this );
  1463. matrix.elements[0] /= scale.x;
  1464. matrix.elements[1] /= scale.x;
  1465. matrix.elements[2] /= scale.x;
  1466. matrix.elements[4] /= scale.y;
  1467. matrix.elements[5] /= scale.y;
  1468. matrix.elements[6] /= scale.y;
  1469. matrix.elements[8] /= scale.z;
  1470. matrix.elements[9] /= scale.z;
  1471. matrix.elements[10] /= scale.z;
  1472. rotation.setFromRotationMatrix( matrix );
  1473. return [ translation, rotation, scale ];
  1474. },
  1475. extractPosition: function ( m ) {
  1476. var te = this.elements;
  1477. var me = m.elements;
  1478. te[12] = me[12];
  1479. te[13] = me[13];
  1480. te[14] = me[14];
  1481. return this;
  1482. },
  1483. extractRotation: function ( m ) {
  1484. var te = this.elements;
  1485. var me = m.elements;
  1486. var vector = THREE.Matrix4.__v1;
  1487. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1488. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1489. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1490. te[0] = me[0] * scaleX;
  1491. te[1] = me[1] * scaleX;
  1492. te[2] = me[2] * scaleX;
  1493. te[4] = me[4] * scaleY;
  1494. te[5] = me[5] * scaleY;
  1495. te[6] = me[6] * scaleY;
  1496. te[8] = me[8] * scaleZ;
  1497. te[9] = me[9] * scaleZ;
  1498. te[10] = me[10] * scaleZ;
  1499. return this;
  1500. },
  1501. //
  1502. translate: function ( v ) {
  1503. var te = this.elements;
  1504. var x = v.x, y = v.y, z = v.z;
  1505. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1506. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1507. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1508. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1509. return this;
  1510. },
  1511. rotateX: function ( angle ) {
  1512. var te = this.elements;
  1513. var m12 = te[4];
  1514. var m22 = te[5];
  1515. var m32 = te[6];
  1516. var m42 = te[7];
  1517. var m13 = te[8];
  1518. var m23 = te[9];
  1519. var m33 = te[10];
  1520. var m43 = te[11];
  1521. var c = Math.cos( angle );
  1522. var s = Math.sin( angle );
  1523. te[4] = c * m12 + s * m13;
  1524. te[5] = c * m22 + s * m23;
  1525. te[6] = c * m32 + s * m33;
  1526. te[7] = c * m42 + s * m43;
  1527. te[8] = c * m13 - s * m12;
  1528. te[9] = c * m23 - s * m22;
  1529. te[10] = c * m33 - s * m32;
  1530. te[11] = c * m43 - s * m42;
  1531. return this;
  1532. },
  1533. rotateY: function ( angle ) {
  1534. var te = this.elements;
  1535. var m11 = te[0];
  1536. var m21 = te[1];
  1537. var m31 = te[2];
  1538. var m41 = te[3];
  1539. var m13 = te[8];
  1540. var m23 = te[9];
  1541. var m33 = te[10];
  1542. var m43 = te[11];
  1543. var c = Math.cos( angle );
  1544. var s = Math.sin( angle );
  1545. te[0] = c * m11 - s * m13;
  1546. te[1] = c * m21 - s * m23;
  1547. te[2] = c * m31 - s * m33;
  1548. te[3] = c * m41 - s * m43;
  1549. te[8] = c * m13 + s * m11;
  1550. te[9] = c * m23 + s * m21;
  1551. te[10] = c * m33 + s * m31;
  1552. te[11] = c * m43 + s * m41;
  1553. return this;
  1554. },
  1555. rotateZ: function ( angle ) {
  1556. var te = this.elements;
  1557. var m11 = te[0];
  1558. var m21 = te[1];
  1559. var m31 = te[2];
  1560. var m41 = te[3];
  1561. var m12 = te[4];
  1562. var m22 = te[5];
  1563. var m32 = te[6];
  1564. var m42 = te[7];
  1565. var c = Math.cos( angle );
  1566. var s = Math.sin( angle );
  1567. te[0] = c * m11 + s * m12;
  1568. te[1] = c * m21 + s * m22;
  1569. te[2] = c * m31 + s * m32;
  1570. te[3] = c * m41 + s * m42;
  1571. te[4] = c * m12 - s * m11;
  1572. te[5] = c * m22 - s * m21;
  1573. te[6] = c * m32 - s * m31;
  1574. te[7] = c * m42 - s * m41;
  1575. return this;
  1576. },
  1577. rotateByAxis: function ( axis, angle ) {
  1578. var te = this.elements;
  1579. // optimize by checking axis
  1580. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1581. return this.rotateX( angle );
  1582. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1583. return this.rotateY( angle );
  1584. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1585. return this.rotateZ( angle );
  1586. }
  1587. var x = axis.x, y = axis.y, z = axis.z;
  1588. var n = Math.sqrt(x * x + y * y + z * z);
  1589. x /= n;
  1590. y /= n;
  1591. z /= n;
  1592. var xx = x * x, yy = y * y, zz = z * z;
  1593. var c = Math.cos( angle );
  1594. var s = Math.sin( angle );
  1595. var oneMinusCosine = 1 - c;
  1596. var xy = x * y * oneMinusCosine;
  1597. var xz = x * z * oneMinusCosine;
  1598. var yz = y * z * oneMinusCosine;
  1599. var xs = x * s;
  1600. var ys = y * s;
  1601. var zs = z * s;
  1602. var r11 = xx + (1 - xx) * c;
  1603. var r21 = xy + zs;
  1604. var r31 = xz - ys;
  1605. var r12 = xy - zs;
  1606. var r22 = yy + (1 - yy) * c;
  1607. var r32 = yz + xs;
  1608. var r13 = xz + ys;
  1609. var r23 = yz - xs;
  1610. var r33 = zz + (1 - zz) * c;
  1611. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1612. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1613. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1614. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1615. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1616. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1617. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1618. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1619. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1620. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1621. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1622. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1623. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1624. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1625. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1626. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1627. return this;
  1628. },
  1629. scale: function ( v ) {
  1630. var te = this.elements;
  1631. var x = v.x, y = v.y, z = v.z;
  1632. te[0] *= x; te[4] *= y; te[8] *= z;
  1633. te[1] *= x; te[5] *= y; te[9] *= z;
  1634. te[2] *= x; te[6] *= y; te[10] *= z;
  1635. te[3] *= x; te[7] *= y; te[11] *= z;
  1636. return this;
  1637. },
  1638. getMaxScaleOnAxis: function () {
  1639. var te = this.elements;
  1640. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  1641. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  1642. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  1643. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  1644. },
  1645. //
  1646. makeTranslation: function ( x, y, z ) {
  1647. this.set(
  1648. 1, 0, 0, x,
  1649. 0, 1, 0, y,
  1650. 0, 0, 1, z,
  1651. 0, 0, 0, 1
  1652. );
  1653. return this;
  1654. },
  1655. makeRotationX: function ( theta ) {
  1656. var c = Math.cos( theta ), s = Math.sin( theta );
  1657. this.set(
  1658. 1, 0, 0, 0,
  1659. 0, c, -s, 0,
  1660. 0, s, c, 0,
  1661. 0, 0, 0, 1
  1662. );
  1663. return this;
  1664. },
  1665. makeRotationY: function ( theta ) {
  1666. var c = Math.cos( theta ), s = Math.sin( theta );
  1667. this.set(
  1668. c, 0, s, 0,
  1669. 0, 1, 0, 0,
  1670. -s, 0, c, 0,
  1671. 0, 0, 0, 1
  1672. );
  1673. return this;
  1674. },
  1675. makeRotationZ: function ( theta ) {
  1676. var c = Math.cos( theta ), s = Math.sin( theta );
  1677. this.set(
  1678. c, -s, 0, 0,
  1679. s, c, 0, 0,
  1680. 0, 0, 1, 0,
  1681. 0, 0, 0, 1
  1682. );
  1683. return this;
  1684. },
  1685. makeRotationAxis: function ( axis, angle ) {
  1686. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1687. var c = Math.cos( angle );
  1688. var s = Math.sin( angle );
  1689. var t = 1 - c;
  1690. var x = axis.x, y = axis.y, z = axis.z;
  1691. var tx = t * x, ty = t * y;
  1692. this.set(
  1693. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1694. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1695. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1696. 0, 0, 0, 1
  1697. );
  1698. return this;
  1699. },
  1700. makeScale: function ( x, y, z ) {
  1701. this.set(
  1702. x, 0, 0, 0,
  1703. 0, y, 0, 0,
  1704. 0, 0, z, 0,
  1705. 0, 0, 0, 1
  1706. );
  1707. return this;
  1708. },
  1709. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1710. var te = this.elements;
  1711. var x = 2 * near / ( right - left );
  1712. var y = 2 * near / ( top - bottom );
  1713. var a = ( right + left ) / ( right - left );
  1714. var b = ( top + bottom ) / ( top - bottom );
  1715. var c = - ( far + near ) / ( far - near );
  1716. var d = - 2 * far * near / ( far - near );
  1717. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1718. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1719. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1720. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1721. return this;
  1722. },
  1723. makePerspective: function ( fov, aspect, near, far ) {
  1724. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1725. var ymin = - ymax;
  1726. var xmin = ymin * aspect;
  1727. var xmax = ymax * aspect;
  1728. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1729. },
  1730. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1731. var te = this.elements;
  1732. var w = right - left;
  1733. var h = top - bottom;
  1734. var p = far - near;
  1735. var x = ( right + left ) / w;
  1736. var y = ( top + bottom ) / h;
  1737. var z = ( far + near ) / p;
  1738. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1739. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1740. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1741. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  1742. return this;
  1743. },
  1744. clone: function () {
  1745. var te = this.elements;
  1746. return new THREE.Matrix4(
  1747. te[0], te[4], te[8], te[12],
  1748. te[1], te[5], te[9], te[13],
  1749. te[2], te[6], te[10], te[14],
  1750. te[3], te[7], te[11], te[15]
  1751. );
  1752. }
  1753. };
  1754. THREE.Matrix4.__v1 = new THREE.Vector3();
  1755. THREE.Matrix4.__v2 = new THREE.Vector3();
  1756. THREE.Matrix4.__v3 = new THREE.Vector3();
  1757. THREE.Matrix4.__m1 = new THREE.Matrix4();
  1758. THREE.Matrix4.__m2 = new THREE.Matrix4();
  1759. /**
  1760. * https://github.com/mrdoob/eventtarget.js/
  1761. */
  1762. THREE.EventTarget = function () {
  1763. var listeners = {};
  1764. this.addEventListener = function ( type, listener ) {
  1765. if ( listeners[ type ] === undefined ) {
  1766. listeners[ type ] = [];
  1767. }
  1768. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1769. listeners[ type ].push( listener );
  1770. }
  1771. };
  1772. this.dispatchEvent = function ( event ) {
  1773. var listenerArray = listeners[ event.type ];
  1774. if ( listenerArray !== undefined ) {
  1775. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  1776. listenerArray[ i ]( event );
  1777. }
  1778. }
  1779. };
  1780. this.removeEventListener = function ( type, listener ) {
  1781. var index = listeners[ type ].indexOf( listener );
  1782. if ( index !== - 1 ) {
  1783. listeners[ type ].splice( index, 1 );
  1784. }
  1785. };
  1786. };
  1787. /**
  1788. * @author mrdoob / http://mrdoob.com/
  1789. * @author alteredq / http://alteredqualia.com/
  1790. */
  1791. THREE.Frustum = function ( ) {
  1792. this.planes = [
  1793. new THREE.Vector4(),
  1794. new THREE.Vector4(),
  1795. new THREE.Vector4(),
  1796. new THREE.Vector4(),
  1797. new THREE.Vector4(),
  1798. new THREE.Vector4()
  1799. ];
  1800. };
  1801. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  1802. var plane;
  1803. var planes = this.planes;
  1804. var me = m.elements;
  1805. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  1806. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  1807. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  1808. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  1809. planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  1810. planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  1811. planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  1812. planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  1813. planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  1814. planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  1815. for ( var i = 0; i < 6; i ++ ) {
  1816. plane = planes[ i ];
  1817. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  1818. }
  1819. };
  1820. THREE.Frustum.prototype.contains = function ( object ) {
  1821. var distance = 0.0;
  1822. var planes = this.planes;
  1823. var matrix = object.matrixWorld;
  1824. var me = matrix.elements;
  1825. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  1826. for ( var i = 0; i < 6; i ++ ) {
  1827. distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
  1828. if ( distance <= radius ) return false;
  1829. }
  1830. return true;
  1831. };
  1832. THREE.Frustum.__v1 = new THREE.Vector3();
  1833. /**
  1834. * @author mrdoob / http://mrdoob.com/
  1835. */
  1836. ( function ( THREE ) {
  1837. THREE.Ray = function ( origin, direction, near, far ) {
  1838. this.origin = origin || new THREE.Vector3();
  1839. this.direction = direction || new THREE.Vector3();
  1840. this.near = near || 0;
  1841. this.far = far || Infinity;
  1842. };
  1843. var originCopy = new THREE.Vector3();
  1844. var localOriginCopy = new THREE.Vector3();
  1845. var localDirectionCopy = new THREE.Vector3();
  1846. var vector = new THREE.Vector3();
  1847. var normal = new THREE.Vector3();
  1848. var intersectPoint = new THREE.Vector3();
  1849. var inverseMatrix = new THREE.Matrix4();
  1850. var descSort = function ( a, b ) {
  1851. return a.distance - b.distance;
  1852. };
  1853. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  1854. var distanceFromIntersection = function ( origin, direction, position ) {
  1855. v0.sub( position, origin );
  1856. var dot = v0.dot( direction );
  1857. var intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  1858. var distance = position.distanceTo( intersect );
  1859. return distance;
  1860. };
  1861. // http://www.blackpawn.com/texts/pointinpoly/default.html
  1862. var pointInFace3 = function ( p, a, b, c ) {
  1863. v0.sub( c, a );
  1864. v1.sub( b, a );
  1865. v2.sub( p, a );
  1866. var dot00 = v0.dot( v0 );
  1867. var dot01 = v0.dot( v1 );
  1868. var dot02 = v0.dot( v2 );
  1869. var dot11 = v1.dot( v1 );
  1870. var dot12 = v1.dot( v2 );
  1871. var invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  1872. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  1873. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  1874. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  1875. };
  1876. var intersectObject = function ( object, ray, intersects ) {
  1877. if ( object instanceof THREE.Particle ) {
  1878. var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1879. if ( distance > object.scale.x ) {
  1880. return intersects;
  1881. }
  1882. intersects.push( {
  1883. distance: distance,
  1884. point: object.position,
  1885. face: null,
  1886. object: object
  1887. } );
  1888. } else if ( object instanceof THREE.Mesh ) {
  1889. // Checking boundingSphere
  1890. var scaledRadius = object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis();
  1891. // Checking distance to ray
  1892. var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1893. if ( distance > scaledRadius) {
  1894. return intersects;
  1895. }
  1896. // Checking faces
  1897. var geometry = object.geometry;
  1898. var vertices = geometry.vertices;
  1899. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  1900. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  1901. var side = object.material.side;
  1902. var a, b, c, d;
  1903. var precision = ray.precision;
  1904. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  1905. originCopy.copy( ray.origin );
  1906. inverseMatrix.getInverse( object.matrixWorld );
  1907. localOriginCopy.copy( originCopy );
  1908. inverseMatrix.multiplyVector3( localOriginCopy );
  1909. localDirectionCopy.copy( ray.direction );
  1910. inverseMatrix.rotateAxis( localDirectionCopy ).normalize();
  1911. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  1912. var face = geometry.faces[ f ];
  1913. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  1914. if ( material === undefined ) continue;
  1915. side = material.side;
  1916. vector.sub( face.centroid, localOriginCopy );
  1917. var normal = face.normal;
  1918. var dot = localDirectionCopy.dot( normal );
  1919. // bail if ray and plane are parallel
  1920. if ( Math.abs( dot ) < precision ) continue;
  1921. // calc distance to plane
  1922. var scalar = normal.dot( vector ) / dot;
  1923. // if negative distance, then plane is behind ray
  1924. if ( scalar < 0 ) continue;
  1925. if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {
  1926. intersectPoint.add( localOriginCopy, localDirectionCopy.multiplyScalar( scalar ) );
  1927. if ( face instanceof THREE.Face3 ) {
  1928. a = vertices[ face.a ];
  1929. b = vertices[ face.b ];
  1930. c = vertices[ face.c ];
  1931. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  1932. var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1933. distance = originCopy.distanceTo( point );
  1934. if ( distance < ray.near || distance > ray.far ) continue;
  1935. intersects.push( {
  1936. distance: distance,
  1937. point: point,
  1938. face: face,
  1939. faceIndex: f,
  1940. object: object
  1941. } );
  1942. }
  1943. } else if ( face instanceof THREE.Face4 ) {
  1944. a = vertices[ face.a ];
  1945. b = vertices[ face.b ];
  1946. c = vertices[ face.c ];
  1947. d = vertices[ face.d ];
  1948. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  1949. var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1950. distance = originCopy.distanceTo( point );
  1951. if ( distance < ray.near || distance > ray.far ) continue;
  1952. intersects.push( {
  1953. distance: distance,
  1954. point: point,
  1955. face: face,
  1956. faceIndex: f,
  1957. object: object
  1958. } );
  1959. }
  1960. }
  1961. }
  1962. }
  1963. }
  1964. };
  1965. var intersectDescendants = function ( object, ray, intersects ) {
  1966. var descendants = object.getDescendants();
  1967. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  1968. intersectObject( descendants[ i ], ray, intersects );
  1969. }
  1970. };
  1971. //
  1972. THREE.Ray.prototype.precision = 0.0001;
  1973. THREE.Ray.prototype.set = function ( origin, direction ) {
  1974. this.origin = origin;
  1975. this.direction = direction;
  1976. };
  1977. THREE.Ray.prototype.intersectObject = function ( object, recursive ) {
  1978. var intersects = [];
  1979. if ( recursive === true ) {
  1980. intersectDescendants( object, this, intersects );
  1981. }
  1982. intersectObject( object, this, intersects );
  1983. intersects.sort( descSort );
  1984. return intersects;
  1985. };
  1986. THREE.Ray.prototype.intersectObjects = function ( objects, recursive ) {
  1987. var intersects = [];
  1988. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  1989. intersectObject( objects[ i ], this, intersects );
  1990. if ( recursive === true ) {
  1991. intersectDescendants( objects[ i ], this, intersects );
  1992. }
  1993. }
  1994. intersects.sort( descSort );
  1995. return intersects;
  1996. };
  1997. }( THREE ) );
  1998. /**
  1999. * @author mrdoob / http://mrdoob.com/
  2000. */
  2001. THREE.Rectangle = function () {
  2002. var _left = 0;
  2003. var _top = 0;
  2004. var _right = 0;
  2005. var _bottom = 0;
  2006. var _width = 0;
  2007. var _height = 0;
  2008. var _isEmpty = true;
  2009. function resize() {
  2010. _width = _right - _left;
  2011. _height = _bottom - _top;
  2012. }
  2013. this.getX = function () {
  2014. return _left;
  2015. };
  2016. this.getY = function () {
  2017. return _top;
  2018. };
  2019. this.getWidth = function () {
  2020. return _width;
  2021. };
  2022. this.getHeight = function () {
  2023. return _height;
  2024. };
  2025. this.getLeft = function() {
  2026. return _left;
  2027. };
  2028. this.getTop = function() {
  2029. return _top;
  2030. };
  2031. this.getRight = function() {
  2032. return _right;
  2033. };
  2034. this.getBottom = function() {
  2035. return _bottom;
  2036. };
  2037. this.set = function ( left, top, right, bottom ) {
  2038. _isEmpty = false;
  2039. _left = left; _top = top;
  2040. _right = right; _bottom = bottom;
  2041. resize();
  2042. };
  2043. this.addPoint = function ( x, y ) {
  2044. if ( _isEmpty === true ) {
  2045. _isEmpty = false;
  2046. _left = x; _top = y;
  2047. _right = x; _bottom = y;
  2048. resize();
  2049. } else {
  2050. _left = _left < x ? _left : x; // Math.min( _left, x );
  2051. _top = _top < y ? _top : y; // Math.min( _top, y );
  2052. _right = _right > x ? _right : x; // Math.max( _right, x );
  2053. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  2054. resize();
  2055. }
  2056. };
  2057. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  2058. if ( _isEmpty === true ) {
  2059. _isEmpty = false;
  2060. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  2061. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  2062. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  2063. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  2064. resize();
  2065. } else {
  2066. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  2067. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  2068. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  2069. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  2070. resize();
  2071. };
  2072. };
  2073. this.addRectangle = function ( r ) {
  2074. if ( _isEmpty === true ) {
  2075. _isEmpty = false;
  2076. _left = r.getLeft(); _top = r.getTop();
  2077. _right = r.getRight(); _bottom = r.getBottom();
  2078. resize();
  2079. } else {
  2080. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  2081. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  2082. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  2083. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  2084. resize();
  2085. }
  2086. };
  2087. this.inflate = function ( v ) {
  2088. _left -= v; _top -= v;
  2089. _right += v; _bottom += v;
  2090. resize();
  2091. };
  2092. this.minSelf = function ( r ) {
  2093. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  2094. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  2095. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  2096. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  2097. resize();
  2098. };
  2099. this.intersects = function ( r ) {
  2100. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  2101. if ( _right < r.getLeft() ) return false;
  2102. if ( _left > r.getRight() ) return false;
  2103. if ( _bottom < r.getTop() ) return false;
  2104. if ( _top > r.getBottom() ) return false;
  2105. return true;
  2106. };
  2107. this.empty = function () {
  2108. _isEmpty = true;
  2109. _left = 0; _top = 0;
  2110. _right = 0; _bottom = 0;
  2111. resize();
  2112. };
  2113. this.isEmpty = function () {
  2114. return _isEmpty;
  2115. };
  2116. };
  2117. /**
  2118. * @author alteredq / http://alteredqualia.com/
  2119. */
  2120. THREE.Math = {
  2121. // Clamp value to range <a, b>
  2122. clamp: function ( x, a, b ) {
  2123. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2124. },
  2125. // Clamp value to range <a, inf)
  2126. clampBottom: function ( x, a ) {
  2127. return x < a ? a : x;
  2128. },
  2129. // Linear mapping from range <a1, a2> to range <b1, b2>
  2130. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2131. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2132. },
  2133. // Random float from <0, 1> with 16 bits of randomness
  2134. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2135. random16: function () {
  2136. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2137. },
  2138. // Random integer from <low, high> interval
  2139. randInt: function ( low, high ) {
  2140. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2141. },
  2142. // Random float from <low, high> interval
  2143. randFloat: function ( low, high ) {
  2144. return low + Math.random() * ( high - low );
  2145. },
  2146. // Random float from <-range/2, range/2> interval
  2147. randFloatSpread: function ( range ) {
  2148. return range * ( 0.5 - Math.random() );
  2149. },
  2150. sign: function ( x ) {
  2151. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2152. }
  2153. };
  2154. /**
  2155. * @author mrdoob / http://mrdoob.com/
  2156. * @author mikael emtinger / http://gomo.se/
  2157. * @author alteredq / http://alteredqualia.com/
  2158. */
  2159. THREE.Object3D = function () {
  2160. THREE.Object3DLibrary.push( this );
  2161. this.id = THREE.Object3DIdCount ++;
  2162. this.name = '';
  2163. this.properties = {};
  2164. this.parent = undefined;
  2165. this.children = [];
  2166. this.up = new THREE.Vector3( 0, 1, 0 );
  2167. this.position = new THREE.Vector3();
  2168. this.rotation = new THREE.Vector3();
  2169. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  2170. this.scale = new THREE.Vector3( 1, 1, 1 );
  2171. this.renderDepth = null;
  2172. this.rotationAutoUpdate = true;
  2173. this.matrix = new THREE.Matrix4();
  2174. this.matrixWorld = new THREE.Matrix4();
  2175. this.matrixRotationWorld = new THREE.Matrix4();
  2176. this.matrixAutoUpdate = true;
  2177. this.matrixWorldNeedsUpdate = true;
  2178. this.quaternion = new THREE.Quaternion();
  2179. this.useQuaternion = false;
  2180. this.boundRadius = 0.0;
  2181. this.boundRadiusScale = 1.0;
  2182. this.visible = true;
  2183. this.castShadow = false;
  2184. this.receiveShadow = false;
  2185. this.frustumCulled = true;
  2186. this._vector = new THREE.Vector3();
  2187. };
  2188. THREE.Object3D.prototype = {
  2189. constructor: THREE.Object3D,
  2190. applyMatrix: function ( matrix ) {
  2191. this.matrix.multiply( matrix, this.matrix );
  2192. this.scale.getScaleFromMatrix( this.matrix );
  2193. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  2194. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  2195. this.position.getPositionFromMatrix( this.matrix );
  2196. },
  2197. translate: function ( distance, axis ) {
  2198. this.matrix.rotateAxis( axis );
  2199. this.position.addSelf( axis.multiplyScalar( distance ) );
  2200. },
  2201. translateX: function ( distance ) {
  2202. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  2203. },
  2204. translateY: function ( distance ) {
  2205. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  2206. },
  2207. translateZ: function ( distance ) {
  2208. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  2209. },
  2210. localToWorld: function ( vector ) {
  2211. return this.matrixWorld.multiplyVector3( vector );
  2212. },
  2213. worldToLocal: function ( vector ) {
  2214. return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
  2215. },
  2216. lookAt: function ( vector ) {
  2217. // TODO: Add hierarchy support.
  2218. this.matrix.lookAt( vector, this.position, this.up );
  2219. if ( this.rotationAutoUpdate ) {
  2220. if ( this.useQuaternion === false ) {
  2221. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  2222. } else {
  2223. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  2224. }
  2225. }
  2226. },
  2227. add: function ( object ) {
  2228. if ( object === this ) {
  2229. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  2230. return;
  2231. }
  2232. if ( object instanceof THREE.Object3D ) {
  2233. if ( object.parent !== undefined ) {
  2234. object.parent.remove( object );
  2235. }
  2236. object.parent = this;
  2237. this.children.push( object );
  2238. // add to scene
  2239. var scene = this;
  2240. while ( scene.parent !== undefined ) {
  2241. scene = scene.parent;
  2242. }
  2243. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2244. scene.__addObject( object );
  2245. }
  2246. }
  2247. },
  2248. remove: function ( object ) {
  2249. var index = this.children.indexOf( object );
  2250. if ( index !== - 1 ) {
  2251. object.parent = undefined;
  2252. this.children.splice( index, 1 );
  2253. // remove from scene
  2254. var scene = this;
  2255. while ( scene.parent !== undefined ) {
  2256. scene = scene.parent;
  2257. }
  2258. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2259. scene.__removeObject( object );
  2260. }
  2261. }
  2262. },
  2263. traverse: function ( callback ) {
  2264. callback( this );
  2265. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2266. this.children[ i ].traverse( callback );
  2267. }
  2268. },
  2269. getChildByName: function ( name, recursive ) {
  2270. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2271. var child = this.children[ i ];
  2272. if ( child.name === name ) {
  2273. return child;
  2274. }
  2275. if ( recursive === true ) {
  2276. child = child.getChildByName( name, recursive );
  2277. if ( child !== undefined ) {
  2278. return child;
  2279. }
  2280. }
  2281. }
  2282. return undefined;
  2283. },
  2284. getDescendants: function ( array ) {
  2285. if ( array === undefined ) array = [];
  2286. Array.prototype.push.apply( array, this.children );
  2287. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2288. this.children[ i ].getDescendants( array );
  2289. }
  2290. return array;
  2291. },
  2292. updateMatrix: function () {
  2293. this.matrix.setPosition( this.position );
  2294. if ( this.useQuaternion === false ) {
  2295. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  2296. } else {
  2297. this.matrix.setRotationFromQuaternion( this.quaternion );
  2298. }
  2299. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  2300. this.matrix.scale( this.scale );
  2301. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  2302. }
  2303. this.matrixWorldNeedsUpdate = true;
  2304. },
  2305. updateMatrixWorld: function ( force ) {
  2306. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  2307. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  2308. if ( this.parent === undefined ) {
  2309. this.matrixWorld.copy( this.matrix );
  2310. } else {
  2311. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2312. }
  2313. this.matrixWorldNeedsUpdate = false;
  2314. force = true;
  2315. }
  2316. // update children
  2317. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2318. this.children[ i ].updateMatrixWorld( force );
  2319. }
  2320. },
  2321. clone: function ( object ) {
  2322. if ( object === undefined ) object = new THREE.Object3D();
  2323. object.name = this.name;
  2324. object.up.copy( this.up );
  2325. object.position.copy( this.position );
  2326. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  2327. object.eulerOrder = this.eulerOrder;
  2328. object.scale.copy( this.scale );
  2329. object.renderDepth = this.renderDepth;
  2330. object.rotationAutoUpdate = this.rotationAutoUpdate;
  2331. object.matrix.copy( this.matrix );
  2332. object.matrixWorld.copy( this.matrixWorld );
  2333. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  2334. object.matrixAutoUpdate = this.matrixAutoUpdate;
  2335. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  2336. object.quaternion.copy( this.quaternion );
  2337. object.useQuaternion = this.useQuaternion;
  2338. object.boundRadius = this.boundRadius;
  2339. object.boundRadiusScale = this.boundRadiusScale;
  2340. object.visible = this.visible;
  2341. object.castShadow = this.castShadow;
  2342. object.receiveShadow = this.receiveShadow;
  2343. object.frustumCulled = this.frustumCulled;
  2344. for ( var i = 0; i < this.children.length; i ++ ) {
  2345. var child = this.children[ i ];
  2346. object.add( child.clone() );
  2347. }
  2348. return object;
  2349. },
  2350. deallocate: function () {
  2351. var index = THREE.Object3DLibrary.indexOf( this );
  2352. if ( index !== -1 ) THREE.Object3DLibrary.splice( index, 1 );
  2353. }
  2354. };
  2355. THREE.Object3D.__m1 = new THREE.Matrix4();
  2356. THREE.Object3D.defaultEulerOrder = 'XYZ',
  2357. THREE.Object3DIdCount = 0;
  2358. THREE.Object3DLibrary = [];
  2359. /**
  2360. * @author mrdoob / http://mrdoob.com/
  2361. * @author supereggbert / http://www.paulbrunt.co.uk/
  2362. * @author julianwa / https://github.com/julianwa
  2363. */
  2364. THREE.Projector = function() {
  2365. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  2366. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  2367. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  2368. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  2369. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  2370. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  2371. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  2372. _vector3 = new THREE.Vector3(),
  2373. _vector4 = new THREE.Vector4(),
  2374. _viewProjectionMatrix = new THREE.Matrix4(),
  2375. _modelViewProjectionMatrix = new THREE.Matrix4(),
  2376. _normalMatrix = new THREE.Matrix3(),
  2377. _frustum = new THREE.Frustum(),
  2378. _clippedVertex1PositionScreen = new THREE.Vector4(),
  2379. _clippedVertex2PositionScreen = new THREE.Vector4(),
  2380. _face3VertexNormals;
  2381. this.projectVector = function ( vector, camera ) {
  2382. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2383. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2384. _viewProjectionMatrix.multiplyVector3( vector );
  2385. return vector;
  2386. };
  2387. this.unprojectVector = function ( vector, camera ) {
  2388. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  2389. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  2390. _viewProjectionMatrix.multiplyVector3( vector );
  2391. return vector;
  2392. };
  2393. this.pickingRay = function ( vector, camera ) {
  2394. var end, ray, t;
  2395. // set two vectors with opposing z values
  2396. vector.z = -1.0;
  2397. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  2398. this.unprojectVector( vector, camera );
  2399. this.unprojectVector( end, camera );
  2400. // find direction from vector to end
  2401. end.subSelf( vector ).normalize();
  2402. return new THREE.Ray( vector, end );
  2403. };
  2404. var projectGraph = function ( root, sortObjects ) {
  2405. _objectCount = 0;
  2406. _renderData.objects.length = 0;
  2407. _renderData.sprites.length = 0;
  2408. _renderData.lights.length = 0;
  2409. var projectObject = function ( parent ) {
  2410. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  2411. var object = parent.children[ c ];
  2412. if ( object.visible === false ) continue;
  2413. if ( object instanceof THREE.Light ) {
  2414. _renderData.lights.push( object );
  2415. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  2416. if ( object.frustumCulled === false || _frustum.contains( object ) === true ) {
  2417. _object = getNextObjectInPool();
  2418. _object.object = object;
  2419. if ( object.renderDepth !== null ) {
  2420. _object.z = object.renderDepth;
  2421. } else {
  2422. _vector3.copy( object.matrixWorld.getPosition() );
  2423. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2424. _object.z = _vector3.z;
  2425. }
  2426. _renderData.objects.push( _object );
  2427. }
  2428. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  2429. _object = getNextObjectInPool();
  2430. _object.object = object;
  2431. // TODO: Find an elegant and performant solution and remove this dupe code.
  2432. if ( object.renderDepth !== null ) {
  2433. _object.z = object.renderDepth;
  2434. } else {
  2435. _vector3.copy( object.matrixWorld.getPosition() );
  2436. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2437. _object.z = _vector3.z;
  2438. }
  2439. _renderData.sprites.push( _object );
  2440. } else {
  2441. _object = getNextObjectInPool();
  2442. _object.object = object;
  2443. if ( object.renderDepth !== null ) {
  2444. _object.z = object.renderDepth;
  2445. } else {
  2446. _vector3.copy( object.matrixWorld.getPosition() );
  2447. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2448. _object.z = _vector3.z;
  2449. }
  2450. _renderData.objects.push( _object );
  2451. }
  2452. projectObject( object );
  2453. }
  2454. };
  2455. projectObject( root );
  2456. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  2457. return _renderData;
  2458. };
  2459. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  2460. var near = camera.near, far = camera.far, visible = false,
  2461. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object, modelMatrix,
  2462. geometry, vertices, vertex, vertexPositionScreen,
  2463. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  2464. v1, v2, v3, v4, isFaceMaterial, objectMaterials, material, side;
  2465. _face3Count = 0;
  2466. _face4Count = 0;
  2467. _lineCount = 0;
  2468. _particleCount = 0;
  2469. _renderData.elements.length = 0;
  2470. scene.updateMatrixWorld();
  2471. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  2472. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2473. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2474. _frustum.setFromMatrix( _viewProjectionMatrix );
  2475. _renderData = projectGraph( scene, sortObjects );
  2476. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  2477. object = _renderData.objects[ o ].object;
  2478. modelMatrix = object.matrixWorld;
  2479. _vertexCount = 0;
  2480. if ( object instanceof THREE.Mesh ) {
  2481. geometry = object.geometry;
  2482. vertices = geometry.vertices;
  2483. faces = geometry.faces;
  2484. faceVertexUvs = geometry.faceVertexUvs;
  2485. _normalMatrix.getInverse( modelMatrix );
  2486. _normalMatrix.transpose();
  2487. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  2488. objectMaterials = isFaceMaterial === true ? object.material : null;
  2489. side = object.material.side;
  2490. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  2491. _vertex = getNextVertexInPool();
  2492. _vertex.positionWorld.copy( vertices[ v ] );
  2493. modelMatrix.multiplyVector3( _vertex.positionWorld );
  2494. _vertex.positionScreen.copy( _vertex.positionWorld );
  2495. _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
  2496. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  2497. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  2498. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  2499. }
  2500. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  2501. face = faces[ f ];
  2502. material = isFaceMaterial === true ? objectMaterials.materials[ face.materialIndex ] : object.material;
  2503. if ( material === undefined ) continue;
  2504. side = material.side;
  2505. if ( face instanceof THREE.Face3 ) {
  2506. v1 = _vertexPool[ face.a ];
  2507. v2 = _vertexPool[ face.b ];
  2508. v3 = _vertexPool[ face.c ];
  2509. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  2510. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2511. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  2512. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2513. _face = getNextFace3InPool();
  2514. _face.v1.copy( v1 );
  2515. _face.v2.copy( v2 );
  2516. _face.v3.copy( v3 );
  2517. } else {
  2518. continue;
  2519. }
  2520. } else {
  2521. continue;
  2522. }
  2523. } else if ( face instanceof THREE.Face4 ) {
  2524. v1 = _vertexPool[ face.a ];
  2525. v2 = _vertexPool[ face.b ];
  2526. v3 = _vertexPool[ face.c ];
  2527. v4 = _vertexPool[ face.d ];
  2528. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  2529. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2530. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  2531. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  2532. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  2533. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2534. _face = getNextFace4InPool();
  2535. _face.v1.copy( v1 );
  2536. _face.v2.copy( v2 );
  2537. _face.v3.copy( v3 );
  2538. _face.v4.copy( v4 );
  2539. } else {
  2540. continue;
  2541. }
  2542. } else {
  2543. continue;
  2544. }
  2545. }
  2546. _face.normalWorld.copy( face.normal );
  2547. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
  2548. _normalMatrix.multiplyVector3( _face.normalWorld ).normalize();
  2549. _face.centroidWorld.copy( face.centroid );
  2550. modelMatrix.multiplyVector3( _face.centroidWorld );
  2551. _face.centroidScreen.copy( _face.centroidWorld );
  2552. _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
  2553. faceVertexNormals = face.vertexNormals;
  2554. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  2555. normal = _face.vertexNormalsWorld[ n ];
  2556. normal.copy( faceVertexNormals[ n ] );
  2557. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
  2558. _normalMatrix.multiplyVector3( normal ).normalize();
  2559. }
  2560. _face.vertexNormalsLength = faceVertexNormals.length;
  2561. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  2562. uvs = faceVertexUvs[ c ][ f ];
  2563. if ( uvs === undefined ) continue;
  2564. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  2565. _face.uvs[ c ][ u ] = uvs[ u ];
  2566. }
  2567. }
  2568. _face.color = face.color;
  2569. _face.material = material;
  2570. _face.z = _face.centroidScreen.z;
  2571. _renderData.elements.push( _face );
  2572. }
  2573. } else if ( object instanceof THREE.Line ) {
  2574. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
  2575. vertices = object.geometry.vertices;
  2576. v1 = getNextVertexInPool();
  2577. v1.positionScreen.copy( vertices[ 0 ] );
  2578. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2579. // Handle LineStrip and LinePieces
  2580. var step = object.type === THREE.LinePieces ? 2 : 1;
  2581. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2582. v1 = getNextVertexInPool();
  2583. v1.positionScreen.copy( vertices[ v ] );
  2584. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2585. if ( ( v + 1 ) % step > 0 ) continue;
  2586. v2 = _vertexPool[ _vertexCount - 2 ];
  2587. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2588. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2589. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  2590. // Perform the perspective divide
  2591. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2592. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2593. _line = getNextLineInPool();
  2594. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2595. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2596. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2597. _line.material = object.material;
  2598. _renderData.elements.push( _line );
  2599. }
  2600. }
  2601. }
  2602. }
  2603. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2604. object = _renderData.sprites[ o ].object;
  2605. modelMatrix = object.matrixWorld;
  2606. if ( object instanceof THREE.Particle ) {
  2607. _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
  2608. _viewProjectionMatrix.multiplyVector4( _vector4 );
  2609. _vector4.z /= _vector4.w;
  2610. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2611. _particle = getNextParticleInPool();
  2612. _particle.object = object;
  2613. _particle.x = _vector4.x / _vector4.w;
  2614. _particle.y = _vector4.y / _vector4.w;
  2615. _particle.z = _vector4.z;
  2616. _particle.rotation = object.rotation.z;
  2617. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2618. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2619. _particle.material = object.material;
  2620. _renderData.elements.push( _particle );
  2621. }
  2622. }
  2623. }
  2624. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  2625. return _renderData;
  2626. };
  2627. // Pools
  2628. function getNextObjectInPool() {
  2629. if ( _objectCount === _objectPoolLength ) {
  2630. var object = new THREE.RenderableObject();
  2631. _objectPool.push( object );
  2632. _objectPoolLength ++;
  2633. _objectCount ++;
  2634. return object;
  2635. }
  2636. return _objectPool[ _objectCount ++ ];
  2637. }
  2638. function getNextVertexInPool() {
  2639. if ( _vertexCount === _vertexPoolLength ) {
  2640. var vertex = new THREE.RenderableVertex();
  2641. _vertexPool.push( vertex );
  2642. _vertexPoolLength ++;
  2643. _vertexCount ++;
  2644. return vertex;
  2645. }
  2646. return _vertexPool[ _vertexCount ++ ];
  2647. }
  2648. function getNextFace3InPool() {
  2649. if ( _face3Count === _face3PoolLength ) {
  2650. var face = new THREE.RenderableFace3();
  2651. _face3Pool.push( face );
  2652. _face3PoolLength ++;
  2653. _face3Count ++;
  2654. return face;
  2655. }
  2656. return _face3Pool[ _face3Count ++ ];
  2657. }
  2658. function getNextFace4InPool() {
  2659. if ( _face4Count === _face4PoolLength ) {
  2660. var face = new THREE.RenderableFace4();
  2661. _face4Pool.push( face );
  2662. _face4PoolLength ++;
  2663. _face4Count ++;
  2664. return face;
  2665. }
  2666. return _face4Pool[ _face4Count ++ ];
  2667. }
  2668. function getNextLineInPool() {
  2669. if ( _lineCount === _linePoolLength ) {
  2670. var line = new THREE.RenderableLine();
  2671. _linePool.push( line );
  2672. _linePoolLength ++;
  2673. _lineCount ++
  2674. return line;
  2675. }
  2676. return _linePool[ _lineCount ++ ];
  2677. }
  2678. function getNextParticleInPool() {
  2679. if ( _particleCount === _particlePoolLength ) {
  2680. var particle = new THREE.RenderableParticle();
  2681. _particlePool.push( particle );
  2682. _particlePoolLength ++;
  2683. _particleCount ++
  2684. return particle;
  2685. }
  2686. return _particlePool[ _particleCount ++ ];
  2687. }
  2688. //
  2689. function painterSort( a, b ) {
  2690. return b.z - a.z;
  2691. }
  2692. function clipLine( s1, s2 ) {
  2693. var alpha1 = 0, alpha2 = 1,
  2694. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2695. // Z = -1 and Z = +1, respectively.
  2696. bc1near = s1.z + s1.w,
  2697. bc2near = s2.z + s2.w,
  2698. bc1far = - s1.z + s1.w,
  2699. bc2far = - s2.z + s2.w;
  2700. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2701. // Both vertices lie entirely within all clip planes.
  2702. return true;
  2703. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2704. // Both vertices lie entirely outside one of the clip planes.
  2705. return false;
  2706. } else {
  2707. // The line segment spans at least one clip plane.
  2708. if ( bc1near < 0 ) {
  2709. // v1 lies outside the near plane, v2 inside
  2710. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2711. } else if ( bc2near < 0 ) {
  2712. // v2 lies outside the near plane, v1 inside
  2713. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2714. }
  2715. if ( bc1far < 0 ) {
  2716. // v1 lies outside the far plane, v2 inside
  2717. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2718. } else if ( bc2far < 0 ) {
  2719. // v2 lies outside the far plane, v2 inside
  2720. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2721. }
  2722. if ( alpha2 < alpha1 ) {
  2723. // The line segment spans two boundaries, but is outside both of them.
  2724. // (This can't happen when we're only clipping against just near/far but good
  2725. // to leave the check here for future usage if other clip planes are added.)
  2726. return false;
  2727. } else {
  2728. // Update the s1 and s2 vertices to match the clipped line segment.
  2729. s1.lerpSelf( s2, alpha1 );
  2730. s2.lerpSelf( s1, 1 - alpha2 );
  2731. return true;
  2732. }
  2733. }
  2734. }
  2735. };
  2736. /**
  2737. * @author mikael emtinger / http://gomo.se/
  2738. * @author alteredq / http://alteredqualia.com/
  2739. * @author WestLangley / http://github.com/WestLangley
  2740. */
  2741. THREE.Quaternion = function( x, y, z, w ) {
  2742. this.x = x || 0;
  2743. this.y = y || 0;
  2744. this.z = z || 0;
  2745. this.w = ( w !== undefined ) ? w : 1;
  2746. };
  2747. THREE.Quaternion.prototype = {
  2748. constructor: THREE.Quaternion,
  2749. set: function ( x, y, z, w ) {
  2750. this.x = x;
  2751. this.y = y;
  2752. this.z = z;
  2753. this.w = w;
  2754. return this;
  2755. },
  2756. copy: function ( q ) {
  2757. this.x = q.x;
  2758. this.y = q.y;
  2759. this.z = q.z;
  2760. this.w = q.w;
  2761. return this;
  2762. },
  2763. setFromEuler: function ( v, order ) {
  2764. // http://www.mathworks.com/matlabcentral/fileexchange/
  2765. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2766. // content/SpinCalc.m
  2767. var c1 = Math.cos( v.x / 2 );
  2768. var c2 = Math.cos( v.y / 2 );
  2769. var c3 = Math.cos( v.z / 2 );
  2770. var s1 = Math.sin( v.x / 2 );
  2771. var s2 = Math.sin( v.y / 2 );
  2772. var s3 = Math.sin( v.z / 2 );
  2773. if ( order === undefined || order === 'XYZ' ) {
  2774. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2775. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2776. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2777. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2778. } else if ( order === 'YXZ' ) {
  2779. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2780. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2781. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2782. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2783. } else if ( order === 'ZXY' ) {
  2784. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2785. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2786. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2787. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2788. } else if ( order === 'ZYX' ) {
  2789. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2790. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2791. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2792. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2793. } else if ( order === 'YZX' ) {
  2794. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2795. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2796. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2797. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2798. } else if ( order === 'XZY' ) {
  2799. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2800. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2801. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2802. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2803. }
  2804. return this;
  2805. },
  2806. setFromAxisAngle: function ( axis, angle ) {
  2807. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2808. // axis have to be normalized
  2809. var halfAngle = angle / 2,
  2810. s = Math.sin( halfAngle );
  2811. this.x = axis.x * s;
  2812. this.y = axis.y * s;
  2813. this.z = axis.z * s;
  2814. this.w = Math.cos( halfAngle );
  2815. return this;
  2816. },
  2817. setFromRotationMatrix: function ( m ) {
  2818. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2819. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2820. var te = m.elements,
  2821. m11 = te[0], m12 = te[4], m13 = te[8],
  2822. m21 = te[1], m22 = te[5], m23 = te[9],
  2823. m31 = te[2], m32 = te[6], m33 = te[10],
  2824. trace = m11 + m22 + m33,
  2825. s;
  2826. if( trace > 0 ) {
  2827. s = 0.5 / Math.sqrt( trace + 1.0 );
  2828. this.w = 0.25 / s;
  2829. this.x = ( m32 - m23 ) * s;
  2830. this.y = ( m13 - m31 ) * s;
  2831. this.z = ( m21 - m12 ) * s;
  2832. } else if ( m11 > m22 && m11 > m33 ) {
  2833. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2834. this.w = (m32 - m23 ) / s;
  2835. this.x = 0.25 * s;
  2836. this.y = (m12 + m21 ) / s;
  2837. this.z = (m13 + m31 ) / s;
  2838. } else if (m22 > m33) {
  2839. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2840. this.w = (m13 - m31 ) / s;
  2841. this.x = (m12 + m21 ) / s;
  2842. this.y = 0.25 * s;
  2843. this.z = (m23 + m32 ) / s;
  2844. } else {
  2845. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2846. this.w = ( m21 - m12 ) / s;
  2847. this.x = ( m13 + m31 ) / s;
  2848. this.y = ( m23 + m32 ) / s;
  2849. this.z = 0.25 * s;
  2850. }
  2851. return this;
  2852. },
  2853. inverse: function () {
  2854. this.conjugate().normalize();
  2855. return this;
  2856. },
  2857. conjugate: function () {
  2858. this.x *= -1;
  2859. this.y *= -1;
  2860. this.z *= -1;
  2861. return this;
  2862. },
  2863. length: function () {
  2864. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2865. },
  2866. normalize: function () {
  2867. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2868. if ( l === 0 ) {
  2869. this.x = 0;
  2870. this.y = 0;
  2871. this.z = 0;
  2872. this.w = 1;
  2873. } else {
  2874. l = 1 / l;
  2875. this.x = this.x * l;
  2876. this.y = this.y * l;
  2877. this.z = this.z * l;
  2878. this.w = this.w * l;
  2879. }
  2880. return this;
  2881. },
  2882. multiply: function ( a, b ) {
  2883. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2884. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
  2885. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2886. this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
  2887. this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
  2888. this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
  2889. this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
  2890. return this;
  2891. },
  2892. multiplySelf: function ( b ) {
  2893. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2894. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2895. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2896. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2897. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2898. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2899. return this;
  2900. },
  2901. multiplyVector3: function ( vector, dest ) {
  2902. if ( !dest ) { dest = vector; }
  2903. var x = vector.x, y = vector.y, z = vector.z,
  2904. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2905. // calculate quat * vector
  2906. var ix = qw * x + qy * z - qz * y,
  2907. iy = qw * y + qz * x - qx * z,
  2908. iz = qw * z + qx * y - qy * x,
  2909. iw = -qx * x - qy * y - qz * z;
  2910. // calculate result * inverse quat
  2911. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2912. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2913. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2914. return dest;
  2915. },
  2916. slerpSelf: function ( qb, t ) {
  2917. var x = this.x, y = this.y, z = this.z, w = this.w;
  2918. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2919. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  2920. if ( cosHalfTheta < 0 ) {
  2921. this.w = -qb.w;
  2922. this.x = -qb.x;
  2923. this.y = -qb.y;
  2924. this.z = -qb.z;
  2925. cosHalfTheta = -cosHalfTheta;
  2926. } else {
  2927. this.copy( qb );
  2928. }
  2929. if ( cosHalfTheta >= 1.0 ) {
  2930. this.w = w;
  2931. this.x = x;
  2932. this.y = y;
  2933. this.z = z;
  2934. return this;
  2935. }
  2936. var halfTheta = Math.acos( cosHalfTheta );
  2937. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2938. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2939. this.w = 0.5 * ( w + this.w );
  2940. this.x = 0.5 * ( x + this.x );
  2941. this.y = 0.5 * ( y + this.y );
  2942. this.z = 0.5 * ( z + this.z );
  2943. return this;
  2944. }
  2945. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2946. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2947. this.w = ( w * ratioA + this.w * ratioB );
  2948. this.x = ( x * ratioA + this.x * ratioB );
  2949. this.y = ( y * ratioA + this.y * ratioB );
  2950. this.z = ( z * ratioA + this.z * ratioB );
  2951. return this;
  2952. },
  2953. clone: function () {
  2954. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2955. }
  2956. }
  2957. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2958. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2959. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2960. if ( cosHalfTheta < 0 ) {
  2961. qm.w = -qb.w;
  2962. qm.x = -qb.x;
  2963. qm.y = -qb.y;
  2964. qm.z = -qb.z;
  2965. cosHalfTheta = -cosHalfTheta;
  2966. } else {
  2967. qm.copy( qb );
  2968. }
  2969. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2970. qm.w = qa.w;
  2971. qm.x = qa.x;
  2972. qm.y = qa.y;
  2973. qm.z = qa.z;
  2974. return qm;
  2975. }
  2976. var halfTheta = Math.acos( cosHalfTheta );
  2977. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2978. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2979. qm.w = 0.5 * ( qa.w + qm.w );
  2980. qm.x = 0.5 * ( qa.x + qm.x );
  2981. qm.y = 0.5 * ( qa.y + qm.y );
  2982. qm.z = 0.5 * ( qa.z + qm.z );
  2983. return qm;
  2984. }
  2985. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
  2986. var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2987. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2988. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2989. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2990. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2991. return qm;
  2992. }
  2993. /**
  2994. * @author mrdoob / http://mrdoob.com/
  2995. */
  2996. THREE.Vertex = function ( v ) {
  2997. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  2998. return v;
  2999. };
  3000. /**
  3001. * @author mrdoob / http://mrdoob.com/
  3002. * @author alteredq / http://alteredqualia.com/
  3003. */
  3004. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  3005. this.a = a;
  3006. this.b = b;
  3007. this.c = c;
  3008. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  3009. this.vertexNormals = normal instanceof Array ? normal : [ ];
  3010. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  3011. this.vertexColors = color instanceof Array ? color : [];
  3012. this.vertexTangents = [];
  3013. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  3014. this.centroid = new THREE.Vector3();
  3015. };
  3016. THREE.Face3.prototype = {
  3017. constructor: THREE.Face3,
  3018. clone: function () {
  3019. var face = new THREE.Face3( this.a, this.b, this.c );
  3020. face.normal.copy( this.normal );
  3021. face.color.copy( this.color );
  3022. face.centroid.copy( this.centroid );
  3023. face.materialIndex = this.materialIndex;
  3024. var i, il;
  3025. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  3026. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  3027. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  3028. return face;
  3029. }
  3030. };
  3031. /**
  3032. * @author mrdoob / http://mrdoob.com/
  3033. * @author alteredq / http://alteredqualia.com/
  3034. */
  3035. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  3036. this.a = a;
  3037. this.b = b;
  3038. this.c = c;
  3039. this.d = d;
  3040. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  3041. this.vertexNormals = normal instanceof Array ? normal : [ ];
  3042. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  3043. this.vertexColors = color instanceof Array ? color : [];
  3044. this.vertexTangents = [];
  3045. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  3046. this.centroid = new THREE.Vector3();
  3047. };
  3048. THREE.Face4.prototype = {
  3049. constructor: THREE.Face4,
  3050. clone: function () {
  3051. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  3052. face.normal.copy( this.normal );
  3053. face.color.copy( this.color );
  3054. face.centroid.copy( this.centroid );
  3055. face.materialIndex = this.materialIndex;
  3056. var i, il;
  3057. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  3058. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  3059. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  3060. return face;
  3061. }
  3062. };
  3063. /**
  3064. * @author mrdoob / http://mrdoob.com/
  3065. */
  3066. THREE.UV = function ( u, v ) {
  3067. this.u = u || 0;
  3068. this.v = v || 0;
  3069. };
  3070. THREE.UV.prototype = {
  3071. constructor: THREE.UV,
  3072. set: function ( u, v ) {
  3073. this.u = u;
  3074. this.v = v;
  3075. return this;
  3076. },
  3077. copy: function ( uv ) {
  3078. this.u = uv.u;
  3079. this.v = uv.v;
  3080. return this;
  3081. },
  3082. lerpSelf: function ( uv, alpha ) {
  3083. this.u += ( uv.u - this.u ) * alpha;
  3084. this.v += ( uv.v - this.v ) * alpha;
  3085. return this;
  3086. },
  3087. clone: function () {
  3088. return new THREE.UV( this.u, this.v );
  3089. }
  3090. };
  3091. /**
  3092. * @author mrdoob / http://mrdoob.com/
  3093. * @author kile / http://kile.stravaganza.org/
  3094. * @author alteredq / http://alteredqualia.com/
  3095. * @author mikael emtinger / http://gomo.se/
  3096. * @author zz85 / http://www.lab4games.net/zz85/blog
  3097. */
  3098. THREE.Geometry = function () {
  3099. THREE.GeometryLibrary.push( this );
  3100. this.id = THREE.GeometryIdCount ++;
  3101. this.name = '';
  3102. this.vertices = [];
  3103. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  3104. this.normals = []; // one-to-one vertex normals, used in Ribbon
  3105. this.faces = [];
  3106. this.faceUvs = [[]];
  3107. this.faceVertexUvs = [[]];
  3108. this.morphTargets = [];
  3109. this.morphColors = [];
  3110. this.morphNormals = [];
  3111. this.skinWeights = [];
  3112. this.skinIndices = [];
  3113. this.lineDistances = [];
  3114. this.boundingBox = null;
  3115. this.boundingSphere = null;
  3116. this.hasTangents = false;
  3117. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  3118. // update flags
  3119. this.verticesNeedUpdate = false;
  3120. this.elementsNeedUpdate = false;
  3121. this.uvsNeedUpdate = false;
  3122. this.normalsNeedUpdate = false;
  3123. this.tangentsNeedUpdate = false;
  3124. this.colorsNeedUpdate = false;
  3125. this.lineDistancesNeedUpdate = false;
  3126. this.buffersNeedUpdate = false;
  3127. };
  3128. THREE.Geometry.prototype = {
  3129. constructor : THREE.Geometry,
  3130. applyMatrix: function ( matrix ) {
  3131. var normalMatrix = new THREE.Matrix3();
  3132. normalMatrix.getInverse( matrix ).transpose();
  3133. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  3134. var vertex = this.vertices[ i ];
  3135. matrix.multiplyVector3( vertex );
  3136. }
  3137. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  3138. var face = this.faces[ i ];
  3139. normalMatrix.multiplyVector3( face.normal ).normalize();
  3140. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  3141. normalMatrix.multiplyVector3( face.vertexNormals[ j ] ).normalize();
  3142. }
  3143. matrix.multiplyVector3( face.centroid );
  3144. }
  3145. },
  3146. computeCentroids: function () {
  3147. var f, fl, face;
  3148. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3149. face = this.faces[ f ];
  3150. face.centroid.set( 0, 0, 0 );
  3151. if ( face instanceof THREE.Face3 ) {
  3152. face.centroid.addSelf( this.vertices[ face.a ] );
  3153. face.centroid.addSelf( this.vertices[ face.b ] );
  3154. face.centroid.addSelf( this.vertices[ face.c ] );
  3155. face.centroid.divideScalar( 3 );
  3156. } else if ( face instanceof THREE.Face4 ) {
  3157. face.centroid.addSelf( this.vertices[ face.a ] );
  3158. face.centroid.addSelf( this.vertices[ face.b ] );
  3159. face.centroid.addSelf( this.vertices[ face.c ] );
  3160. face.centroid.addSelf( this.vertices[ face.d ] );
  3161. face.centroid.divideScalar( 4 );
  3162. }
  3163. }
  3164. },
  3165. computeFaceNormals: function () {
  3166. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  3167. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  3168. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3169. face = this.faces[ f ];
  3170. vA = this.vertices[ face.a ];
  3171. vB = this.vertices[ face.b ];
  3172. vC = this.vertices[ face.c ];
  3173. cb.sub( vC, vB );
  3174. ab.sub( vA, vB );
  3175. cb.crossSelf( ab );
  3176. cb.normalize();
  3177. face.normal.copy( cb );
  3178. }
  3179. },
  3180. computeVertexNormals: function ( areaWeighted ) {
  3181. var v, vl, f, fl, face, vertices;
  3182. // create internal buffers for reuse when calling this method repeatedly
  3183. // (otherwise memory allocation / deallocation every frame is big resource hog)
  3184. if ( this.__tmpVertices === undefined ) {
  3185. this.__tmpVertices = new Array( this.vertices.length );
  3186. vertices = this.__tmpVertices;
  3187. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3188. vertices[ v ] = new THREE.Vector3();
  3189. }
  3190. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3191. face = this.faces[ f ];
  3192. if ( face instanceof THREE.Face3 ) {
  3193. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3194. } else if ( face instanceof THREE.Face4 ) {
  3195. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3196. }
  3197. }
  3198. } else {
  3199. vertices = this.__tmpVertices;
  3200. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3201. vertices[ v ].set( 0, 0, 0 );
  3202. }
  3203. }
  3204. if ( areaWeighted ) {
  3205. // vertex normals weighted by triangle areas
  3206. // http://www.iquilezles.org/www/articles/normals/normals.htm
  3207. var vA, vB, vC, vD;
  3208. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  3209. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  3210. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3211. face = this.faces[ f ];
  3212. if ( face instanceof THREE.Face3 ) {
  3213. vA = this.vertices[ face.a ];
  3214. vB = this.vertices[ face.b ];
  3215. vC = this.vertices[ face.c ];
  3216. cb.sub( vC, vB );
  3217. ab.sub( vA, vB );
  3218. cb.crossSelf( ab );
  3219. vertices[ face.a ].addSelf( cb );
  3220. vertices[ face.b ].addSelf( cb );
  3221. vertices[ face.c ].addSelf( cb );
  3222. } else if ( face instanceof THREE.Face4 ) {
  3223. vA = this.vertices[ face.a ];
  3224. vB = this.vertices[ face.b ];
  3225. vC = this.vertices[ face.c ];
  3226. vD = this.vertices[ face.d ];
  3227. // abd
  3228. db.sub( vD, vB );
  3229. ab.sub( vA, vB );
  3230. db.crossSelf( ab );
  3231. vertices[ face.a ].addSelf( db );
  3232. vertices[ face.b ].addSelf( db );
  3233. vertices[ face.d ].addSelf( db );
  3234. // bcd
  3235. dc.sub( vD, vC );
  3236. bc.sub( vB, vC );
  3237. dc.crossSelf( bc );
  3238. vertices[ face.b ].addSelf( dc );
  3239. vertices[ face.c ].addSelf( dc );
  3240. vertices[ face.d ].addSelf( dc );
  3241. }
  3242. }
  3243. } else {
  3244. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3245. face = this.faces[ f ];
  3246. if ( face instanceof THREE.Face3 ) {
  3247. vertices[ face.a ].addSelf( face.normal );
  3248. vertices[ face.b ].addSelf( face.normal );
  3249. vertices[ face.c ].addSelf( face.normal );
  3250. } else if ( face instanceof THREE.Face4 ) {
  3251. vertices[ face.a ].addSelf( face.normal );
  3252. vertices[ face.b ].addSelf( face.normal );
  3253. vertices[ face.c ].addSelf( face.normal );
  3254. vertices[ face.d ].addSelf( face.normal );
  3255. }
  3256. }
  3257. }
  3258. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3259. vertices[ v ].normalize();
  3260. }
  3261. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3262. face = this.faces[ f ];
  3263. if ( face instanceof THREE.Face3 ) {
  3264. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3265. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3266. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3267. } else if ( face instanceof THREE.Face4 ) {
  3268. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3269. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3270. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3271. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  3272. }
  3273. }
  3274. },
  3275. computeMorphNormals: function () {
  3276. var i, il, f, fl, face;
  3277. // save original normals
  3278. // - create temp variables on first access
  3279. // otherwise just copy (for faster repeated calls)
  3280. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3281. face = this.faces[ f ];
  3282. if ( ! face.__originalFaceNormal ) {
  3283. face.__originalFaceNormal = face.normal.clone();
  3284. } else {
  3285. face.__originalFaceNormal.copy( face.normal );
  3286. }
  3287. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  3288. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  3289. if ( ! face.__originalVertexNormals[ i ] ) {
  3290. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  3291. } else {
  3292. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  3293. }
  3294. }
  3295. }
  3296. // use temp geometry to compute face and vertex normals for each morph
  3297. var tmpGeo = new THREE.Geometry();
  3298. tmpGeo.faces = this.faces;
  3299. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  3300. // create on first access
  3301. if ( ! this.morphNormals[ i ] ) {
  3302. this.morphNormals[ i ] = {};
  3303. this.morphNormals[ i ].faceNormals = [];
  3304. this.morphNormals[ i ].vertexNormals = [];
  3305. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  3306. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  3307. var faceNormal, vertexNormals;
  3308. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3309. face = this.faces[ f ];
  3310. faceNormal = new THREE.Vector3();
  3311. if ( face instanceof THREE.Face3 ) {
  3312. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  3313. } else {
  3314. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  3315. }
  3316. dstNormalsFace.push( faceNormal );
  3317. dstNormalsVertex.push( vertexNormals );
  3318. }
  3319. }
  3320. var morphNormals = this.morphNormals[ i ];
  3321. // set vertices to morph target
  3322. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  3323. // compute morph normals
  3324. tmpGeo.computeFaceNormals();
  3325. tmpGeo.computeVertexNormals();
  3326. // store morph normals
  3327. var faceNormal, vertexNormals;
  3328. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3329. face = this.faces[ f ];
  3330. faceNormal = morphNormals.faceNormals[ f ];
  3331. vertexNormals = morphNormals.vertexNormals[ f ];
  3332. faceNormal.copy( face.normal );
  3333. if ( face instanceof THREE.Face3 ) {
  3334. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3335. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3336. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3337. } else {
  3338. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3339. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3340. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3341. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  3342. }
  3343. }
  3344. }
  3345. // restore original normals
  3346. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3347. face = this.faces[ f ];
  3348. face.normal = face.__originalFaceNormal;
  3349. face.vertexNormals = face.__originalVertexNormals;
  3350. }
  3351. },
  3352. computeTangents: function () {
  3353. // based on http://www.terathon.com/code/tangent.html
  3354. // tangents go to vertices
  3355. var f, fl, v, vl, i, il, vertexIndex,
  3356. face, uv, vA, vB, vC, uvA, uvB, uvC,
  3357. x1, x2, y1, y2, z1, z2,
  3358. s1, s2, t1, t2, r, t, test,
  3359. tan1 = [], tan2 = [],
  3360. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  3361. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  3362. n = new THREE.Vector3(), w;
  3363. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3364. tan1[ v ] = new THREE.Vector3();
  3365. tan2[ v ] = new THREE.Vector3();
  3366. }
  3367. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  3368. vA = context.vertices[ a ];
  3369. vB = context.vertices[ b ];
  3370. vC = context.vertices[ c ];
  3371. uvA = uv[ ua ];
  3372. uvB = uv[ ub ];
  3373. uvC = uv[ uc ];
  3374. x1 = vB.x - vA.x;
  3375. x2 = vC.x - vA.x;
  3376. y1 = vB.y - vA.y;
  3377. y2 = vC.y - vA.y;
  3378. z1 = vB.z - vA.z;
  3379. z2 = vC.z - vA.z;
  3380. s1 = uvB.u - uvA.u;
  3381. s2 = uvC.u - uvA.u;
  3382. t1 = uvB.v - uvA.v;
  3383. t2 = uvC.v - uvA.v;
  3384. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3385. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  3386. ( t2 * y1 - t1 * y2 ) * r,
  3387. ( t2 * z1 - t1 * z2 ) * r );
  3388. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  3389. ( s1 * y2 - s2 * y1 ) * r,
  3390. ( s1 * z2 - s2 * z1 ) * r );
  3391. tan1[ a ].addSelf( sdir );
  3392. tan1[ b ].addSelf( sdir );
  3393. tan1[ c ].addSelf( sdir );
  3394. tan2[ a ].addSelf( tdir );
  3395. tan2[ b ].addSelf( tdir );
  3396. tan2[ c ].addSelf( tdir );
  3397. }
  3398. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3399. face = this.faces[ f ];
  3400. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  3401. if ( face instanceof THREE.Face3 ) {
  3402. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  3403. } else if ( face instanceof THREE.Face4 ) {
  3404. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  3405. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  3406. }
  3407. }
  3408. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  3409. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3410. face = this.faces[ f ];
  3411. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  3412. n.copy( face.vertexNormals[ i ] );
  3413. vertexIndex = face[ faceIndex[ i ] ];
  3414. t = tan1[ vertexIndex ];
  3415. // Gram-Schmidt orthogonalize
  3416. tmp.copy( t );
  3417. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3418. // Calculate handedness
  3419. tmp2.cross( face.vertexNormals[ i ], t );
  3420. test = tmp2.dot( tan2[ vertexIndex ] );
  3421. w = (test < 0.0) ? -1.0 : 1.0;
  3422. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  3423. }
  3424. }
  3425. this.hasTangents = true;
  3426. },
  3427. computeLineDistances: function ( ) {
  3428. var d = 0;
  3429. var vertices = this.vertices;
  3430. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  3431. if ( i > 0 ) {
  3432. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  3433. }
  3434. this.lineDistances[ i ] = d;
  3435. }
  3436. },
  3437. computeBoundingBox: function () {
  3438. if ( ! this.boundingBox ) {
  3439. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  3440. }
  3441. if ( this.vertices.length > 0 ) {
  3442. var position, firstPosition = this.vertices[ 0 ];
  3443. this.boundingBox.min.copy( firstPosition );
  3444. this.boundingBox.max.copy( firstPosition );
  3445. var min = this.boundingBox.min,
  3446. max = this.boundingBox.max;
  3447. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  3448. position = this.vertices[ v ];
  3449. if ( position.x < min.x ) {
  3450. min.x = position.x;
  3451. } else if ( position.x > max.x ) {
  3452. max.x = position.x;
  3453. }
  3454. if ( position.y < min.y ) {
  3455. min.y = position.y;
  3456. } else if ( position.y > max.y ) {
  3457. max.y = position.y;
  3458. }
  3459. if ( position.z < min.z ) {
  3460. min.z = position.z;
  3461. } else if ( position.z > max.z ) {
  3462. max.z = position.z;
  3463. }
  3464. }
  3465. } else {
  3466. this.boundingBox.min.set( 0, 0, 0 );
  3467. this.boundingBox.max.set( 0, 0, 0 );
  3468. }
  3469. },
  3470. computeBoundingSphere: function () {
  3471. var maxRadiusSq = 0;
  3472. if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };
  3473. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  3474. var radiusSq = this.vertices[ i ].lengthSq();
  3475. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3476. }
  3477. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3478. },
  3479. /*
  3480. * Checks for duplicate vertices with hashmap.
  3481. * Duplicated vertices are removed
  3482. * and faces' vertices are updated.
  3483. */
  3484. mergeVertices: function () {
  3485. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  3486. var unique = [], changes = [];
  3487. var v, key;
  3488. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  3489. var precision = Math.pow( 10, precisionPoints );
  3490. var i,il, face;
  3491. var abcd = 'abcd', o, k, j, jl, u;
  3492. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  3493. v = this.vertices[ i ];
  3494. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  3495. if ( verticesMap[ key ] === undefined ) {
  3496. verticesMap[ key ] = i;
  3497. unique.push( this.vertices[ i ] );
  3498. changes[ i ] = unique.length - 1;
  3499. } else {
  3500. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  3501. changes[ i ] = changes[ verticesMap[ key ] ];
  3502. }
  3503. };
  3504. // Start to patch face indices
  3505. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  3506. face = this.faces[ i ];
  3507. if ( face instanceof THREE.Face3 ) {
  3508. face.a = changes[ face.a ];
  3509. face.b = changes[ face.b ];
  3510. face.c = changes[ face.c ];
  3511. } else if ( face instanceof THREE.Face4 ) {
  3512. face.a = changes[ face.a ];
  3513. face.b = changes[ face.b ];
  3514. face.c = changes[ face.c ];
  3515. face.d = changes[ face.d ];
  3516. // check dups in (a, b, c, d) and convert to -> face3
  3517. o = [ face.a, face.b, face.c, face.d ];
  3518. for ( k = 3; k > 0; k -- ) {
  3519. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  3520. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  3521. o.splice( k, 1 );
  3522. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  3523. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  3524. u = this.faceVertexUvs[ j ][ i ];
  3525. if ( u ) u.splice( k, 1 );
  3526. }
  3527. this.faces[ i ].vertexColors = face.vertexColors;
  3528. break;
  3529. }
  3530. }
  3531. }
  3532. }
  3533. // Use unique set of vertices
  3534. var diff = this.vertices.length - unique.length;
  3535. this.vertices = unique;
  3536. return diff;
  3537. },
  3538. clone: function () {
  3539. var geometry = new THREE.Geometry();
  3540. var vertices = this.vertices;
  3541. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  3542. geometry.vertices.push( vertices[ i ].clone() );
  3543. }
  3544. var faces = this.faces;
  3545. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  3546. geometry.faces.push( faces[ i ].clone() );
  3547. }
  3548. var uvs = this.faceVertexUvs[ 0 ];
  3549. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  3550. var uv = uvs[ i ], uvCopy = [];
  3551. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  3552. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  3553. }
  3554. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  3555. }
  3556. return geometry;
  3557. },
  3558. deallocate: function () {
  3559. var index = THREE.GeometryLibrary.indexOf( this );
  3560. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  3561. }
  3562. };
  3563. THREE.GeometryIdCount = 0;
  3564. THREE.GeometryLibrary = [];
  3565. /**
  3566. * @author alteredq / http://alteredqualia.com/
  3567. */
  3568. THREE.BufferGeometry = function () {
  3569. THREE.GeometryLibrary.push( this );
  3570. this.id = THREE.GeometryIdCount ++;
  3571. // attributes
  3572. this.attributes = {};
  3573. // attributes typed arrays are kept only if dynamic flag is set
  3574. this.dynamic = false;
  3575. // offsets for chunks when using indexed elements
  3576. this.offsets = [];
  3577. // boundings
  3578. this.boundingBox = null;
  3579. this.boundingSphere = null;
  3580. this.hasTangents = false;
  3581. // for compatibility
  3582. this.morphTargets = [];
  3583. };
  3584. THREE.BufferGeometry.prototype = {
  3585. constructor : THREE.BufferGeometry,
  3586. applyMatrix: function ( matrix ) {
  3587. var positionArray;
  3588. var normalArray;
  3589. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  3590. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  3591. if ( positionArray !== undefined ) {
  3592. matrix.multiplyVector3Array( positionArray );
  3593. this.verticesNeedUpdate = true;
  3594. }
  3595. if ( normalArray !== undefined ) {
  3596. var normalMatrix = new THREE.Matrix3();
  3597. normalMatrix.getInverse( matrix ).transpose();
  3598. normalMatrix.multiplyVector3Array( normalArray );
  3599. this.normalizeNormals();
  3600. this.normalsNeedUpdate = true;
  3601. }
  3602. },
  3603. computeBoundingBox: function () {
  3604. if ( ! this.boundingBox ) {
  3605. this.boundingBox = {
  3606. min: new THREE.Vector3( Infinity, Infinity, Infinity ),
  3607. max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
  3608. };
  3609. }
  3610. var positions = this.attributes[ "position" ].array;
  3611. if ( positions ) {
  3612. var bb = this.boundingBox;
  3613. var x, y, z;
  3614. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3615. x = positions[ i ];
  3616. y = positions[ i + 1 ];
  3617. z = positions[ i + 2 ];
  3618. // bounding box
  3619. if ( x < bb.min.x ) {
  3620. bb.min.x = x;
  3621. } else if ( x > bb.max.x ) {
  3622. bb.max.x = x;
  3623. }
  3624. if ( y < bb.min.y ) {
  3625. bb.min.y = y;
  3626. } else if ( y > bb.max.y ) {
  3627. bb.max.y = y;
  3628. }
  3629. if ( z < bb.min.z ) {
  3630. bb.min.z = z;
  3631. } else if ( z > bb.max.z ) {
  3632. bb.max.z = z;
  3633. }
  3634. }
  3635. }
  3636. if ( positions === undefined || positions.length === 0 ) {
  3637. this.boundingBox.min.set( 0, 0, 0 );
  3638. this.boundingBox.max.set( 0, 0, 0 );
  3639. }
  3640. },
  3641. computeBoundingSphere: function () {
  3642. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  3643. var positions = this.attributes[ "position" ].array;
  3644. if ( positions ) {
  3645. var radiusSq, maxRadiusSq = 0;
  3646. var x, y, z;
  3647. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3648. x = positions[ i ];
  3649. y = positions[ i + 1 ];
  3650. z = positions[ i + 2 ];
  3651. radiusSq = x * x + y * y + z * z;
  3652. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3653. }
  3654. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3655. }
  3656. },
  3657. computeVertexNormals: function () {
  3658. if ( this.attributes[ "position" ] ) {
  3659. var i, il;
  3660. var j, jl;
  3661. var nVertexElements = this.attributes[ "position" ].array.length;
  3662. if ( this.attributes[ "normal" ] === undefined ) {
  3663. this.attributes[ "normal" ] = {
  3664. itemSize: 3,
  3665. array: new Float32Array( nVertexElements ),
  3666. numItems: nVertexElements
  3667. };
  3668. } else {
  3669. // reset existing normals to zero
  3670. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  3671. this.attributes[ "normal" ].array[ i ] = 0;
  3672. }
  3673. }
  3674. var positions = this.attributes[ "position" ].array;
  3675. var normals = this.attributes[ "normal" ].array;
  3676. var vA, vB, vC, x, y, z,
  3677. pA = new THREE.Vector3(),
  3678. pB = new THREE.Vector3(),
  3679. pC = new THREE.Vector3(),
  3680. cb = new THREE.Vector3(),
  3681. ab = new THREE.Vector3();
  3682. // indexed elements
  3683. if ( this.attributes[ "index" ] ) {
  3684. var indices = this.attributes[ "index" ].array;
  3685. var offsets = this.offsets;
  3686. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3687. var start = offsets[ j ].start;
  3688. var count = offsets[ j ].count;
  3689. var index = offsets[ j ].index;
  3690. for ( i = start, il = start + count; i < il; i += 3 ) {
  3691. vA = index + indices[ i ];
  3692. vB = index + indices[ i + 1 ];
  3693. vC = index + indices[ i + 2 ];
  3694. x = positions[ vA * 3 ];
  3695. y = positions[ vA * 3 + 1 ];
  3696. z = positions[ vA * 3 + 2 ];
  3697. pA.set( x, y, z );
  3698. x = positions[ vB * 3 ];
  3699. y = positions[ vB * 3 + 1 ];
  3700. z = positions[ vB * 3 + 2 ];
  3701. pB.set( x, y, z );
  3702. x = positions[ vC * 3 ];
  3703. y = positions[ vC * 3 + 1 ];
  3704. z = positions[ vC * 3 + 2 ];
  3705. pC.set( x, y, z );
  3706. cb.sub( pC, pB );
  3707. ab.sub( pA, pB );
  3708. cb.crossSelf( ab );
  3709. normals[ vA * 3 ] += cb.x;
  3710. normals[ vA * 3 + 1 ] += cb.y;
  3711. normals[ vA * 3 + 2 ] += cb.z;
  3712. normals[ vB * 3 ] += cb.x;
  3713. normals[ vB * 3 + 1 ] += cb.y;
  3714. normals[ vB * 3 + 2 ] += cb.z;
  3715. normals[ vC * 3 ] += cb.x;
  3716. normals[ vC * 3 + 1 ] += cb.y;
  3717. normals[ vC * 3 + 2 ] += cb.z;
  3718. }
  3719. }
  3720. // non-indexed elements (unconnected triangle soup)
  3721. } else {
  3722. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  3723. x = positions[ i ];
  3724. y = positions[ i + 1 ];
  3725. z = positions[ i + 2 ];
  3726. pA.set( x, y, z );
  3727. x = positions[ i + 3 ];
  3728. y = positions[ i + 4 ];
  3729. z = positions[ i + 5 ];
  3730. pB.set( x, y, z );
  3731. x = positions[ i + 6 ];
  3732. y = positions[ i + 7 ];
  3733. z = positions[ i + 8 ];
  3734. pC.set( x, y, z );
  3735. cb.sub( pC, pB );
  3736. ab.sub( pA, pB );
  3737. cb.crossSelf( ab );
  3738. normals[ i ] = cb.x;
  3739. normals[ i + 1 ] = cb.y;
  3740. normals[ i + 2 ] = cb.z;
  3741. normals[ i + 3 ] = cb.x;
  3742. normals[ i + 4 ] = cb.y;
  3743. normals[ i + 5 ] = cb.z;
  3744. normals[ i + 6 ] = cb.x;
  3745. normals[ i + 7 ] = cb.y;
  3746. normals[ i + 8 ] = cb.z;
  3747. }
  3748. }
  3749. this.normalizeNormals();
  3750. this.normalsNeedUpdate = true;
  3751. }
  3752. },
  3753. normalizeNormals: function () {
  3754. var normals = this.attributes[ "normal" ].array;
  3755. var x, y, z, n;
  3756. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  3757. x = normals[ i ];
  3758. y = normals[ i + 1 ];
  3759. z = normals[ i + 2 ];
  3760. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  3761. normals[ i ] *= n;
  3762. normals[ i + 1 ] *= n;
  3763. normals[ i + 2 ] *= n;
  3764. }
  3765. },
  3766. computeTangents: function () {
  3767. // based on http://www.terathon.com/code/tangent.html
  3768. // (per vertex tangents)
  3769. if ( this.attributes[ "index" ] === undefined ||
  3770. this.attributes[ "position" ] === undefined ||
  3771. this.attributes[ "normal" ] === undefined ||
  3772. this.attributes[ "uv" ] === undefined ) {
  3773. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  3774. return;
  3775. }
  3776. var indices = this.attributes[ "index" ].array;
  3777. var positions = this.attributes[ "position" ].array;
  3778. var normals = this.attributes[ "normal" ].array;
  3779. var uvs = this.attributes[ "uv" ].array;
  3780. var nVertices = positions.length / 3;
  3781. if ( this.attributes[ "tangent" ] === undefined ) {
  3782. var nTangentElements = 4 * nVertices;
  3783. this.attributes[ "tangent" ] = {
  3784. itemSize: 4,
  3785. array: new Float32Array( nTangentElements ),
  3786. numItems: nTangentElements
  3787. };
  3788. }
  3789. var tangents = this.attributes[ "tangent" ].array;
  3790. var tan1 = [], tan2 = [];
  3791. for ( var k = 0; k < nVertices; k ++ ) {
  3792. tan1[ k ] = new THREE.Vector3();
  3793. tan2[ k ] = new THREE.Vector3();
  3794. }
  3795. var xA, yA, zA,
  3796. xB, yB, zB,
  3797. xC, yC, zC,
  3798. uA, vA,
  3799. uB, vB,
  3800. uC, vC,
  3801. x1, x2, y1, y2, z1, z2,
  3802. s1, s2, t1, t2, r;
  3803. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  3804. function handleTriangle( a, b, c ) {
  3805. xA = positions[ a * 3 ];
  3806. yA = positions[ a * 3 + 1 ];
  3807. zA = positions[ a * 3 + 2 ];
  3808. xB = positions[ b * 3 ];
  3809. yB = positions[ b * 3 + 1 ];
  3810. zB = positions[ b * 3 + 2 ];
  3811. xC = positions[ c * 3 ];
  3812. yC = positions[ c * 3 + 1 ];
  3813. zC = positions[ c * 3 + 2 ];
  3814. uA = uvs[ a * 2 ];
  3815. vA = uvs[ a * 2 + 1 ];
  3816. uB = uvs[ b * 2 ];
  3817. vB = uvs[ b * 2 + 1 ];
  3818. uC = uvs[ c * 2 ];
  3819. vC = uvs[ c * 2 + 1 ];
  3820. x1 = xB - xA;
  3821. x2 = xC - xA;
  3822. y1 = yB - yA;
  3823. y2 = yC - yA;
  3824. z1 = zB - zA;
  3825. z2 = zC - zA;
  3826. s1 = uB - uA;
  3827. s2 = uC - uA;
  3828. t1 = vB - vA;
  3829. t2 = vC - vA;
  3830. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3831. sdir.set(
  3832. ( t2 * x1 - t1 * x2 ) * r,
  3833. ( t2 * y1 - t1 * y2 ) * r,
  3834. ( t2 * z1 - t1 * z2 ) * r
  3835. );
  3836. tdir.set(
  3837. ( s1 * x2 - s2 * x1 ) * r,
  3838. ( s1 * y2 - s2 * y1 ) * r,
  3839. ( s1 * z2 - s2 * z1 ) * r
  3840. );
  3841. tan1[ a ].addSelf( sdir );
  3842. tan1[ b ].addSelf( sdir );
  3843. tan1[ c ].addSelf( sdir );
  3844. tan2[ a ].addSelf( tdir );
  3845. tan2[ b ].addSelf( tdir );
  3846. tan2[ c ].addSelf( tdir );
  3847. }
  3848. var i, il;
  3849. var j, jl;
  3850. var iA, iB, iC;
  3851. var offsets = this.offsets;
  3852. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3853. var start = offsets[ j ].start;
  3854. var count = offsets[ j ].count;
  3855. var index = offsets[ j ].index;
  3856. for ( i = start, il = start + count; i < il; i += 3 ) {
  3857. iA = index + indices[ i ];
  3858. iB = index + indices[ i + 1 ];
  3859. iC = index + indices[ i + 2 ];
  3860. handleTriangle( iA, iB, iC );
  3861. }
  3862. }
  3863. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  3864. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  3865. var w, t, test;
  3866. var nx, ny, nz;
  3867. function handleVertex( v ) {
  3868. n.x = normals[ v * 3 ];
  3869. n.y = normals[ v * 3 + 1 ];
  3870. n.z = normals[ v * 3 + 2 ];
  3871. n2.copy( n );
  3872. t = tan1[ v ];
  3873. // Gram-Schmidt orthogonalize
  3874. tmp.copy( t );
  3875. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3876. // Calculate handedness
  3877. tmp2.cross( n2, t );
  3878. test = tmp2.dot( tan2[ v ] );
  3879. w = ( test < 0.0 ) ? -1.0 : 1.0;
  3880. tangents[ v * 4 ] = tmp.x;
  3881. tangents[ v * 4 + 1 ] = tmp.y;
  3882. tangents[ v * 4 + 2 ] = tmp.z;
  3883. tangents[ v * 4 + 3 ] = w;
  3884. }
  3885. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3886. var start = offsets[ j ].start;
  3887. var count = offsets[ j ].count;
  3888. var index = offsets[ j ].index;
  3889. for ( i = start, il = start + count; i < il; i += 3 ) {
  3890. iA = index + indices[ i ];
  3891. iB = index + indices[ i + 1 ];
  3892. iC = index + indices[ i + 2 ];
  3893. handleVertex( iA );
  3894. handleVertex( iB );
  3895. handleVertex( iC );
  3896. }
  3897. }
  3898. this.hasTangents = true;
  3899. this.tangentsNeedUpdate = true;
  3900. },
  3901. deallocate: function () {
  3902. var index = THREE.GeometryLibrary.indexOf( this );
  3903. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  3904. }
  3905. };
  3906. /**
  3907. * Spline from Tween.js, slightly optimized (and trashed)
  3908. * http://sole.github.com/tween.js/examples/05_spline.html
  3909. *
  3910. * @author mrdoob / http://mrdoob.com/
  3911. * @author alteredq / http://alteredqualia.com/
  3912. */
  3913. THREE.Spline = function ( points ) {
  3914. this.points = points;
  3915. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3916. point, intPoint, weight, w2, w3,
  3917. pa, pb, pc, pd;
  3918. this.initFromArray = function( a ) {
  3919. this.points = [];
  3920. for ( var i = 0; i < a.length; i++ ) {
  3921. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3922. }
  3923. };
  3924. this.getPoint = function ( k ) {
  3925. point = ( this.points.length - 1 ) * k;
  3926. intPoint = Math.floor( point );
  3927. weight = point - intPoint;
  3928. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3929. c[ 1 ] = intPoint;
  3930. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3931. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3932. pa = this.points[ c[ 0 ] ];
  3933. pb = this.points[ c[ 1 ] ];
  3934. pc = this.points[ c[ 2 ] ];
  3935. pd = this.points[ c[ 3 ] ];
  3936. w2 = weight * weight;
  3937. w3 = weight * w2;
  3938. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3939. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3940. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3941. return v3;
  3942. };
  3943. this.getControlPointsArray = function () {
  3944. var i, p, l = this.points.length,
  3945. coords = [];
  3946. for ( i = 0; i < l; i ++ ) {
  3947. p = this.points[ i ];
  3948. coords[ i ] = [ p.x, p.y, p.z ];
  3949. }
  3950. return coords;
  3951. };
  3952. // approximate length by summing linear segments
  3953. this.getLength = function ( nSubDivisions ) {
  3954. var i, index, nSamples, position,
  3955. point = 0, intPoint = 0, oldIntPoint = 0,
  3956. oldPosition = new THREE.Vector3(),
  3957. tmpVec = new THREE.Vector3(),
  3958. chunkLengths = [],
  3959. totalLength = 0;
  3960. // first point has 0 length
  3961. chunkLengths[ 0 ] = 0;
  3962. if ( !nSubDivisions ) nSubDivisions = 100;
  3963. nSamples = this.points.length * nSubDivisions;
  3964. oldPosition.copy( this.points[ 0 ] );
  3965. for ( i = 1; i < nSamples; i ++ ) {
  3966. index = i / nSamples;
  3967. position = this.getPoint( index );
  3968. tmpVec.copy( position );
  3969. totalLength += tmpVec.distanceTo( oldPosition );
  3970. oldPosition.copy( position );
  3971. point = ( this.points.length - 1 ) * index;
  3972. intPoint = Math.floor( point );
  3973. if ( intPoint != oldIntPoint ) {
  3974. chunkLengths[ intPoint ] = totalLength;
  3975. oldIntPoint = intPoint;
  3976. }
  3977. }
  3978. // last point ends with total length
  3979. chunkLengths[ chunkLengths.length ] = totalLength;
  3980. return { chunks: chunkLengths, total: totalLength };
  3981. };
  3982. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3983. var i, j,
  3984. index, indexCurrent, indexNext,
  3985. linearDistance, realDistance,
  3986. sampling, position,
  3987. newpoints = [],
  3988. tmpVec = new THREE.Vector3(),
  3989. sl = this.getLength();
  3990. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3991. for ( i = 1; i < this.points.length; i++ ) {
  3992. //tmpVec.copy( this.points[ i - 1 ] );
  3993. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3994. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3995. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3996. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3997. indexNext = i / ( this.points.length - 1 );
  3998. for ( j = 1; j < sampling - 1; j++ ) {
  3999. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  4000. position = this.getPoint( index );
  4001. newpoints.push( tmpVec.copy( position ).clone() );
  4002. }
  4003. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  4004. }
  4005. this.points = newpoints;
  4006. };
  4007. // Catmull-Rom
  4008. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  4009. var v0 = ( p2 - p0 ) * 0.5,
  4010. v1 = ( p3 - p1 ) * 0.5;
  4011. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  4012. };
  4013. };
  4014. /**
  4015. * @author mrdoob / http://mrdoob.com/
  4016. * @author mikael emtinger / http://gomo.se/
  4017. */
  4018. THREE.Camera = function () {
  4019. THREE.Object3D.call( this );
  4020. this.matrixWorldInverse = new THREE.Matrix4();
  4021. this.projectionMatrix = new THREE.Matrix4();
  4022. this.projectionMatrixInverse = new THREE.Matrix4();
  4023. };
  4024. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  4025. THREE.Camera.prototype.lookAt = function ( vector ) {
  4026. // TODO: Add hierarchy support.
  4027. this.matrix.lookAt( this.position, vector, this.up );
  4028. if ( this.rotationAutoUpdate === true ) {
  4029. if ( this.useQuaternion === false ) {
  4030. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  4031. } else {
  4032. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  4033. }
  4034. }
  4035. };
  4036. /**
  4037. * @author alteredq / http://alteredqualia.com/
  4038. */
  4039. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  4040. THREE.Camera.call( this );
  4041. this.left = left;
  4042. this.right = right;
  4043. this.top = top;
  4044. this.bottom = bottom;
  4045. this.near = ( near !== undefined ) ? near : 0.1;
  4046. this.far = ( far !== undefined ) ? far : 2000;
  4047. this.updateProjectionMatrix();
  4048. };
  4049. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  4050. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  4051. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  4052. };
  4053. /**
  4054. * @author mrdoob / http://mrdoob.com/
  4055. * @author greggman / http://games.greggman.com/
  4056. * @author zz85 / http://www.lab4games.net/zz85/blog
  4057. */
  4058. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  4059. THREE.Camera.call( this );
  4060. this.fov = fov !== undefined ? fov : 50;
  4061. this.aspect = aspect !== undefined ? aspect : 1;
  4062. this.near = near !== undefined ? near : 0.1;
  4063. this.far = far !== undefined ? far : 2000;
  4064. this.updateProjectionMatrix();
  4065. };
  4066. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  4067. /**
  4068. * Uses Focal Length (in mm) to estimate and set FOV
  4069. * 35mm (fullframe) camera is used if frame size is not specified;
  4070. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  4071. */
  4072. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  4073. if ( frameHeight === undefined ) frameHeight = 24;
  4074. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  4075. this.updateProjectionMatrix();
  4076. }
  4077. /**
  4078. * Sets an offset in a larger frustum. This is useful for multi-window or
  4079. * multi-monitor/multi-machine setups.
  4080. *
  4081. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  4082. * the monitors are in grid like this
  4083. *
  4084. * +---+---+---+
  4085. * | A | B | C |
  4086. * +---+---+---+
  4087. * | D | E | F |
  4088. * +---+---+---+
  4089. *
  4090. * then for each monitor you would call it like this
  4091. *
  4092. * var w = 1920;
  4093. * var h = 1080;
  4094. * var fullWidth = w * 3;
  4095. * var fullHeight = h * 2;
  4096. *
  4097. * --A--
  4098. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  4099. * --B--
  4100. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  4101. * --C--
  4102. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  4103. * --D--
  4104. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  4105. * --E--
  4106. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  4107. * --F--
  4108. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  4109. *
  4110. * Note there is no reason monitors have to be the same size or in a grid.
  4111. */
  4112. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  4113. this.fullWidth = fullWidth;
  4114. this.fullHeight = fullHeight;
  4115. this.x = x;
  4116. this.y = y;
  4117. this.width = width;
  4118. this.height = height;
  4119. this.updateProjectionMatrix();
  4120. };
  4121. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  4122. if ( this.fullWidth ) {
  4123. var aspect = this.fullWidth / this.fullHeight;
  4124. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  4125. var bottom = -top;
  4126. var left = aspect * bottom;
  4127. var right = aspect * top;
  4128. var width = Math.abs( right - left );
  4129. var height = Math.abs( top - bottom );
  4130. this.projectionMatrix.makeFrustum(
  4131. left + this.x * width / this.fullWidth,
  4132. left + ( this.x + this.width ) * width / this.fullWidth,
  4133. top - ( this.y + this.height ) * height / this.fullHeight,
  4134. top - this.y * height / this.fullHeight,
  4135. this.near,
  4136. this.far
  4137. );
  4138. } else {
  4139. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  4140. }
  4141. };
  4142. /**
  4143. * @author mrdoob / http://mrdoob.com/
  4144. * @author alteredq / http://alteredqualia.com/
  4145. */
  4146. THREE.Light = function ( hex ) {
  4147. THREE.Object3D.call( this );
  4148. this.color = new THREE.Color( hex );
  4149. };
  4150. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  4151. /**
  4152. * @author mrdoob / http://mrdoob.com/
  4153. */
  4154. THREE.AmbientLight = function ( hex ) {
  4155. THREE.Light.call( this, hex );
  4156. };
  4157. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  4158. /**
  4159. * @author mrdoob / http://mrdoob.com/
  4160. * @author alteredq / http://alteredqualia.com/
  4161. */
  4162. THREE.DirectionalLight = function ( hex, intensity ) {
  4163. THREE.Light.call( this, hex );
  4164. this.position = new THREE.Vector3( 0, 1, 0 );
  4165. this.target = new THREE.Object3D();
  4166. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4167. this.castShadow = false;
  4168. this.onlyShadow = false;
  4169. //
  4170. this.shadowCameraNear = 50;
  4171. this.shadowCameraFar = 5000;
  4172. this.shadowCameraLeft = -500;
  4173. this.shadowCameraRight = 500;
  4174. this.shadowCameraTop = 500;
  4175. this.shadowCameraBottom = -500;
  4176. this.shadowCameraVisible = false;
  4177. this.shadowBias = 0;
  4178. this.shadowDarkness = 0.5;
  4179. this.shadowMapWidth = 512;
  4180. this.shadowMapHeight = 512;
  4181. //
  4182. this.shadowCascade = false;
  4183. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  4184. this.shadowCascadeCount = 2;
  4185. this.shadowCascadeBias = [ 0, 0, 0 ];
  4186. this.shadowCascadeWidth = [ 512, 512, 512 ];
  4187. this.shadowCascadeHeight = [ 512, 512, 512 ];
  4188. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  4189. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  4190. this.shadowCascadeArray = [];
  4191. //
  4192. this.shadowMap = null;
  4193. this.shadowMapSize = null;
  4194. this.shadowCamera = null;
  4195. this.shadowMatrix = null;
  4196. };
  4197. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  4198. /**
  4199. * @author alteredq / http://alteredqualia.com/
  4200. */
  4201. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  4202. THREE.Light.call( this, skyColorHex );
  4203. this.groundColor = new THREE.Color( groundColorHex );
  4204. this.position = new THREE.Vector3( 0, 100, 0 );
  4205. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4206. };
  4207. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  4208. /**
  4209. * @author mrdoob / http://mrdoob.com/
  4210. */
  4211. THREE.PointLight = function ( hex, intensity, distance ) {
  4212. THREE.Light.call( this, hex );
  4213. this.position = new THREE.Vector3( 0, 0, 0 );
  4214. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4215. this.distance = ( distance !== undefined ) ? distance : 0;
  4216. };
  4217. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  4218. /**
  4219. * @author alteredq / http://alteredqualia.com/
  4220. */
  4221. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  4222. THREE.Light.call( this, hex );
  4223. this.position = new THREE.Vector3( 0, 1, 0 );
  4224. this.target = new THREE.Object3D();
  4225. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4226. this.distance = ( distance !== undefined ) ? distance : 0;
  4227. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  4228. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  4229. this.castShadow = false;
  4230. this.onlyShadow = false;
  4231. //
  4232. this.shadowCameraNear = 50;
  4233. this.shadowCameraFar = 5000;
  4234. this.shadowCameraFov = 50;
  4235. this.shadowCameraVisible = false;
  4236. this.shadowBias = 0;
  4237. this.shadowDarkness = 0.5;
  4238. this.shadowMapWidth = 512;
  4239. this.shadowMapHeight = 512;
  4240. //
  4241. this.shadowMap = null;
  4242. this.shadowMapSize = null;
  4243. this.shadowCamera = null;
  4244. this.shadowMatrix = null;
  4245. };
  4246. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  4247. /**
  4248. * @author alteredq / http://alteredqualia.com/
  4249. */
  4250. THREE.Loader = function ( showStatus ) {
  4251. this.showStatus = showStatus;
  4252. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  4253. this.onLoadStart = function () {};
  4254. this.onLoadProgress = function () {};
  4255. this.onLoadComplete = function () {};
  4256. };
  4257. THREE.Loader.prototype = {
  4258. constructor: THREE.Loader,
  4259. crossOrigin: 'anonymous',
  4260. addStatusElement: function () {
  4261. var e = document.createElement( "div" );
  4262. e.style.position = "absolute";
  4263. e.style.right = "0px";
  4264. e.style.top = "0px";
  4265. e.style.fontSize = "0.8em";
  4266. e.style.textAlign = "left";
  4267. e.style.background = "rgba(0,0,0,0.25)";
  4268. e.style.color = "#fff";
  4269. e.style.width = "120px";
  4270. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  4271. e.style.zIndex = 1000;
  4272. e.innerHTML = "Loading ...";
  4273. return e;
  4274. },
  4275. updateProgress: function ( progress ) {
  4276. var message = "Loaded ";
  4277. if ( progress.total ) {
  4278. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  4279. } else {
  4280. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  4281. }
  4282. this.statusDomElement.innerHTML = message;
  4283. },
  4284. extractUrlBase: function ( url ) {
  4285. var parts = url.split( '/' );
  4286. parts.pop();
  4287. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  4288. },
  4289. initMaterials: function ( materials, texturePath ) {
  4290. var array = [];
  4291. for ( var i = 0; i < materials.length; ++ i ) {
  4292. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  4293. }
  4294. return array;
  4295. },
  4296. needsTangents: function ( materials ) {
  4297. for( var i = 0, il = materials.length; i < il; i ++ ) {
  4298. var m = materials[ i ];
  4299. if ( m instanceof THREE.ShaderMaterial ) return true;
  4300. }
  4301. return false;
  4302. },
  4303. createMaterial: function ( m, texturePath ) {
  4304. var _this = this;
  4305. function is_pow2( n ) {
  4306. var l = Math.log( n ) / Math.LN2;
  4307. return Math.floor( l ) == l;
  4308. }
  4309. function nearest_pow2( n ) {
  4310. var l = Math.log( n ) / Math.LN2;
  4311. return Math.pow( 2, Math.round( l ) );
  4312. }
  4313. function load_image( where, url ) {
  4314. var image = new Image();
  4315. image.onload = function () {
  4316. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  4317. var width = nearest_pow2( this.width );
  4318. var height = nearest_pow2( this.height );
  4319. where.image.width = width;
  4320. where.image.height = height;
  4321. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  4322. } else {
  4323. where.image = this;
  4324. }
  4325. where.needsUpdate = true;
  4326. };
  4327. image.crossOrigin = _this.crossOrigin;
  4328. image.src = url;
  4329. }
  4330. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  4331. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  4332. var fullPath = texturePath + "/" + sourceFile;
  4333. if ( isCompressed ) {
  4334. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  4335. where[ name ] = texture;
  4336. } else {
  4337. var texture = document.createElement( 'canvas' );
  4338. where[ name ] = new THREE.Texture( texture );
  4339. }
  4340. where[ name ].sourceFile = sourceFile;
  4341. if( repeat ) {
  4342. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4343. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4344. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4345. }
  4346. if ( offset ) {
  4347. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4348. }
  4349. if ( wrap ) {
  4350. var wrapMap = {
  4351. "repeat": THREE.RepeatWrapping,
  4352. "mirror": THREE.MirroredRepeatWrapping
  4353. }
  4354. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4355. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4356. }
  4357. if ( anisotropy ) {
  4358. where[ name ].anisotropy = anisotropy;
  4359. }
  4360. if ( ! isCompressed ) {
  4361. load_image( where[ name ], fullPath );
  4362. }
  4363. }
  4364. function rgb2hex( rgb ) {
  4365. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4366. }
  4367. // defaults
  4368. var mtype = "MeshLambertMaterial";
  4369. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4370. // parameters from model file
  4371. if ( m.shading ) {
  4372. var shading = m.shading.toLowerCase();
  4373. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4374. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4375. }
  4376. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4377. mpars.blending = THREE[ m.blending ];
  4378. }
  4379. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4380. mpars.transparent = m.transparent;
  4381. }
  4382. if ( m.depthTest !== undefined ) {
  4383. mpars.depthTest = m.depthTest;
  4384. }
  4385. if ( m.depthWrite !== undefined ) {
  4386. mpars.depthWrite = m.depthWrite;
  4387. }
  4388. if ( m.visible !== undefined ) {
  4389. mpars.visible = m.visible;
  4390. }
  4391. if ( m.flipSided !== undefined ) {
  4392. mpars.side = THREE.BackSide;
  4393. }
  4394. if ( m.doubleSided !== undefined ) {
  4395. mpars.side = THREE.DoubleSide;
  4396. }
  4397. if ( m.wireframe !== undefined ) {
  4398. mpars.wireframe = m.wireframe;
  4399. }
  4400. if ( m.vertexColors !== undefined ) {
  4401. if ( m.vertexColors === "face" ) {
  4402. mpars.vertexColors = THREE.FaceColors;
  4403. } else if ( m.vertexColors ) {
  4404. mpars.vertexColors = THREE.VertexColors;
  4405. }
  4406. }
  4407. // colors
  4408. if ( m.colorDiffuse ) {
  4409. mpars.color = rgb2hex( m.colorDiffuse );
  4410. } else if ( m.DbgColor ) {
  4411. mpars.color = m.DbgColor;
  4412. }
  4413. if ( m.colorSpecular ) {
  4414. mpars.specular = rgb2hex( m.colorSpecular );
  4415. }
  4416. if ( m.colorAmbient ) {
  4417. mpars.ambient = rgb2hex( m.colorAmbient );
  4418. }
  4419. // modifiers
  4420. if ( m.transparency ) {
  4421. mpars.opacity = m.transparency;
  4422. }
  4423. if ( m.specularCoef ) {
  4424. mpars.shininess = m.specularCoef;
  4425. }
  4426. // textures
  4427. if ( m.mapDiffuse && texturePath ) {
  4428. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  4429. }
  4430. if ( m.mapLight && texturePath ) {
  4431. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  4432. }
  4433. if ( m.mapBump && texturePath ) {
  4434. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  4435. }
  4436. if ( m.mapNormal && texturePath ) {
  4437. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  4438. }
  4439. if ( m.mapSpecular && texturePath ) {
  4440. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  4441. }
  4442. //
  4443. if ( m.mapBumpScale ) {
  4444. mpars.bumpScale = m.mapBumpScale;
  4445. }
  4446. // special case for normal mapped material
  4447. if ( m.mapNormal ) {
  4448. var shader = THREE.ShaderUtils.lib[ "normal" ];
  4449. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  4450. uniforms[ "tNormal" ].value = mpars.normalMap;
  4451. if ( m.mapNormalFactor ) {
  4452. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  4453. }
  4454. if ( mpars.map ) {
  4455. uniforms[ "tDiffuse" ].value = mpars.map;
  4456. uniforms[ "enableDiffuse" ].value = true;
  4457. }
  4458. if ( mpars.specularMap ) {
  4459. uniforms[ "tSpecular" ].value = mpars.specularMap;
  4460. uniforms[ "enableSpecular" ].value = true;
  4461. }
  4462. if ( mpars.lightMap ) {
  4463. uniforms[ "tAO" ].value = mpars.lightMap;
  4464. uniforms[ "enableAO" ].value = true;
  4465. }
  4466. // for the moment don't handle displacement texture
  4467. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  4468. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  4469. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  4470. uniforms[ "uShininess" ].value = mpars.shininess;
  4471. if ( mpars.opacity !== undefined ) {
  4472. uniforms[ "uOpacity" ].value = mpars.opacity;
  4473. }
  4474. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  4475. var material = new THREE.ShaderMaterial( parameters );
  4476. } else {
  4477. var material = new THREE[ mtype ]( mpars );
  4478. }
  4479. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  4480. return material;
  4481. }
  4482. };
  4483. /**
  4484. * @author alteredq / http://alteredqualia.com/
  4485. */
  4486. THREE.BinaryLoader = function ( showStatus ) {
  4487. THREE.Loader.call( this, showStatus );
  4488. };
  4489. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  4490. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  4491. // - binary models consist of two files: JS and BIN
  4492. // - parameters
  4493. // - url (required)
  4494. // - callback (required)
  4495. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  4496. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  4497. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  4498. // todo: unify load API to for easier SceneLoader use
  4499. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  4500. binaryPath = binaryPath && ( typeof binaryPath === "string" ) ? binaryPath : this.extractUrlBase( url );
  4501. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  4502. this.onLoadStart();
  4503. // #1 load JS part via web worker
  4504. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  4505. };
  4506. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  4507. var xhr = new XMLHttpRequest();
  4508. xhr.onreadystatechange = function () {
  4509. if ( xhr.readyState == 4 ) {
  4510. if ( xhr.status == 200 || xhr.status == 0 ) {
  4511. var json = JSON.parse( xhr.responseText );
  4512. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  4513. } else {
  4514. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4515. }
  4516. }
  4517. };
  4518. xhr.open( "GET", url, true );
  4519. xhr.send( null );
  4520. };
  4521. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  4522. var xhr = new XMLHttpRequest(),
  4523. url = binaryPath + "/" + json.buffers;
  4524. var length = 0;
  4525. xhr.onreadystatechange = function () {
  4526. if ( xhr.readyState == 4 ) {
  4527. if ( xhr.status == 200 || xhr.status == 0 ) {
  4528. var buffer = xhr.response;
  4529. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  4530. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  4531. } else {
  4532. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4533. }
  4534. } else if ( xhr.readyState == 3 ) {
  4535. if ( callbackProgress ) {
  4536. if ( length == 0 ) {
  4537. length = xhr.getResponseHeader( "Content-Length" );
  4538. }
  4539. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4540. }
  4541. } else if ( xhr.readyState == 2 ) {
  4542. length = xhr.getResponseHeader( "Content-Length" );
  4543. }
  4544. };
  4545. xhr.open( "GET", url, true );
  4546. xhr.responseType = "arraybuffer";
  4547. xhr.send( null );
  4548. };
  4549. // Binary AJAX parser
  4550. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, jsonMaterials ) {
  4551. var Model = function ( texturePath ) {
  4552. var scope = this,
  4553. currentOffset = 0,
  4554. md,
  4555. normals = [],
  4556. uvs = [],
  4557. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  4558. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  4559. tri_size, quad_size,
  4560. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  4561. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  4562. THREE.Geometry.call( this );
  4563. md = parseMetaData( data, currentOffset );
  4564. currentOffset += md.header_bytes;
  4565. /*
  4566. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4567. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  4568. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4569. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4570. */
  4571. // buffers sizes
  4572. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  4573. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  4574. len_tri_flat = md.ntri_flat * ( tri_size );
  4575. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  4576. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  4577. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  4578. len_quad_flat = md.nquad_flat * ( quad_size );
  4579. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  4580. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  4581. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  4582. // read buffers
  4583. currentOffset += init_vertices( currentOffset );
  4584. currentOffset += init_normals( currentOffset );
  4585. currentOffset += handlePadding( md.nnormals * 3 );
  4586. currentOffset += init_uvs( currentOffset );
  4587. start_tri_flat = currentOffset;
  4588. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  4589. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  4590. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  4591. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  4592. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  4593. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  4594. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  4595. // have to first process faces with uvs
  4596. // so that face and uv indices match
  4597. init_triangles_flat_uv( start_tri_flat_uv );
  4598. init_triangles_smooth_uv( start_tri_smooth_uv );
  4599. init_quads_flat_uv( start_quad_flat_uv );
  4600. init_quads_smooth_uv( start_quad_smooth_uv );
  4601. // now we can process untextured faces
  4602. init_triangles_flat( start_tri_flat );
  4603. init_triangles_smooth( start_tri_smooth );
  4604. init_quads_flat( start_quad_flat );
  4605. init_quads_smooth( start_quad_smooth );
  4606. this.computeCentroids();
  4607. this.computeFaceNormals();
  4608. function handlePadding( n ) {
  4609. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  4610. };
  4611. function parseMetaData( data, offset ) {
  4612. var metaData = {
  4613. 'signature' :parseString( data, offset, 12 ),
  4614. 'header_bytes' :parseUChar8( data, offset + 12 ),
  4615. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  4616. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  4617. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  4618. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  4619. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  4620. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  4621. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  4622. 'nvertices' :parseUInt32( data, offset + 20 ),
  4623. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  4624. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  4625. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  4626. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  4627. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  4628. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  4629. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  4630. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  4631. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  4632. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  4633. };
  4634. /*
  4635. console.log( "signature: " + metaData.signature );
  4636. console.log( "header_bytes: " + metaData.header_bytes );
  4637. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  4638. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  4639. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  4640. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  4641. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  4642. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  4643. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  4644. console.log( "nvertices: " + metaData.nvertices );
  4645. console.log( "nnormals: " + metaData.nnormals );
  4646. console.log( "nuvs: " + metaData.nuvs );
  4647. console.log( "ntri_flat: " + metaData.ntri_flat );
  4648. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  4649. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  4650. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  4651. console.log( "nquad_flat: " + metaData.nquad_flat );
  4652. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  4653. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  4654. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  4655. var total = metaData.header_bytes
  4656. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  4657. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  4658. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  4659. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  4660. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  4661. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  4662. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  4663. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  4664. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  4665. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  4666. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  4667. console.log( "total bytes: " + total );
  4668. */
  4669. return metaData;
  4670. };
  4671. function parseString( data, offset, length ) {
  4672. var charArray = new Uint8Array( data, offset, length );
  4673. var text = "";
  4674. for ( var i = 0; i < length; i ++ ) {
  4675. text += String.fromCharCode( charArray[ offset + i ] );
  4676. }
  4677. return text;
  4678. };
  4679. function parseUChar8( data, offset ) {
  4680. var charArray = new Uint8Array( data, offset, 1 );
  4681. return charArray[ 0 ];
  4682. };
  4683. function parseUInt32( data, offset ) {
  4684. var intArray = new Uint32Array( data, offset, 1 );
  4685. return intArray[ 0 ];
  4686. };
  4687. function init_vertices( start ) {
  4688. var nElements = md.nvertices;
  4689. var coordArray = new Float32Array( data, start, nElements * 3 );
  4690. var i, x, y, z;
  4691. for( i = 0; i < nElements; i ++ ) {
  4692. x = coordArray[ i * 3 ];
  4693. y = coordArray[ i * 3 + 1 ];
  4694. z = coordArray[ i * 3 + 2 ];
  4695. vertex( scope, x, y, z );
  4696. }
  4697. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  4698. };
  4699. function init_normals( start ) {
  4700. var nElements = md.nnormals;
  4701. if ( nElements ) {
  4702. var normalArray = new Int8Array( data, start, nElements * 3 );
  4703. var i, x, y, z;
  4704. for( i = 0; i < nElements; i ++ ) {
  4705. x = normalArray[ i * 3 ];
  4706. y = normalArray[ i * 3 + 1 ];
  4707. z = normalArray[ i * 3 + 2 ];
  4708. normals.push( x/127, y/127, z/127 );
  4709. }
  4710. }
  4711. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  4712. };
  4713. function init_uvs( start ) {
  4714. var nElements = md.nuvs;
  4715. if ( nElements ) {
  4716. var uvArray = new Float32Array( data, start, nElements * 2 );
  4717. var i, u, v;
  4718. for( i = 0; i < nElements; i ++ ) {
  4719. u = uvArray[ i * 2 ];
  4720. v = uvArray[ i * 2 + 1 ];
  4721. uvs.push( u, v );
  4722. }
  4723. }
  4724. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  4725. };
  4726. function init_uvs3( nElements, offset ) {
  4727. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  4728. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  4729. for( i = 0; i < nElements; i ++ ) {
  4730. uva = uvIndexBuffer[ i * 3 ];
  4731. uvb = uvIndexBuffer[ i * 3 + 1 ];
  4732. uvc = uvIndexBuffer[ i * 3 + 2 ];
  4733. u1 = uvs[ uva*2 ];
  4734. v1 = uvs[ uva*2 + 1 ];
  4735. u2 = uvs[ uvb*2 ];
  4736. v2 = uvs[ uvb*2 + 1 ];
  4737. u3 = uvs[ uvc*2 ];
  4738. v3 = uvs[ uvc*2 + 1 ];
  4739. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  4740. }
  4741. };
  4742. function init_uvs4( nElements, offset ) {
  4743. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  4744. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  4745. for( i = 0; i < nElements; i ++ ) {
  4746. uva = uvIndexBuffer[ i * 4 ];
  4747. uvb = uvIndexBuffer[ i * 4 + 1 ];
  4748. uvc = uvIndexBuffer[ i * 4 + 2 ];
  4749. uvd = uvIndexBuffer[ i * 4 + 3 ];
  4750. u1 = uvs[ uva*2 ];
  4751. v1 = uvs[ uva*2 + 1 ];
  4752. u2 = uvs[ uvb*2 ];
  4753. v2 = uvs[ uvb*2 + 1 ];
  4754. u3 = uvs[ uvc*2 ];
  4755. v3 = uvs[ uvc*2 + 1 ];
  4756. u4 = uvs[ uvd*2 ];
  4757. v4 = uvs[ uvd*2 + 1 ];
  4758. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  4759. }
  4760. };
  4761. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  4762. var i, a, b, c, m;
  4763. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4764. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4765. for( i = 0; i < nElements; i ++ ) {
  4766. a = vertexIndexBuffer[ i * 3 ];
  4767. b = vertexIndexBuffer[ i * 3 + 1 ];
  4768. c = vertexIndexBuffer[ i * 3 + 2 ];
  4769. m = materialIndexBuffer[ i ];
  4770. f3( scope, a, b, c, m );
  4771. }
  4772. };
  4773. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  4774. var i, a, b, c, d, m;
  4775. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4776. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4777. for( i = 0; i < nElements; i ++ ) {
  4778. a = vertexIndexBuffer[ i * 4 ];
  4779. b = vertexIndexBuffer[ i * 4 + 1 ];
  4780. c = vertexIndexBuffer[ i * 4 + 2 ];
  4781. d = vertexIndexBuffer[ i * 4 + 3 ];
  4782. m = materialIndexBuffer[ i ];
  4783. f4( scope, a, b, c, d, m );
  4784. }
  4785. };
  4786. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4787. var i, a, b, c, m;
  4788. var na, nb, nc;
  4789. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4790. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  4791. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4792. for( i = 0; i < nElements; i ++ ) {
  4793. a = vertexIndexBuffer[ i * 3 ];
  4794. b = vertexIndexBuffer[ i * 3 + 1 ];
  4795. c = vertexIndexBuffer[ i * 3 + 2 ];
  4796. na = normalIndexBuffer[ i * 3 ];
  4797. nb = normalIndexBuffer[ i * 3 + 1 ];
  4798. nc = normalIndexBuffer[ i * 3 + 2 ];
  4799. m = materialIndexBuffer[ i ];
  4800. f3n( scope, normals, a, b, c, m, na, nb, nc );
  4801. }
  4802. };
  4803. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4804. var i, a, b, c, d, m;
  4805. var na, nb, nc, nd;
  4806. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4807. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  4808. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4809. for( i = 0; i < nElements; i ++ ) {
  4810. a = vertexIndexBuffer[ i * 4 ];
  4811. b = vertexIndexBuffer[ i * 4 + 1 ];
  4812. c = vertexIndexBuffer[ i * 4 + 2 ];
  4813. d = vertexIndexBuffer[ i * 4 + 3 ];
  4814. na = normalIndexBuffer[ i * 4 ];
  4815. nb = normalIndexBuffer[ i * 4 + 1 ];
  4816. nc = normalIndexBuffer[ i * 4 + 2 ];
  4817. nd = normalIndexBuffer[ i * 4 + 3 ];
  4818. m = materialIndexBuffer[ i ];
  4819. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  4820. }
  4821. };
  4822. function init_triangles_flat( start ) {
  4823. var nElements = md.ntri_flat;
  4824. if ( nElements ) {
  4825. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4826. init_faces3_flat( nElements, start, offsetMaterials );
  4827. }
  4828. };
  4829. function init_triangles_flat_uv( start ) {
  4830. var nElements = md.ntri_flat_uv;
  4831. if ( nElements ) {
  4832. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4833. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4834. init_faces3_flat( nElements, start, offsetMaterials );
  4835. init_uvs3( nElements, offsetUvs );
  4836. }
  4837. };
  4838. function init_triangles_smooth( start ) {
  4839. var nElements = md.ntri_smooth;
  4840. if ( nElements ) {
  4841. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4842. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4843. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4844. }
  4845. };
  4846. function init_triangles_smooth_uv( start ) {
  4847. var nElements = md.ntri_smooth_uv;
  4848. if ( nElements ) {
  4849. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4850. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4851. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4852. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4853. init_uvs3( nElements, offsetUvs );
  4854. }
  4855. };
  4856. function init_quads_flat( start ) {
  4857. var nElements = md.nquad_flat;
  4858. if ( nElements ) {
  4859. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4860. init_faces4_flat( nElements, start, offsetMaterials );
  4861. }
  4862. };
  4863. function init_quads_flat_uv( start ) {
  4864. var nElements = md.nquad_flat_uv;
  4865. if ( nElements ) {
  4866. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4867. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4868. init_faces4_flat( nElements, start, offsetMaterials );
  4869. init_uvs4( nElements, offsetUvs );
  4870. }
  4871. };
  4872. function init_quads_smooth( start ) {
  4873. var nElements = md.nquad_smooth;
  4874. if ( nElements ) {
  4875. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4876. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4877. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4878. }
  4879. };
  4880. function init_quads_smooth_uv( start ) {
  4881. var nElements = md.nquad_smooth_uv;
  4882. if ( nElements ) {
  4883. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4884. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4885. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4886. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4887. init_uvs4( nElements, offsetUvs );
  4888. }
  4889. };
  4890. };
  4891. function vertex ( scope, x, y, z ) {
  4892. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  4893. };
  4894. function f3 ( scope, a, b, c, mi ) {
  4895. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  4896. };
  4897. function f4 ( scope, a, b, c, d, mi ) {
  4898. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  4899. };
  4900. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  4901. var nax = normals[ na*3 ],
  4902. nay = normals[ na*3 + 1 ],
  4903. naz = normals[ na*3 + 2 ],
  4904. nbx = normals[ nb*3 ],
  4905. nby = normals[ nb*3 + 1 ],
  4906. nbz = normals[ nb*3 + 2 ],
  4907. ncx = normals[ nc*3 ],
  4908. ncy = normals[ nc*3 + 1 ],
  4909. ncz = normals[ nc*3 + 2 ];
  4910. scope.faces.push( new THREE.Face3( a, b, c,
  4911. [new THREE.Vector3( nax, nay, naz ),
  4912. new THREE.Vector3( nbx, nby, nbz ),
  4913. new THREE.Vector3( ncx, ncy, ncz )],
  4914. null,
  4915. mi ) );
  4916. };
  4917. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  4918. var nax = normals[ na*3 ],
  4919. nay = normals[ na*3 + 1 ],
  4920. naz = normals[ na*3 + 2 ],
  4921. nbx = normals[ nb*3 ],
  4922. nby = normals[ nb*3 + 1 ],
  4923. nbz = normals[ nb*3 + 2 ],
  4924. ncx = normals[ nc*3 ],
  4925. ncy = normals[ nc*3 + 1 ],
  4926. ncz = normals[ nc*3 + 2 ],
  4927. ndx = normals[ nd*3 ],
  4928. ndy = normals[ nd*3 + 1 ],
  4929. ndz = normals[ nd*3 + 2 ];
  4930. scope.faces.push( new THREE.Face4( a, b, c, d,
  4931. [new THREE.Vector3( nax, nay, naz ),
  4932. new THREE.Vector3( nbx, nby, nbz ),
  4933. new THREE.Vector3( ncx, ncy, ncz ),
  4934. new THREE.Vector3( ndx, ndy, ndz )],
  4935. null,
  4936. mi ) );
  4937. };
  4938. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  4939. where.push( [
  4940. new THREE.UV( u1, v1 ),
  4941. new THREE.UV( u2, v2 ),
  4942. new THREE.UV( u3, v3 )
  4943. ] );
  4944. };
  4945. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  4946. where.push( [
  4947. new THREE.UV( u1, v1 ),
  4948. new THREE.UV( u2, v2 ),
  4949. new THREE.UV( u3, v3 ),
  4950. new THREE.UV( u4, v4 )
  4951. ] );
  4952. };
  4953. Model.prototype = Object.create( THREE.Geometry.prototype );
  4954. var geometry = new Model( texturePath );
  4955. var materials = this.initMaterials( jsonMaterials, texturePath );
  4956. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  4957. callback( geometry, materials );
  4958. };
  4959. /**
  4960. * @author mrdoob / http://mrdoob.com/
  4961. */
  4962. THREE.ImageLoader = function () {
  4963. THREE.EventTarget.call( this );
  4964. this.crossOrigin = null;
  4965. };
  4966. THREE.ImageLoader.prototype = {
  4967. constructor: THREE.ImageLoader,
  4968. load: function ( url, image ) {
  4969. var scope = this;
  4970. if ( image === undefined ) image = new Image();
  4971. image.addEventListener( 'load', function () {
  4972. scope.dispatchEvent( { type: 'load', content: image } );
  4973. }, false );
  4974. image.addEventListener( 'error', function () {
  4975. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4976. }, false );
  4977. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  4978. image.src = url;
  4979. }
  4980. }
  4981. /**
  4982. * @author mrdoob / http://mrdoob.com/
  4983. * @author alteredq / http://alteredqualia.com/
  4984. */
  4985. THREE.JSONLoader = function ( showStatus ) {
  4986. THREE.Loader.call( this, showStatus );
  4987. this.withCredentials = false;
  4988. };
  4989. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  4990. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  4991. var scope = this;
  4992. // todo: unify load API to for easier SceneLoader use
  4993. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  4994. this.onLoadStart();
  4995. this.loadAjaxJSON( this, url, callback, texturePath );
  4996. };
  4997. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  4998. var xhr = new XMLHttpRequest();
  4999. var length = 0;
  5000. xhr.withCredentials = this.withCredentials;
  5001. xhr.onreadystatechange = function () {
  5002. if ( xhr.readyState === xhr.DONE ) {
  5003. if ( xhr.status === 200 || xhr.status === 0 ) {
  5004. if ( xhr.responseText ) {
  5005. var json = JSON.parse( xhr.responseText );
  5006. context.createModel( json, callback, texturePath );
  5007. } else {
  5008. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5009. }
  5010. // in context of more complex asset initialization
  5011. // do not block on single failed file
  5012. // maybe should go even one more level up
  5013. context.onLoadComplete();
  5014. } else {
  5015. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5016. }
  5017. } else if ( xhr.readyState === xhr.LOADING ) {
  5018. if ( callbackProgress ) {
  5019. if ( length === 0 ) {
  5020. length = xhr.getResponseHeader( "Content-Length" );
  5021. }
  5022. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5023. }
  5024. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5025. length = xhr.getResponseHeader( "Content-Length" );
  5026. }
  5027. };
  5028. xhr.open( "GET", url, true );
  5029. xhr.send( null );
  5030. };
  5031. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  5032. var scope = this,
  5033. geometry = new THREE.Geometry(),
  5034. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5035. parseModel( scale );
  5036. parseSkin();
  5037. parseMorphing( scale );
  5038. geometry.computeCentroids();
  5039. geometry.computeFaceNormals();
  5040. function parseModel( scale ) {
  5041. function isBitSet( value, position ) {
  5042. return value & ( 1 << position );
  5043. }
  5044. var i, j, fi,
  5045. offset, zLength, nVertices,
  5046. colorIndex, normalIndex, uvIndex, materialIndex,
  5047. type,
  5048. isQuad,
  5049. hasMaterial,
  5050. hasFaceUv, hasFaceVertexUv,
  5051. hasFaceNormal, hasFaceVertexNormal,
  5052. hasFaceColor, hasFaceVertexColor,
  5053. vertex, face, color, normal,
  5054. uvLayer, uvs, u, v,
  5055. faces = json.faces,
  5056. vertices = json.vertices,
  5057. normals = json.normals,
  5058. colors = json.colors,
  5059. nUvLayers = 0;
  5060. // disregard empty arrays
  5061. for ( i = 0; i < json.uvs.length; i++ ) {
  5062. if ( json.uvs[ i ].length ) nUvLayers ++;
  5063. }
  5064. for ( i = 0; i < nUvLayers; i++ ) {
  5065. geometry.faceUvs[ i ] = [];
  5066. geometry.faceVertexUvs[ i ] = [];
  5067. }
  5068. offset = 0;
  5069. zLength = vertices.length;
  5070. while ( offset < zLength ) {
  5071. vertex = new THREE.Vector3();
  5072. vertex.x = vertices[ offset ++ ] * scale;
  5073. vertex.y = vertices[ offset ++ ] * scale;
  5074. vertex.z = vertices[ offset ++ ] * scale;
  5075. geometry.vertices.push( vertex );
  5076. }
  5077. offset = 0;
  5078. zLength = faces.length;
  5079. while ( offset < zLength ) {
  5080. type = faces[ offset ++ ];
  5081. isQuad = isBitSet( type, 0 );
  5082. hasMaterial = isBitSet( type, 1 );
  5083. hasFaceUv = isBitSet( type, 2 );
  5084. hasFaceVertexUv = isBitSet( type, 3 );
  5085. hasFaceNormal = isBitSet( type, 4 );
  5086. hasFaceVertexNormal = isBitSet( type, 5 );
  5087. hasFaceColor = isBitSet( type, 6 );
  5088. hasFaceVertexColor = isBitSet( type, 7 );
  5089. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5090. if ( isQuad ) {
  5091. face = new THREE.Face4();
  5092. face.a = faces[ offset ++ ];
  5093. face.b = faces[ offset ++ ];
  5094. face.c = faces[ offset ++ ];
  5095. face.d = faces[ offset ++ ];
  5096. nVertices = 4;
  5097. } else {
  5098. face = new THREE.Face3();
  5099. face.a = faces[ offset ++ ];
  5100. face.b = faces[ offset ++ ];
  5101. face.c = faces[ offset ++ ];
  5102. nVertices = 3;
  5103. }
  5104. if ( hasMaterial ) {
  5105. materialIndex = faces[ offset ++ ];
  5106. face.materialIndex = materialIndex;
  5107. }
  5108. // to get face <=> uv index correspondence
  5109. fi = geometry.faces.length;
  5110. if ( hasFaceUv ) {
  5111. for ( i = 0; i < nUvLayers; i++ ) {
  5112. uvLayer = json.uvs[ i ];
  5113. uvIndex = faces[ offset ++ ];
  5114. u = uvLayer[ uvIndex * 2 ];
  5115. v = uvLayer[ uvIndex * 2 + 1 ];
  5116. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  5117. }
  5118. }
  5119. if ( hasFaceVertexUv ) {
  5120. for ( i = 0; i < nUvLayers; i++ ) {
  5121. uvLayer = json.uvs[ i ];
  5122. uvs = [];
  5123. for ( j = 0; j < nVertices; j ++ ) {
  5124. uvIndex = faces[ offset ++ ];
  5125. u = uvLayer[ uvIndex * 2 ];
  5126. v = uvLayer[ uvIndex * 2 + 1 ];
  5127. uvs[ j ] = new THREE.UV( u, v );
  5128. }
  5129. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5130. }
  5131. }
  5132. if ( hasFaceNormal ) {
  5133. normalIndex = faces[ offset ++ ] * 3;
  5134. normal = new THREE.Vector3();
  5135. normal.x = normals[ normalIndex ++ ];
  5136. normal.y = normals[ normalIndex ++ ];
  5137. normal.z = normals[ normalIndex ];
  5138. face.normal = normal;
  5139. }
  5140. if ( hasFaceVertexNormal ) {
  5141. for ( i = 0; i < nVertices; i++ ) {
  5142. normalIndex = faces[ offset ++ ] * 3;
  5143. normal = new THREE.Vector3();
  5144. normal.x = normals[ normalIndex ++ ];
  5145. normal.y = normals[ normalIndex ++ ];
  5146. normal.z = normals[ normalIndex ];
  5147. face.vertexNormals.push( normal );
  5148. }
  5149. }
  5150. if ( hasFaceColor ) {
  5151. colorIndex = faces[ offset ++ ];
  5152. color = new THREE.Color( colors[ colorIndex ] );
  5153. face.color = color;
  5154. }
  5155. if ( hasFaceVertexColor ) {
  5156. for ( i = 0; i < nVertices; i++ ) {
  5157. colorIndex = faces[ offset ++ ];
  5158. color = new THREE.Color( colors[ colorIndex ] );
  5159. face.vertexColors.push( color );
  5160. }
  5161. }
  5162. geometry.faces.push( face );
  5163. }
  5164. };
  5165. function parseSkin() {
  5166. var i, l, x, y, z, w, a, b, c, d;
  5167. if ( json.skinWeights ) {
  5168. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5169. x = json.skinWeights[ i ];
  5170. y = json.skinWeights[ i + 1 ];
  5171. z = 0;
  5172. w = 0;
  5173. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5174. }
  5175. }
  5176. if ( json.skinIndices ) {
  5177. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5178. a = json.skinIndices[ i ];
  5179. b = json.skinIndices[ i + 1 ];
  5180. c = 0;
  5181. d = 0;
  5182. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5183. }
  5184. }
  5185. geometry.bones = json.bones;
  5186. geometry.animation = json.animation;
  5187. };
  5188. function parseMorphing( scale ) {
  5189. if ( json.morphTargets !== undefined ) {
  5190. var i, l, v, vl, dstVertices, srcVertices;
  5191. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5192. geometry.morphTargets[ i ] = {};
  5193. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5194. geometry.morphTargets[ i ].vertices = [];
  5195. dstVertices = geometry.morphTargets[ i ].vertices;
  5196. srcVertices = json.morphTargets [ i ].vertices;
  5197. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5198. var vertex = new THREE.Vector3();
  5199. vertex.x = srcVertices[ v ] * scale;
  5200. vertex.y = srcVertices[ v + 1 ] * scale;
  5201. vertex.z = srcVertices[ v + 2 ] * scale;
  5202. dstVertices.push( vertex );
  5203. }
  5204. }
  5205. }
  5206. if ( json.morphColors !== undefined ) {
  5207. var i, l, c, cl, dstColors, srcColors, color;
  5208. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5209. geometry.morphColors[ i ] = {};
  5210. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5211. geometry.morphColors[ i ].colors = [];
  5212. dstColors = geometry.morphColors[ i ].colors;
  5213. srcColors = json.morphColors [ i ].colors;
  5214. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5215. color = new THREE.Color( 0xffaa00 );
  5216. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5217. dstColors.push( color );
  5218. }
  5219. }
  5220. }
  5221. };
  5222. var materials = this.initMaterials( json.materials, texturePath );
  5223. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5224. callback( geometry, materials );
  5225. };
  5226. /**
  5227. * @author mrdoob / http://mrdoob.com/
  5228. */
  5229. THREE.LoadingMonitor = function () {
  5230. THREE.EventTarget.call( this );
  5231. var scope = this;
  5232. var loaded = 0;
  5233. var total = 0;
  5234. var onLoad = function ( event ) {
  5235. loaded ++;
  5236. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5237. if ( loaded === total ) {
  5238. scope.dispatchEvent( { type: 'load' } );
  5239. }
  5240. };
  5241. this.add = function ( loader ) {
  5242. total ++;
  5243. loader.addEventListener( 'load', onLoad, false );
  5244. };
  5245. };
  5246. /**
  5247. * @author alteredq / http://alteredqualia.com/
  5248. */
  5249. THREE.SceneLoader = function () {
  5250. this.onLoadStart = function () {};
  5251. this.onLoadProgress = function() {};
  5252. this.onLoadComplete = function () {};
  5253. this.callbackSync = function () {};
  5254. this.callbackProgress = function () {};
  5255. this.geometryHandlerMap = {};
  5256. this.hierarchyHandlerMap = {};
  5257. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5258. this.addGeometryHandler( "binary", THREE.BinaryLoader );
  5259. };
  5260. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5261. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5262. var scope = this;
  5263. var xhr = new XMLHttpRequest();
  5264. xhr.onreadystatechange = function () {
  5265. if ( xhr.readyState === 4 ) {
  5266. if ( xhr.status === 200 || xhr.status === 0 ) {
  5267. var json = JSON.parse( xhr.responseText );
  5268. scope.parse( json, callbackFinished, url );
  5269. } else {
  5270. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5271. }
  5272. }
  5273. };
  5274. xhr.open( "GET", url, true );
  5275. xhr.send( null );
  5276. };
  5277. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5278. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5279. };
  5280. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5281. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5282. };
  5283. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5284. var scope = this;
  5285. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5286. var dg, dm, dc, df, dt,
  5287. g, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  5288. geometry, material, camera, fog,
  5289. texture, images,
  5290. light, hex, intensity,
  5291. counter_models, counter_textures,
  5292. total_models, total_textures,
  5293. result;
  5294. var target_array = [];
  5295. var data = json;
  5296. // async geometry loaders
  5297. for ( var typeID in this.geometryHandlerMap ) {
  5298. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5299. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5300. }
  5301. // async hierachy loaders
  5302. for ( var typeID in this.hierarchyHandlerMap ) {
  5303. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5304. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5305. }
  5306. counter_models = 0;
  5307. counter_textures = 0;
  5308. result = {
  5309. scene: new THREE.Scene(),
  5310. geometries: {},
  5311. face_materials: {},
  5312. materials: {},
  5313. textures: {},
  5314. objects: {},
  5315. cameras: {},
  5316. lights: {},
  5317. fogs: {},
  5318. empties: {}
  5319. };
  5320. if ( data.transform ) {
  5321. var position = data.transform.position,
  5322. rotation = data.transform.rotation,
  5323. scale = data.transform.scale;
  5324. if ( position )
  5325. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5326. if ( rotation )
  5327. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5328. if ( scale )
  5329. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5330. if ( position || rotation || scale ) {
  5331. result.scene.updateMatrix();
  5332. result.scene.updateMatrixWorld();
  5333. }
  5334. }
  5335. function get_url( source_url, url_type ) {
  5336. if ( url_type == "relativeToHTML" ) {
  5337. return source_url;
  5338. } else {
  5339. return urlBase + "/" + source_url;
  5340. }
  5341. };
  5342. // toplevel loader function, delegates to handle_children
  5343. function handle_objects() {
  5344. handle_children( result.scene, data.objects );
  5345. }
  5346. // handle all the children from the loaded json and attach them to given parent
  5347. function handle_children( parent, children ) {
  5348. for ( var dd in children ) {
  5349. // check by id if child has already been handled,
  5350. // if not, create new object
  5351. if ( result.objects[ dd ] === undefined ) {
  5352. var o = children[ dd ];
  5353. var object = null;
  5354. // meshes
  5355. if ( o.type && ( o.type in scope.hierarchyHandlerMap ) && o.loading === undefined ) {
  5356. var loaderParameters = {};
  5357. for ( var parType in g ) {
  5358. if ( parType !== "type" && parType !== "url" ) {
  5359. loaderParameters[ parType ] = g[ parType ];
  5360. }
  5361. }
  5362. material = result.materials[ o.material ];
  5363. o.loading = true;
  5364. var loader = scope.hierarchyHandlerMap[ o.type ][ "loaderObject" ];
  5365. // OBJLoader
  5366. if ( loader.addEventListener ) {
  5367. loader.addEventListener( 'load', create_callback_hierachy( dd, parent, material, o ) );
  5368. loader.load( get_url( o.url, data.urlBaseType ) );
  5369. } else {
  5370. // ColladaLoader
  5371. if ( loader.options ) {
  5372. loader.load( get_url( o.url, data.urlBaseType ), create_callback_hierachy( dd, parent, material, o ) );
  5373. // UTF8Loader
  5374. } else {
  5375. loader.load( get_url( o.url, data.urlBaseType ), create_callback_hierachy( dd, parent, material, o ), loaderParameters );
  5376. }
  5377. }
  5378. } else if ( o.geometry !== undefined ) {
  5379. geometry = result.geometries[ o.geometry ];
  5380. // geometry already loaded
  5381. if ( geometry ) {
  5382. var needsTangents = false;
  5383. material = result.materials[ o.material ];
  5384. needsTangents = material instanceof THREE.ShaderMaterial;
  5385. p = o.position;
  5386. r = o.rotation;
  5387. q = o.quaternion;
  5388. s = o.scale;
  5389. m = o.matrix;
  5390. // turn off quaternions, for the moment
  5391. q = 0;
  5392. // use materials from the model file
  5393. // if there is no material specified in the object
  5394. if ( ! o.material ) {
  5395. material = new THREE.MeshFaceMaterial( result.face_materials[ o.geometry ] );
  5396. }
  5397. // use materials from the model file
  5398. // if there is just empty face material
  5399. // (must create new material as each model has its own face material)
  5400. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  5401. material = new THREE.MeshFaceMaterial( result.face_materials[ o.geometry ] );
  5402. }
  5403. if ( material instanceof THREE.MeshFaceMaterial ) {
  5404. for ( var i = 0; i < material.materials.length; i ++ ) {
  5405. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  5406. }
  5407. }
  5408. if ( needsTangents ) {
  5409. geometry.computeTangents();
  5410. }
  5411. if ( o.skin ) {
  5412. object = new THREE.SkinnedMesh( geometry, material );
  5413. } else if ( o.morph ) {
  5414. object = new THREE.MorphAnimMesh( geometry, material );
  5415. if ( o.duration !== undefined ) {
  5416. object.duration = o.duration;
  5417. }
  5418. if ( o.time !== undefined ) {
  5419. object.time = o.time;
  5420. }
  5421. if ( o.mirroredLoop !== undefined ) {
  5422. object.mirroredLoop = o.mirroredLoop;
  5423. }
  5424. if ( material.morphNormals ) {
  5425. geometry.computeMorphNormals();
  5426. }
  5427. } else {
  5428. object = new THREE.Mesh( geometry, material );
  5429. }
  5430. object.name = dd;
  5431. if ( m ) {
  5432. object.matrixAutoUpdate = false;
  5433. object.matrix.set(
  5434. m[0], m[1], m[2], m[3],
  5435. m[4], m[5], m[6], m[7],
  5436. m[8], m[9], m[10], m[11],
  5437. m[12], m[13], m[14], m[15]
  5438. );
  5439. } else {
  5440. object.position.set( p[0], p[1], p[2] );
  5441. if ( q ) {
  5442. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5443. object.useQuaternion = true;
  5444. } else {
  5445. object.rotation.set( r[0], r[1], r[2] );
  5446. }
  5447. object.scale.set( s[0], s[1], s[2] );
  5448. }
  5449. object.visible = o.visible;
  5450. object.castShadow = o.castShadow;
  5451. object.receiveShadow = o.receiveShadow;
  5452. parent.add( object );
  5453. result.objects[ dd ] = object;
  5454. }
  5455. // lights
  5456. } else if ( o.type === "DirectionalLight" || o.type === "PointLight" || o.type === "AmbientLight" ) {
  5457. hex = ( o.color !== undefined ) ? o.color : 0xffffff;
  5458. intensity = ( o.intensity !== undefined ) ? o.intensity : 1;
  5459. if ( o.type === "DirectionalLight" ) {
  5460. p = o.direction;
  5461. light = new THREE.DirectionalLight( hex, intensity );
  5462. light.position.set( p[0], p[1], p[2] );
  5463. if ( o.target ) {
  5464. target_array.push( { "object": light, "targetName" : o.target } );
  5465. // kill existing default target
  5466. // otherwise it gets added to scene when parent gets added
  5467. light.target = null;
  5468. }
  5469. } else if ( o.type === "PointLight" ) {
  5470. p = o.position;
  5471. d = o.distance;
  5472. light = new THREE.PointLight( hex, intensity, d );
  5473. light.position.set( p[0], p[1], p[2] );
  5474. } else if ( o.type === "AmbientLight" ) {
  5475. light = new THREE.AmbientLight( hex );
  5476. }
  5477. parent.add( light );
  5478. light.name = dd;
  5479. result.lights[ dd ] = light;
  5480. result.objects[ dd ] = light;
  5481. // cameras
  5482. } else if ( o.type === "PerspectiveCamera" || o.type === "OrthographicCamera" ) {
  5483. if ( o.type === "PerspectiveCamera" ) {
  5484. camera = new THREE.PerspectiveCamera( o.fov, o.aspect, o.near, o.far );
  5485. } else if ( o.type === "OrthographicCamera" ) {
  5486. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  5487. }
  5488. p = o.position;
  5489. camera.position.set( p[0], p[1], p[2] );
  5490. parent.add( camera );
  5491. camera.name = dd;
  5492. result.cameras[ dd ] = camera;
  5493. result.objects[ dd ] = camera;
  5494. // pure Object3D
  5495. } else {
  5496. p = o.position;
  5497. r = o.rotation;
  5498. q = o.quaternion;
  5499. s = o.scale;
  5500. // turn off quaternions, for the moment
  5501. q = 0;
  5502. object = new THREE.Object3D();
  5503. object.name = dd;
  5504. object.position.set( p[0], p[1], p[2] );
  5505. if ( q ) {
  5506. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5507. object.useQuaternion = true;
  5508. } else {
  5509. object.rotation.set( r[0], r[1], r[2] );
  5510. }
  5511. object.scale.set( s[0], s[1], s[2] );
  5512. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  5513. parent.add( object );
  5514. result.objects[ dd ] = object;
  5515. result.empties[ dd ] = object;
  5516. }
  5517. if ( object ) {
  5518. if ( o.properties !== undefined ) {
  5519. for ( var key in o.properties ) {
  5520. var value = o.properties[ key ];
  5521. object.properties[ key ] = value;
  5522. }
  5523. }
  5524. if ( o.children !== undefined ) {
  5525. handle_children( object, o.children );
  5526. }
  5527. }
  5528. }
  5529. }
  5530. };
  5531. function handle_mesh( geo, mat, id ) {
  5532. result.geometries[ id ] = geo;
  5533. result.face_materials[ id ] = mat;
  5534. handle_objects();
  5535. };
  5536. function handle_hierarchy( node, id, parent, material, o ) {
  5537. var p = o.position;
  5538. var r = o.rotation;
  5539. var q = o.quaternion;
  5540. var s = o.scale;
  5541. node.position.set( p[0], p[1], p[2] );
  5542. if ( q ) {
  5543. node.quaternion.set( q[0], q[1], q[2], q[3] );
  5544. node.useQuaternion = true;
  5545. } else {
  5546. node.rotation.set( r[0], r[1], r[2] );
  5547. }
  5548. node.scale.set( s[0], s[1], s[2] );
  5549. if ( material ) {
  5550. node.traverse( function ( child ) {
  5551. child.material = material;
  5552. } );
  5553. }
  5554. parent.add( node );
  5555. result.objects[ id ] = node;
  5556. handle_objects();
  5557. };
  5558. function create_callback_geometry( id ) {
  5559. return function( geo, mat ) {
  5560. handle_mesh( geo, mat, id );
  5561. counter_models -= 1;
  5562. scope.onLoadComplete();
  5563. async_callback_gate();
  5564. }
  5565. };
  5566. function create_callback_hierachy( id, parent, material, obj ) {
  5567. return function( event ) {
  5568. var result;
  5569. // loaders which use EventTarget
  5570. if ( event.content ) {
  5571. result = event.content;
  5572. // ColladaLoader
  5573. } else if ( event.dae ) {
  5574. result = event.scene;
  5575. // UTF8Loader
  5576. } else {
  5577. result = event;
  5578. }
  5579. handle_hierarchy( result, id, parent, material, obj );
  5580. counter_models -= 1;
  5581. scope.onLoadComplete();
  5582. async_callback_gate();
  5583. }
  5584. };
  5585. function create_callback_embed( id ) {
  5586. return function( geo, mat ) {
  5587. result.geometries[ id ] = geo;
  5588. result.face_materials[ id ] = mat;
  5589. }
  5590. };
  5591. function async_callback_gate() {
  5592. var progress = {
  5593. totalModels : total_models,
  5594. totalTextures : total_textures,
  5595. loadedModels : total_models - counter_models,
  5596. loadedTextures : total_textures - counter_textures
  5597. };
  5598. scope.callbackProgress( progress, result );
  5599. scope.onLoadProgress();
  5600. if ( counter_models === 0 && counter_textures === 0 ) {
  5601. finalize();
  5602. callbackFinished( result );
  5603. }
  5604. };
  5605. function finalize() {
  5606. // take care of targets which could be asynchronously loaded objects
  5607. for ( var i = 0; i < target_array.length; i ++ ) {
  5608. var ta = target_array[ i ];
  5609. var target = result.objects[ ta.targetName ];
  5610. if ( target ) {
  5611. ta.object.target = target;
  5612. } else {
  5613. // if there was error and target of specified name doesn't exist in the scene file
  5614. // create instead dummy target
  5615. // (target must be added to scene explicitly as parent is already added)
  5616. ta.object.target = new THREE.Object3D();
  5617. result.scene.add( ta.object.target );
  5618. }
  5619. ta.object.target.properties.targetInverse = ta.object;
  5620. }
  5621. };
  5622. var callbackTexture = function ( count ) {
  5623. counter_textures -= count;
  5624. async_callback_gate();
  5625. scope.onLoadComplete();
  5626. };
  5627. // must use this instead of just directly calling callbackTexture
  5628. // because of closure in the calling context loop
  5629. var generateTextureCallback = function ( count ) {
  5630. return function() {
  5631. callbackTexture( count );
  5632. };
  5633. };
  5634. // first go synchronous elements
  5635. // fogs
  5636. for ( df in data.fogs ) {
  5637. f = data.fogs[ df ];
  5638. if ( f.type === "linear" ) {
  5639. fog = new THREE.Fog( 0x000000, f.near, f.far );
  5640. } else if ( f.type === "exp2" ) {
  5641. fog = new THREE.FogExp2( 0x000000, f.density );
  5642. }
  5643. c = f.color;
  5644. fog.color.setRGB( c[0], c[1], c[2] );
  5645. result.fogs[ df ] = fog;
  5646. }
  5647. // now come potentially asynchronous elements
  5648. // geometries
  5649. // count how many geometries will be loaded asynchronously
  5650. for ( dg in data.geometries ) {
  5651. g = data.geometries[ dg ];
  5652. if ( g.type in this.geometryHandlerMap ) {
  5653. counter_models += 1;
  5654. scope.onLoadStart();
  5655. }
  5656. }
  5657. // count how many hierarchies will be loaded asynchronously
  5658. for ( var dd in data.objects ) {
  5659. var o = data.objects[ dd ];
  5660. if ( o.type && ( o.type in this.hierarchyHandlerMap ) ) {
  5661. counter_models += 1;
  5662. scope.onLoadStart();
  5663. }
  5664. }
  5665. total_models = counter_models;
  5666. for ( dg in data.geometries ) {
  5667. g = data.geometries[ dg ];
  5668. if ( g.type === "cube" ) {
  5669. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.widthSegments, g.heightSegments, g.depthSegments );
  5670. result.geometries[ dg ] = geometry;
  5671. } else if ( g.type === "plane" ) {
  5672. geometry = new THREE.PlaneGeometry( g.width, g.height, g.widthSegments, g.heightSegments );
  5673. result.geometries[ dg ] = geometry;
  5674. } else if ( g.type === "sphere" ) {
  5675. geometry = new THREE.SphereGeometry( g.radius, g.widthSegments, g.heightSegments );
  5676. result.geometries[ dg ] = geometry;
  5677. } else if ( g.type === "cylinder" ) {
  5678. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  5679. result.geometries[ dg ] = geometry;
  5680. } else if ( g.type === "torus" ) {
  5681. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  5682. result.geometries[ dg ] = geometry;
  5683. } else if ( g.type === "icosahedron" ) {
  5684. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  5685. result.geometries[ dg ] = geometry;
  5686. } else if ( g.type in this.geometryHandlerMap ) {
  5687. var loaderParameters = {};
  5688. for ( var parType in g ) {
  5689. if ( parType !== "type" && parType !== "url" ) {
  5690. loaderParameters[ parType ] = g[ parType ];
  5691. }
  5692. }
  5693. var loader = this.geometryHandlerMap[ g.type ][ "loaderObject" ];
  5694. loader.load( get_url( g.url, data.urlBaseType ), create_callback_geometry( dg ), loaderParameters );
  5695. } else if ( g.type === "embedded" ) {
  5696. var modelJson = data.embeds[ g.id ],
  5697. texture_path = "";
  5698. // pass metadata along to jsonLoader so it knows the format version
  5699. modelJson.metadata = data.metadata;
  5700. if ( modelJson ) {
  5701. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  5702. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  5703. }
  5704. }
  5705. }
  5706. // textures
  5707. // count how many textures will be loaded asynchronously
  5708. for ( dt in data.textures ) {
  5709. tt = data.textures[ dt ];
  5710. if ( tt.url instanceof Array ) {
  5711. counter_textures += tt.url.length;
  5712. for( var n = 0; n < tt.url.length; n ++ ) {
  5713. scope.onLoadStart();
  5714. }
  5715. } else {
  5716. counter_textures += 1;
  5717. scope.onLoadStart();
  5718. }
  5719. }
  5720. total_textures = counter_textures;
  5721. for ( dt in data.textures ) {
  5722. tt = data.textures[ dt ];
  5723. if ( tt.mapping !== undefined && THREE[ tt.mapping ] !== undefined ) {
  5724. tt.mapping = new THREE[ tt.mapping ]();
  5725. }
  5726. if ( tt.url instanceof Array ) {
  5727. var count = tt.url.length;
  5728. var url_array = [];
  5729. for( var i = 0; i < count; i ++ ) {
  5730. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  5731. }
  5732. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  5733. if ( isCompressed ) {
  5734. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5735. } else {
  5736. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5737. }
  5738. } else {
  5739. var isCompressed = tt.url.toLowerCase().endsWith( ".dds" );
  5740. var fullUrl = get_url( tt.url, data.urlBaseType );
  5741. var textureCallback = generateTextureCallback( 1 );
  5742. if ( isCompressed ) {
  5743. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, tt.mapping, textureCallback );
  5744. } else {
  5745. texture = THREE.ImageUtils.loadTexture( fullUrl, tt.mapping, textureCallback );
  5746. }
  5747. if ( THREE[ tt.minFilter ] !== undefined )
  5748. texture.minFilter = THREE[ tt.minFilter ];
  5749. if ( THREE[ tt.magFilter ] !== undefined )
  5750. texture.magFilter = THREE[ tt.magFilter ];
  5751. if ( tt.anisotropy ) texture.anisotropy = tt.anisotropy;
  5752. if ( tt.repeat ) {
  5753. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  5754. if ( tt.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  5755. if ( tt.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  5756. }
  5757. if ( tt.offset ) {
  5758. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  5759. }
  5760. // handle wrap after repeat so that default repeat can be overriden
  5761. if ( tt.wrap ) {
  5762. var wrapMap = {
  5763. "repeat" : THREE.RepeatWrapping,
  5764. "mirror" : THREE.MirroredRepeatWrapping
  5765. }
  5766. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  5767. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  5768. }
  5769. }
  5770. result.textures[ dt ] = texture;
  5771. }
  5772. // materials
  5773. for ( dm in data.materials ) {
  5774. m = data.materials[ dm ];
  5775. for ( pp in m.parameters ) {
  5776. if ( pp === "envMap" || pp === "map" || pp === "lightMap" || pp === "bumpMap" ) {
  5777. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  5778. } else if ( pp === "shading" ) {
  5779. m.parameters[ pp ] = ( m.parameters[ pp ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  5780. } else if ( pp === "side" ) {
  5781. if ( m.parameters[ pp ] == "double" ) {
  5782. m.parameters[ pp ] = THREE.DoubleSide;
  5783. } else if ( m.parameters[ pp ] == "back" ) {
  5784. m.parameters[ pp ] = THREE.BackSide;
  5785. } else {
  5786. m.parameters[ pp ] = THREE.FrontSide;
  5787. }
  5788. } else if ( pp === "blending" ) {
  5789. m.parameters[ pp ] = m.parameters[ pp ] in THREE ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  5790. } else if ( pp === "combine" ) {
  5791. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  5792. } else if ( pp === "vertexColors" ) {
  5793. if ( m.parameters[ pp ] == "face" ) {
  5794. m.parameters[ pp ] = THREE.FaceColors;
  5795. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  5796. } else if ( m.parameters[ pp ] ) {
  5797. m.parameters[ pp ] = THREE.VertexColors;
  5798. }
  5799. } else if ( pp === "wrapRGB" ) {
  5800. var v3 = m.parameters[ pp ];
  5801. m.parameters[ pp ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  5802. }
  5803. }
  5804. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  5805. m.parameters.transparent = true;
  5806. }
  5807. if ( m.parameters.normalMap ) {
  5808. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5809. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5810. var diffuse = m.parameters.color;
  5811. var specular = m.parameters.specular;
  5812. var ambient = m.parameters.ambient;
  5813. var shininess = m.parameters.shininess;
  5814. uniforms[ "tNormal" ].value = result.textures[ m.parameters.normalMap ];
  5815. if ( m.parameters.normalScale ) {
  5816. uniforms[ "uNormalScale" ].value.set( m.parameters.normalScale[ 0 ], m.parameters.normalScale[ 1 ] );
  5817. }
  5818. if ( m.parameters.map ) {
  5819. uniforms[ "tDiffuse" ].value = m.parameters.map;
  5820. uniforms[ "enableDiffuse" ].value = true;
  5821. }
  5822. if ( m.parameters.envMap ) {
  5823. uniforms[ "tCube" ].value = m.parameters.envMap;
  5824. uniforms[ "enableReflection" ].value = true;
  5825. uniforms[ "uReflectivity" ].value = m.parameters.reflectivity;
  5826. }
  5827. if ( m.parameters.lightMap ) {
  5828. uniforms[ "tAO" ].value = m.parameters.lightMap;
  5829. uniforms[ "enableAO" ].value = true;
  5830. }
  5831. if ( m.parameters.specularMap ) {
  5832. uniforms[ "tSpecular" ].value = result.textures[ m.parameters.specularMap ];
  5833. uniforms[ "enableSpecular" ].value = true;
  5834. }
  5835. if ( m.parameters.displacementMap ) {
  5836. uniforms[ "tDisplacement" ].value = result.textures[ m.parameters.displacementMap ];
  5837. uniforms[ "enableDisplacement" ].value = true;
  5838. uniforms[ "uDisplacementBias" ].value = m.parameters.displacementBias;
  5839. uniforms[ "uDisplacementScale" ].value = m.parameters.displacementScale;
  5840. }
  5841. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  5842. uniforms[ "uSpecularColor" ].value.setHex( specular );
  5843. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  5844. uniforms[ "uShininess" ].value = shininess;
  5845. if ( m.parameters.opacity ) {
  5846. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  5847. }
  5848. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5849. material = new THREE.ShaderMaterial( parameters );
  5850. } else {
  5851. material = new THREE[ m.type ]( m.parameters );
  5852. }
  5853. result.materials[ dm ] = material;
  5854. }
  5855. // second pass through all materials to initialize MeshFaceMaterials
  5856. // that could be referring to other materials out of order
  5857. for ( dm in data.materials ) {
  5858. m = data.materials[ dm ];
  5859. if ( m.parameters.materials ) {
  5860. var materialArray = [];
  5861. for ( var i = 0; i < m.parameters.materials.length; i ++ ) {
  5862. var label = m.parameters.materials[ i ];
  5863. materialArray.push( result.materials[ label ] );
  5864. }
  5865. result.materials[ dm ].materials = materialArray;
  5866. }
  5867. }
  5868. // objects ( synchronous init of procedural primitives )
  5869. handle_objects();
  5870. // defaults
  5871. if ( result.cameras && data.defaults.camera ) {
  5872. result.currentCamera = result.cameras[ data.defaults.camera ];
  5873. }
  5874. if ( result.fogs && data.defaults.fog ) {
  5875. result.scene.fog = result.fogs[ data.defaults.fog ];
  5876. }
  5877. c = data.defaults.bgcolor;
  5878. result.bgColor = new THREE.Color();
  5879. result.bgColor.setRGB( c[0], c[1], c[2] );
  5880. result.bgColorAlpha = data.defaults.bgalpha;
  5881. // synchronous callback
  5882. scope.callbackSync( result );
  5883. // just in case there are no async elements
  5884. async_callback_gate();
  5885. };
  5886. /**
  5887. * @author mrdoob / http://mrdoob.com/
  5888. */
  5889. THREE.TextureLoader = function () {
  5890. THREE.EventTarget.call( this );
  5891. this.crossOrigin = null;
  5892. };
  5893. THREE.TextureLoader.prototype = {
  5894. constructor: THREE.TextureLoader,
  5895. load: function ( url ) {
  5896. var scope = this;
  5897. var image = new Image();
  5898. image.addEventListener( 'load', function () {
  5899. var texture = new THREE.Texture( image );
  5900. texture.needsUpdate = true;
  5901. scope.dispatchEvent( { type: 'load', content: texture } );
  5902. }, false );
  5903. image.addEventListener( 'error', function () {
  5904. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5905. }, false );
  5906. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5907. image.src = url;
  5908. }
  5909. }
  5910. /**
  5911. * @author mrdoob / http://mrdoob.com/
  5912. * @author alteredq / http://alteredqualia.com/
  5913. */
  5914. THREE.Material = function () {
  5915. THREE.MaterialLibrary.push( this );
  5916. this.id = THREE.MaterialIdCount ++;
  5917. this.name = '';
  5918. this.side = THREE.FrontSide;
  5919. this.opacity = 1;
  5920. this.transparent = false;
  5921. this.blending = THREE.NormalBlending;
  5922. this.blendSrc = THREE.SrcAlphaFactor;
  5923. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  5924. this.blendEquation = THREE.AddEquation;
  5925. this.depthTest = true;
  5926. this.depthWrite = true;
  5927. this.polygonOffset = false;
  5928. this.polygonOffsetFactor = 0;
  5929. this.polygonOffsetUnits = 0;
  5930. this.alphaTest = 0;
  5931. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  5932. this.visible = true;
  5933. this.needsUpdate = true;
  5934. };
  5935. THREE.Material.prototype.setValues = function ( values ) {
  5936. if ( values === undefined ) return;
  5937. for ( var key in values ) {
  5938. var newValue = values[ key ];
  5939. if ( newValue === undefined ) {
  5940. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5941. continue;
  5942. }
  5943. if ( key in this ) {
  5944. var currentValue = this[ key ];
  5945. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  5946. currentValue.copy( newValue );
  5947. } else if ( currentValue instanceof THREE.Color ) {
  5948. currentValue.set( newValue );
  5949. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  5950. currentValue.copy( newValue );
  5951. } else {
  5952. this[ key ] = newValue;
  5953. }
  5954. }
  5955. }
  5956. };
  5957. THREE.Material.prototype.clone = function ( material ) {
  5958. if ( material === undefined ) material = new THREE.Material();
  5959. material.name = this.name;
  5960. material.side = this.side;
  5961. material.opacity = this.opacity;
  5962. material.transparent = this.transparent;
  5963. material.blending = this.blending;
  5964. material.blendSrc = this.blendSrc;
  5965. material.blendDst = this.blendDst;
  5966. material.blendEquation = this.blendEquation;
  5967. material.depthTest = this.depthTest;
  5968. material.depthWrite = this.depthWrite;
  5969. material.polygonOffset = this.polygonOffset;
  5970. material.polygonOffsetFactor = this.polygonOffsetFactor;
  5971. material.polygonOffsetUnits = this.polygonOffsetUnits;
  5972. material.alphaTest = this.alphaTest;
  5973. material.overdraw = this.overdraw;
  5974. material.visible = this.visible;
  5975. return material;
  5976. };
  5977. THREE.Material.prototype.deallocate = function () {
  5978. var index = THREE.MaterialLibrary.indexOf( this );
  5979. if ( index !== -1 ) THREE.MaterialLibrary.splice( index, 1 );
  5980. };
  5981. THREE.MaterialIdCount = 0;
  5982. THREE.MaterialLibrary = [];
  5983. /**
  5984. * @author mrdoob / http://mrdoob.com/
  5985. * @author alteredq / http://alteredqualia.com/
  5986. *
  5987. * parameters = {
  5988. * color: <hex>,
  5989. * opacity: <float>,
  5990. *
  5991. * blending: THREE.NormalBlending,
  5992. * depthTest: <bool>,
  5993. * depthWrite: <bool>,
  5994. *
  5995. * linewidth: <float>,
  5996. * linecap: "round",
  5997. * linejoin: "round",
  5998. *
  5999. * vertexColors: <bool>
  6000. *
  6001. * fog: <bool>
  6002. * }
  6003. */
  6004. THREE.LineBasicMaterial = function ( parameters ) {
  6005. THREE.Material.call( this );
  6006. this.color = new THREE.Color( 0xffffff );
  6007. this.linewidth = 1;
  6008. this.linecap = 'round';
  6009. this.linejoin = 'round';
  6010. this.vertexColors = false;
  6011. this.fog = true;
  6012. this.setValues( parameters );
  6013. };
  6014. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6015. THREE.LineBasicMaterial.prototype.clone = function () {
  6016. var material = new THREE.LineBasicMaterial();
  6017. THREE.Material.prototype.clone.call( this, material );
  6018. material.color.copy( this.color );
  6019. material.linewidth = this.linewidth;
  6020. material.linecap = this.linecap;
  6021. material.linejoin = this.linejoin;
  6022. material.vertexColors = this.vertexColors;
  6023. material.fog = this.fog;
  6024. return material;
  6025. };
  6026. /**
  6027. * @author alteredq / http://alteredqualia.com/
  6028. *
  6029. * parameters = {
  6030. * color: <hex>,
  6031. * opacity: <float>,
  6032. *
  6033. * blending: THREE.NormalBlending,
  6034. * depthTest: <bool>,
  6035. * depthWrite: <bool>,
  6036. *
  6037. * linewidth: <float>,
  6038. *
  6039. * scale: <float>,
  6040. * dashSize: <float>,
  6041. * gapSize: <float>,
  6042. *
  6043. * vertexColors: <bool>
  6044. *
  6045. * fog: <bool>
  6046. * }
  6047. */
  6048. THREE.LineDashedMaterial = function ( parameters ) {
  6049. THREE.Material.call( this );
  6050. this.color = new THREE.Color( 0xffffff );
  6051. this.linewidth = 1;
  6052. this.scale = 1;
  6053. this.dashSize = 3;
  6054. this.gapSize = 1;
  6055. this.vertexColors = false;
  6056. this.fog = true;
  6057. this.setValues( parameters );
  6058. };
  6059. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6060. THREE.LineDashedMaterial.prototype.clone = function () {
  6061. var material = new THREE.LineDashedMaterial();
  6062. THREE.Material.prototype.clone.call( this, material );
  6063. material.color.copy( this.color );
  6064. material.linewidth = this.linewidth;
  6065. material.scale = this.scale;
  6066. material.dashSize = this.dashSize;
  6067. material.gapSize = this.gapSize;
  6068. material.vertexColors = this.vertexColors;
  6069. material.fog = this.fog;
  6070. return material;
  6071. };
  6072. /**
  6073. * @author mrdoob / http://mrdoob.com/
  6074. * @author alteredq / http://alteredqualia.com/
  6075. *
  6076. * parameters = {
  6077. * color: <hex>,
  6078. * opacity: <float>,
  6079. * map: new THREE.Texture( <Image> ),
  6080. *
  6081. * lightMap: new THREE.Texture( <Image> ),
  6082. *
  6083. * specularMap: new THREE.Texture( <Image> ),
  6084. *
  6085. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6086. * combine: THREE.Multiply,
  6087. * reflectivity: <float>,
  6088. * refractionRatio: <float>,
  6089. *
  6090. * shading: THREE.SmoothShading,
  6091. * blending: THREE.NormalBlending,
  6092. * depthTest: <bool>,
  6093. * depthWrite: <bool>,
  6094. *
  6095. * wireframe: <boolean>,
  6096. * wireframeLinewidth: <float>,
  6097. *
  6098. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6099. *
  6100. * skinning: <bool>,
  6101. * morphTargets: <bool>,
  6102. *
  6103. * fog: <bool>
  6104. * }
  6105. */
  6106. THREE.MeshBasicMaterial = function ( parameters ) {
  6107. THREE.Material.call( this );
  6108. this.color = new THREE.Color( 0xffffff ); // emissive
  6109. this.map = null;
  6110. this.lightMap = null;
  6111. this.specularMap = null;
  6112. this.envMap = null;
  6113. this.combine = THREE.MultiplyOperation;
  6114. this.reflectivity = 1;
  6115. this.refractionRatio = 0.98;
  6116. this.fog = true;
  6117. this.shading = THREE.SmoothShading;
  6118. this.wireframe = false;
  6119. this.wireframeLinewidth = 1;
  6120. this.wireframeLinecap = 'round';
  6121. this.wireframeLinejoin = 'round';
  6122. this.vertexColors = THREE.NoColors;
  6123. this.skinning = false;
  6124. this.morphTargets = false;
  6125. this.setValues( parameters );
  6126. };
  6127. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6128. THREE.MeshBasicMaterial.prototype.clone = function () {
  6129. var material = new THREE.MeshBasicMaterial();
  6130. THREE.Material.prototype.clone.call( this, material );
  6131. material.color.copy( this.color );
  6132. material.map = this.map;
  6133. material.lightMap = this.lightMap;
  6134. material.specularMap = this.specularMap;
  6135. material.envMap = this.envMap;
  6136. material.combine = this.combine;
  6137. material.reflectivity = this.reflectivity;
  6138. material.refractionRatio = this.refractionRatio;
  6139. material.fog = this.fog;
  6140. material.shading = this.shading;
  6141. material.wireframe = this.wireframe;
  6142. material.wireframeLinewidth = this.wireframeLinewidth;
  6143. material.wireframeLinecap = this.wireframeLinecap;
  6144. material.wireframeLinejoin = this.wireframeLinejoin;
  6145. material.vertexColors = this.vertexColors;
  6146. material.skinning = this.skinning;
  6147. material.morphTargets = this.morphTargets;
  6148. return material;
  6149. };
  6150. /**
  6151. * @author mrdoob / http://mrdoob.com/
  6152. * @author alteredq / http://alteredqualia.com/
  6153. *
  6154. * parameters = {
  6155. * color: <hex>,
  6156. * ambient: <hex>,
  6157. * emissive: <hex>,
  6158. * opacity: <float>,
  6159. *
  6160. * map: new THREE.Texture( <Image> ),
  6161. *
  6162. * lightMap: new THREE.Texture( <Image> ),
  6163. *
  6164. * specularMap: new THREE.Texture( <Image> ),
  6165. *
  6166. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6167. * combine: THREE.Multiply,
  6168. * reflectivity: <float>,
  6169. * refractionRatio: <float>,
  6170. *
  6171. * shading: THREE.SmoothShading,
  6172. * blending: THREE.NormalBlending,
  6173. * depthTest: <bool>,
  6174. * depthWrite: <bool>,
  6175. *
  6176. * wireframe: <boolean>,
  6177. * wireframeLinewidth: <float>,
  6178. *
  6179. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6180. *
  6181. * skinning: <bool>,
  6182. * morphTargets: <bool>,
  6183. * morphNormals: <bool>,
  6184. *
  6185. * fog: <bool>
  6186. * }
  6187. */
  6188. THREE.MeshLambertMaterial = function ( parameters ) {
  6189. THREE.Material.call( this );
  6190. this.color = new THREE.Color( 0xffffff ); // diffuse
  6191. this.ambient = new THREE.Color( 0xffffff );
  6192. this.emissive = new THREE.Color( 0x000000 );
  6193. this.wrapAround = false;
  6194. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6195. this.map = null;
  6196. this.lightMap = null;
  6197. this.specularMap = null;
  6198. this.envMap = null;
  6199. this.combine = THREE.MultiplyOperation;
  6200. this.reflectivity = 1;
  6201. this.refractionRatio = 0.98;
  6202. this.fog = true;
  6203. this.shading = THREE.SmoothShading;
  6204. this.wireframe = false;
  6205. this.wireframeLinewidth = 1;
  6206. this.wireframeLinecap = 'round';
  6207. this.wireframeLinejoin = 'round';
  6208. this.vertexColors = THREE.NoColors;
  6209. this.skinning = false;
  6210. this.morphTargets = false;
  6211. this.morphNormals = false;
  6212. this.setValues( parameters );
  6213. };
  6214. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6215. THREE.MeshLambertMaterial.prototype.clone = function () {
  6216. var material = new THREE.MeshLambertMaterial();
  6217. THREE.Material.prototype.clone.call( this, material );
  6218. material.color.copy( this.color );
  6219. material.ambient.copy( this.ambient );
  6220. material.emissive.copy( this.emissive );
  6221. material.wrapAround = this.wrapAround;
  6222. material.wrapRGB.copy( this.wrapRGB );
  6223. material.map = this.map;
  6224. material.lightMap = this.lightMap;
  6225. material.specularMap = this.specularMap;
  6226. material.envMap = this.envMap;
  6227. material.combine = this.combine;
  6228. material.reflectivity = this.reflectivity;
  6229. material.refractionRatio = this.refractionRatio;
  6230. material.fog = this.fog;
  6231. material.shading = this.shading;
  6232. material.wireframe = this.wireframe;
  6233. material.wireframeLinewidth = this.wireframeLinewidth;
  6234. material.wireframeLinecap = this.wireframeLinecap;
  6235. material.wireframeLinejoin = this.wireframeLinejoin;
  6236. material.vertexColors = this.vertexColors;
  6237. material.skinning = this.skinning;
  6238. material.morphTargets = this.morphTargets;
  6239. material.morphNormals = this.morphNormals;
  6240. return material;
  6241. };
  6242. /**
  6243. * @author mrdoob / http://mrdoob.com/
  6244. * @author alteredq / http://alteredqualia.com/
  6245. *
  6246. * parameters = {
  6247. * color: <hex>,
  6248. * ambient: <hex>,
  6249. * emissive: <hex>,
  6250. * specular: <hex>,
  6251. * shininess: <float>,
  6252. * opacity: <float>,
  6253. *
  6254. * map: new THREE.Texture( <Image> ),
  6255. *
  6256. * lightMap: new THREE.Texture( <Image> ),
  6257. *
  6258. * bumpMap: new THREE.Texture( <Image> ),
  6259. * bumpScale: <float>,
  6260. *
  6261. * normalMap: new THREE.Texture( <Image> ),
  6262. * normalScale: <Vector2>,
  6263. *
  6264. * specularMap: new THREE.Texture( <Image> ),
  6265. *
  6266. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6267. * combine: THREE.Multiply,
  6268. * reflectivity: <float>,
  6269. * refractionRatio: <float>,
  6270. *
  6271. * shading: THREE.SmoothShading,
  6272. * blending: THREE.NormalBlending,
  6273. * depthTest: <bool>,
  6274. * depthWrite: <bool>,
  6275. *
  6276. * wireframe: <boolean>,
  6277. * wireframeLinewidth: <float>,
  6278. *
  6279. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6280. *
  6281. * skinning: <bool>,
  6282. * morphTargets: <bool>,
  6283. * morphNormals: <bool>,
  6284. *
  6285. * fog: <bool>
  6286. * }
  6287. */
  6288. THREE.MeshPhongMaterial = function ( parameters ) {
  6289. THREE.Material.call( this );
  6290. this.color = new THREE.Color( 0xffffff ); // diffuse
  6291. this.ambient = new THREE.Color( 0xffffff );
  6292. this.emissive = new THREE.Color( 0x000000 );
  6293. this.specular = new THREE.Color( 0x111111 );
  6294. this.shininess = 30;
  6295. this.metal = false;
  6296. this.perPixel = true;
  6297. this.wrapAround = false;
  6298. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6299. this.map = null;
  6300. this.lightMap = null;
  6301. this.bumpMap = null;
  6302. this.bumpScale = 1;
  6303. this.normalMap = null;
  6304. this.normalScale = new THREE.Vector2( 1, 1 );
  6305. this.specularMap = null;
  6306. this.envMap = null;
  6307. this.combine = THREE.MultiplyOperation;
  6308. this.reflectivity = 1;
  6309. this.refractionRatio = 0.98;
  6310. this.fog = true;
  6311. this.shading = THREE.SmoothShading;
  6312. this.wireframe = false;
  6313. this.wireframeLinewidth = 1;
  6314. this.wireframeLinecap = 'round';
  6315. this.wireframeLinejoin = 'round';
  6316. this.vertexColors = THREE.NoColors;
  6317. this.skinning = false;
  6318. this.morphTargets = false;
  6319. this.morphNormals = false;
  6320. this.setValues( parameters );
  6321. };
  6322. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6323. THREE.MeshPhongMaterial.prototype.clone = function () {
  6324. var material = new THREE.MeshPhongMaterial();
  6325. THREE.Material.prototype.clone.call( this, material );
  6326. material.color.copy( this.color );
  6327. material.ambient.copy( this.ambient );
  6328. material.emissive.copy( this.emissive );
  6329. material.specular.copy( this.specular );
  6330. material.shininess = this.shininess;
  6331. material.metal = this.metal;
  6332. material.perPixel = this.perPixel;
  6333. material.wrapAround = this.wrapAround;
  6334. material.wrapRGB.copy( this.wrapRGB );
  6335. material.map = this.map;
  6336. material.lightMap = this.lightMap;
  6337. material.bumpMap = this.bumpMap;
  6338. material.bumpScale = this.bumpScale;
  6339. material.normalMap = this.normalMap;
  6340. material.normalScale.copy( this.normalScale );
  6341. material.specularMap = this.specularMap;
  6342. material.envMap = this.envMap;
  6343. material.combine = this.combine;
  6344. material.reflectivity = this.reflectivity;
  6345. material.refractionRatio = this.refractionRatio;
  6346. material.fog = this.fog;
  6347. material.shading = this.shading;
  6348. material.wireframe = this.wireframe;
  6349. material.wireframeLinewidth = this.wireframeLinewidth;
  6350. material.wireframeLinecap = this.wireframeLinecap;
  6351. material.wireframeLinejoin = this.wireframeLinejoin;
  6352. material.vertexColors = this.vertexColors;
  6353. material.skinning = this.skinning;
  6354. material.morphTargets = this.morphTargets;
  6355. material.morphNormals = this.morphNormals;
  6356. return material;
  6357. };
  6358. /**
  6359. * @author mrdoob / http://mrdoob.com/
  6360. * @author alteredq / http://alteredqualia.com/
  6361. *
  6362. * parameters = {
  6363. * opacity: <float>,
  6364. *
  6365. * blending: THREE.NormalBlending,
  6366. * depthTest: <bool>,
  6367. * depthWrite: <bool>,
  6368. *
  6369. * wireframe: <boolean>,
  6370. * wireframeLinewidth: <float>
  6371. * }
  6372. */
  6373. THREE.MeshDepthMaterial = function ( parameters ) {
  6374. THREE.Material.call( this );
  6375. this.wireframe = false;
  6376. this.wireframeLinewidth = 1;
  6377. this.setValues( parameters );
  6378. };
  6379. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6380. THREE.MeshDepthMaterial.prototype.clone = function () {
  6381. var material = new THREE.LineBasicMaterial();
  6382. THREE.Material.prototype.clone.call( this, material );
  6383. material.wireframe = this.wireframe;
  6384. material.wireframeLinewidth = this.wireframeLinewidth;
  6385. return material;
  6386. };
  6387. /**
  6388. * @author mrdoob / http://mrdoob.com/
  6389. *
  6390. * parameters = {
  6391. * opacity: <float>,
  6392. *
  6393. * shading: THREE.FlatShading,
  6394. * blending: THREE.NormalBlending,
  6395. * depthTest: <bool>,
  6396. * depthWrite: <bool>,
  6397. *
  6398. * wireframe: <boolean>,
  6399. * wireframeLinewidth: <float>
  6400. * }
  6401. */
  6402. THREE.MeshNormalMaterial = function ( parameters ) {
  6403. THREE.Material.call( this, parameters );
  6404. this.shading = THREE.FlatShading;
  6405. this.wireframe = false;
  6406. this.wireframeLinewidth = 1;
  6407. this.setValues( parameters );
  6408. };
  6409. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  6410. THREE.MeshNormalMaterial.prototype.clone = function () {
  6411. var material = new THREE.MeshNormalMaterial();
  6412. THREE.Material.prototype.clone.call( this, material );
  6413. material.shading = this.shading;
  6414. material.wireframe = this.wireframe;
  6415. material.wireframeLinewidth = this.wireframeLinewidth;
  6416. return material;
  6417. };
  6418. /**
  6419. * @author mrdoob / http://mrdoob.com/
  6420. */
  6421. THREE.MeshFaceMaterial = function ( materials ) {
  6422. this.materials = materials instanceof Array ? materials : [];
  6423. };
  6424. THREE.MeshFaceMaterial.prototype.clone = function () {
  6425. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  6426. };
  6427. /**
  6428. * @author mrdoob / http://mrdoob.com/
  6429. * @author alteredq / http://alteredqualia.com/
  6430. *
  6431. * parameters = {
  6432. * color: <hex>,
  6433. * opacity: <float>,
  6434. * map: new THREE.Texture( <Image> ),
  6435. *
  6436. * size: <float>,
  6437. *
  6438. * blending: THREE.NormalBlending,
  6439. * depthTest: <bool>,
  6440. * depthWrite: <bool>,
  6441. *
  6442. * vertexColors: <bool>,
  6443. *
  6444. * fog: <bool>
  6445. * }
  6446. */
  6447. THREE.ParticleBasicMaterial = function ( parameters ) {
  6448. THREE.Material.call( this );
  6449. this.color = new THREE.Color( 0xffffff );
  6450. this.map = null;
  6451. this.size = 1;
  6452. this.sizeAttenuation = true;
  6453. this.vertexColors = false;
  6454. this.fog = true;
  6455. this.setValues( parameters );
  6456. };
  6457. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6458. THREE.ParticleBasicMaterial.prototype.clone = function () {
  6459. var material = new THREE.ParticleBasicMaterial();
  6460. THREE.Material.prototype.clone.call( this, material );
  6461. material.color.copy( this.color );
  6462. material.map = this.map;
  6463. material.size = this.size;
  6464. material.sizeAttenuation = this.sizeAttenuation;
  6465. material.vertexColors = this.vertexColors;
  6466. material.fog = this.fog;
  6467. return material;
  6468. };
  6469. /**
  6470. * @author mrdoob / http://mrdoob.com/
  6471. *
  6472. * parameters = {
  6473. * color: <hex>,
  6474. * program: <function>,
  6475. * opacity: <float>,
  6476. * blending: THREE.NormalBlending
  6477. * }
  6478. */
  6479. THREE.ParticleCanvasMaterial = function ( parameters ) {
  6480. THREE.Material.call( this );
  6481. this.color = new THREE.Color( 0xffffff );
  6482. this.program = function ( context, color ) {};
  6483. this.setValues( parameters );
  6484. };
  6485. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  6486. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  6487. var material = new THREE.ParticleCanvasMaterial();
  6488. THREE.Material.prototype.clone.call( this, material );
  6489. material.color.copy( this.color );
  6490. material.program = this.program;
  6491. return material;
  6492. };
  6493. /**
  6494. * @author mrdoob / http://mrdoob.com/
  6495. */
  6496. THREE.ParticleDOMMaterial = function ( element ) {
  6497. this.element = element;
  6498. };
  6499. THREE.ParticleDOMMaterial.prototype.clone = function(){
  6500. return new THREE.ParticleDOMMaterial( this.element );
  6501. };
  6502. /**
  6503. * @author alteredq / http://alteredqualia.com/
  6504. *
  6505. * parameters = {
  6506. * fragmentShader: <string>,
  6507. * vertexShader: <string>,
  6508. *
  6509. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  6510. *
  6511. * defines: { "label" : "value" },
  6512. *
  6513. * shading: THREE.SmoothShading,
  6514. * blending: THREE.NormalBlending,
  6515. * depthTest: <bool>,
  6516. * depthWrite: <bool>,
  6517. *
  6518. * wireframe: <boolean>,
  6519. * wireframeLinewidth: <float>,
  6520. *
  6521. * lights: <bool>,
  6522. *
  6523. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6524. *
  6525. * skinning: <bool>,
  6526. * morphTargets: <bool>,
  6527. * morphNormals: <bool>,
  6528. *
  6529. * fog: <bool>
  6530. * }
  6531. */
  6532. THREE.ShaderMaterial = function ( parameters ) {
  6533. THREE.Material.call( this );
  6534. this.fragmentShader = "void main() {}";
  6535. this.vertexShader = "void main() {}";
  6536. this.uniforms = {};
  6537. this.defines = {};
  6538. this.attributes = null;
  6539. this.shading = THREE.SmoothShading;
  6540. this.wireframe = false;
  6541. this.wireframeLinewidth = 1;
  6542. this.fog = false; // set to use scene fog
  6543. this.lights = false; // set to use scene lights
  6544. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  6545. this.skinning = false; // set to use skinning attribute streams
  6546. this.morphTargets = false; // set to use morph targets
  6547. this.morphNormals = false; // set to use morph normals
  6548. this.setValues( parameters );
  6549. };
  6550. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  6551. THREE.ShaderMaterial.prototype.clone = function () {
  6552. var material = new THREE.ShaderMaterial();
  6553. THREE.Material.prototype.clone.call( this, material );
  6554. material.fragmentShader = this.fragmentShader;
  6555. material.vertexShader = this.vertexShader;
  6556. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  6557. material.attributes = this.attributes;
  6558. material.defines = this.defines;
  6559. material.shading = this.shading;
  6560. material.wireframe = this.wireframe;
  6561. material.wireframeLinewidth = this.wireframeLinewidth;
  6562. material.fog = this.fog;
  6563. material.lights = this.lights;
  6564. material.vertexColors = this.vertexColors;
  6565. material.skinning = this.skinning;
  6566. material.morphTargets = this.morphTargets;
  6567. material.morphNormals = this.morphNormals;
  6568. return material;
  6569. };
  6570. /**
  6571. * @author alteredq / http://alteredqualia.com/
  6572. *
  6573. * parameters = {
  6574. * color: <hex>,
  6575. * opacity: <float>,
  6576. * map: new THREE.Texture( <Image> ),
  6577. *
  6578. * blending: THREE.NormalBlending,
  6579. * depthTest: <bool>,
  6580. * depthWrite: <bool>,
  6581. *
  6582. * useScreenCoordinates: <bool>,
  6583. * sizeAttenuation: <bool>,
  6584. * scaleByViewport: <bool>,
  6585. * alignment: THREE.SpriteAlignment.center,
  6586. *
  6587. * uvOffset: new THREE.Vector2(),
  6588. * uvScale: new THREE.Vector2(),
  6589. *
  6590. * fog: <bool>
  6591. * }
  6592. */
  6593. THREE.SpriteMaterial = function ( parameters ) {
  6594. THREE.Material.call( this );
  6595. // defaults
  6596. this.color = new THREE.Color( 0xffffff );
  6597. this.map = new THREE.Texture();
  6598. this.useScreenCoordinates = true;
  6599. this.depthTest = !this.useScreenCoordinates;
  6600. this.sizeAttenuation = !this.useScreenCoordinates;
  6601. this.scaleByViewport = !this.sizeAttenuation;
  6602. this.alignment = THREE.SpriteAlignment.center.clone();
  6603. this.fog = false;
  6604. this.uvOffset = new THREE.Vector2( 0, 0 );
  6605. this.uvScale = new THREE.Vector2( 1, 1 );
  6606. // set parameters
  6607. this.setValues( parameters );
  6608. // override coupled defaults if not specified explicitly by parameters
  6609. parameters = parameters || {};
  6610. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  6611. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  6612. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  6613. };
  6614. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  6615. THREE.SpriteMaterial.prototype.clone = function () {
  6616. var material = new THREE.SpriteMaterial();
  6617. THREE.Material.prototype.clone.call( this, material );
  6618. material.color.copy( this.color );
  6619. material.map = this.map;
  6620. material.useScreenCoordinates = this.useScreenCoordinates;
  6621. material.sizeAttenuation = this.sizeAttenuation;
  6622. material.scaleByViewport = this.scaleByViewport;
  6623. material.alignment.copy( this.alignment );
  6624. material.uvOffset.copy( this.uvOffset );
  6625. material.uvScale.copy( this.uvScale );
  6626. material.fog = this.fog;
  6627. return material;
  6628. };
  6629. // Alignment enums
  6630. THREE.SpriteAlignment = {};
  6631. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  6632. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  6633. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  6634. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  6635. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  6636. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  6637. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  6638. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  6639. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  6640. /**
  6641. * @author mrdoob / http://mrdoob.com/
  6642. * @author alteredq / http://alteredqualia.com/
  6643. * @author szimek / https://github.com/szimek/
  6644. */
  6645. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  6646. THREE.TextureLibrary.push( this );
  6647. this.id = THREE.TextureIdCount ++;
  6648. this.name = '';
  6649. this.image = image;
  6650. this.mipmaps = [];
  6651. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  6652. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  6653. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  6654. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  6655. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  6656. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6657. this.format = format !== undefined ? format : THREE.RGBAFormat;
  6658. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  6659. this.offset = new THREE.Vector2( 0, 0 );
  6660. this.repeat = new THREE.Vector2( 1, 1 );
  6661. this.generateMipmaps = true;
  6662. this.premultiplyAlpha = false;
  6663. this.flipY = true;
  6664. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  6665. this.needsUpdate = false;
  6666. this.onUpdate = null;
  6667. };
  6668. THREE.Texture.prototype = {
  6669. constructor: THREE.Texture,
  6670. clone: function ( texture ) {
  6671. if ( texture === undefined ) texture = new THREE.Texture();
  6672. texture.image = this.image;
  6673. texture.mipmaps = this.mipmaps.slice(0);
  6674. texture.mapping = this.mapping;
  6675. texture.wrapS = this.wrapS;
  6676. texture.wrapT = this.wrapT;
  6677. texture.magFilter = this.magFilter;
  6678. texture.minFilter = this.minFilter;
  6679. texture.anisotropy = this.anisotropy;
  6680. texture.format = this.format;
  6681. texture.type = this.type;
  6682. texture.offset.copy( this.offset );
  6683. texture.repeat.copy( this.repeat );
  6684. texture.generateMipmaps = this.generateMipmaps;
  6685. texture.premultiplyAlpha = this.premultiplyAlpha;
  6686. texture.flipY = this.flipY;
  6687. texture.unpackAlignment = this.unpackAlignment;
  6688. return texture;
  6689. },
  6690. deallocate: function () {
  6691. var index = THREE.TextureLibrary.indexOf( this );
  6692. if ( index !== -1 ) THREE.TextureLibrary.splice( index, 1 );
  6693. }
  6694. };
  6695. THREE.TextureIdCount = 0;
  6696. THREE.TextureLibrary = [];
  6697. /**
  6698. * @author alteredq / http://alteredqualia.com/
  6699. */
  6700. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  6701. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  6702. this.image = { width: width, height: height };
  6703. this.mipmaps = mipmaps;
  6704. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  6705. };
  6706. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  6707. THREE.CompressedTexture.prototype.clone = function () {
  6708. var texture = new THREE.CompressedTexture();
  6709. THREE.Texture.prototype.clone.call( this, texture );
  6710. return texture;
  6711. };
  6712. /**
  6713. * @author alteredq / http://alteredqualia.com/
  6714. */
  6715. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  6716. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  6717. this.image = { data: data, width: width, height: height };
  6718. };
  6719. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  6720. THREE.DataTexture.prototype.clone = function () {
  6721. var texture = new THREE.DataTexture();
  6722. THREE.Texture.prototype.clone.call( this, texture );
  6723. return texture;
  6724. };
  6725. /**
  6726. * @author mrdoob / http://mrdoob.com/
  6727. */
  6728. THREE.Particle = function ( material ) {
  6729. THREE.Object3D.call( this );
  6730. this.material = material;
  6731. };
  6732. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  6733. THREE.Particle.prototype.clone = function ( object ) {
  6734. if ( object === undefined ) object = new THREE.Particle( this.material );
  6735. THREE.Object3D.prototype.clone.call( this, object );
  6736. return object;
  6737. };
  6738. /**
  6739. * @author alteredq / http://alteredqualia.com/
  6740. */
  6741. THREE.ParticleSystem = function ( geometry, material ) {
  6742. THREE.Object3D.call( this );
  6743. this.geometry = geometry;
  6744. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  6745. this.sortParticles = false;
  6746. if ( this.geometry ) {
  6747. // calc bound radius
  6748. if( this.geometry.boundingSphere === null ) {
  6749. this.geometry.computeBoundingSphere();
  6750. }
  6751. this.boundRadius = geometry.boundingSphere.radius;
  6752. }
  6753. this.frustumCulled = false;
  6754. };
  6755. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  6756. THREE.ParticleSystem.prototype.clone = function ( object ) {
  6757. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  6758. object.sortParticles = this.sortParticles;
  6759. THREE.Object3D.prototype.clone.call( this, object );
  6760. return object;
  6761. };
  6762. /**
  6763. * @author mrdoob / http://mrdoob.com/
  6764. */
  6765. THREE.Line = function ( geometry, material, type ) {
  6766. THREE.Object3D.call( this );
  6767. this.geometry = geometry;
  6768. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  6769. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  6770. if ( this.geometry ) {
  6771. if ( ! this.geometry.boundingSphere ) {
  6772. this.geometry.computeBoundingSphere();
  6773. }
  6774. }
  6775. };
  6776. THREE.LineStrip = 0;
  6777. THREE.LinePieces = 1;
  6778. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  6779. THREE.Line.prototype.clone = function ( object ) {
  6780. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  6781. THREE.Object3D.prototype.clone.call( this, object );
  6782. return object;
  6783. };
  6784. /**
  6785. * @author mrdoob / http://mrdoob.com/
  6786. * @author alteredq / http://alteredqualia.com/
  6787. * @author mikael emtinger / http://gomo.se/
  6788. */
  6789. THREE.Mesh = function ( geometry, material ) {
  6790. THREE.Object3D.call( this );
  6791. this.geometry = geometry;
  6792. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  6793. if ( this.geometry ) {
  6794. // calc bound radius
  6795. if ( this.geometry.boundingSphere === null ) {
  6796. this.geometry.computeBoundingSphere();
  6797. }
  6798. this.boundRadius = geometry.boundingSphere.radius;
  6799. // setup morph targets
  6800. if ( this.geometry.morphTargets.length ) {
  6801. this.morphTargetBase = -1;
  6802. this.morphTargetForcedOrder = [];
  6803. this.morphTargetInfluences = [];
  6804. this.morphTargetDictionary = {};
  6805. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  6806. this.morphTargetInfluences.push( 0 );
  6807. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  6808. }
  6809. }
  6810. }
  6811. }
  6812. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  6813. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  6814. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  6815. return this.morphTargetDictionary[ name ];
  6816. }
  6817. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  6818. return 0;
  6819. };
  6820. THREE.Mesh.prototype.clone = function ( object ) {
  6821. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  6822. THREE.Object3D.prototype.clone.call( this, object );
  6823. return object;
  6824. };
  6825. /**
  6826. * @author mikael emtinger / http://gomo.se/
  6827. * @author alteredq / http://alteredqualia.com/
  6828. */
  6829. THREE.Bone = function( belongsToSkin ) {
  6830. THREE.Object3D.call( this );
  6831. this.skin = belongsToSkin;
  6832. this.skinMatrix = new THREE.Matrix4();
  6833. };
  6834. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  6835. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  6836. // update local
  6837. if ( this.matrixAutoUpdate ) {
  6838. forceUpdate |= this.updateMatrix();
  6839. }
  6840. // update skin matrix
  6841. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  6842. if( parentSkinMatrix ) {
  6843. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  6844. } else {
  6845. this.skinMatrix.copy( this.matrix );
  6846. }
  6847. this.matrixWorldNeedsUpdate = false;
  6848. forceUpdate = true;
  6849. }
  6850. // update children
  6851. var child, i, l = this.children.length;
  6852. for ( i = 0; i < l; i ++ ) {
  6853. this.children[ i ].update( this.skinMatrix, forceUpdate );
  6854. }
  6855. };
  6856. /**
  6857. * @author mikael emtinger / http://gomo.se/
  6858. * @author alteredq / http://alteredqualia.com/
  6859. */
  6860. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  6861. THREE.Mesh.call( this, geometry, material );
  6862. //
  6863. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  6864. // init bones
  6865. this.identityMatrix = new THREE.Matrix4();
  6866. this.bones = [];
  6867. this.boneMatrices = [];
  6868. var b, bone, gbone, p, q, s;
  6869. if ( this.geometry && this.geometry.bones !== undefined ) {
  6870. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  6871. gbone = this.geometry.bones[ b ];
  6872. p = gbone.pos;
  6873. q = gbone.rotq;
  6874. s = gbone.scl;
  6875. bone = this.addBone();
  6876. bone.name = gbone.name;
  6877. bone.position.set( p[0], p[1], p[2] );
  6878. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  6879. bone.useQuaternion = true;
  6880. if ( s !== undefined ) {
  6881. bone.scale.set( s[0], s[1], s[2] );
  6882. } else {
  6883. bone.scale.set( 1, 1, 1 );
  6884. }
  6885. }
  6886. for ( b = 0; b < this.bones.length; b ++ ) {
  6887. gbone = this.geometry.bones[ b ];
  6888. bone = this.bones[ b ];
  6889. if ( gbone.parent === -1 ) {
  6890. this.add( bone );
  6891. } else {
  6892. this.bones[ gbone.parent ].add( bone );
  6893. }
  6894. }
  6895. //
  6896. var nBones = this.bones.length;
  6897. if ( this.useVertexTexture ) {
  6898. // layout (1 matrix = 4 pixels)
  6899. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  6900. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  6901. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  6902. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  6903. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  6904. var size;
  6905. if ( nBones > 256 )
  6906. size = 64;
  6907. else if ( nBones > 64 )
  6908. size = 32;
  6909. else if ( nBones > 16 )
  6910. size = 16;
  6911. else
  6912. size = 8;
  6913. this.boneTextureWidth = size;
  6914. this.boneTextureHeight = size;
  6915. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  6916. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  6917. this.boneTexture.minFilter = THREE.NearestFilter;
  6918. this.boneTexture.magFilter = THREE.NearestFilter;
  6919. this.boneTexture.generateMipmaps = false;
  6920. this.boneTexture.flipY = false;
  6921. } else {
  6922. this.boneMatrices = new Float32Array( 16 * nBones );
  6923. }
  6924. this.pose();
  6925. }
  6926. };
  6927. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  6928. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  6929. if ( bone === undefined ) {
  6930. bone = new THREE.Bone( this );
  6931. }
  6932. this.bones.push( bone );
  6933. return bone;
  6934. };
  6935. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  6936. this.matrixAutoUpdate && this.updateMatrix();
  6937. // update matrixWorld
  6938. if ( this.matrixWorldNeedsUpdate || force ) {
  6939. if ( this.parent ) {
  6940. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  6941. } else {
  6942. this.matrixWorld.copy( this.matrix );
  6943. }
  6944. this.matrixWorldNeedsUpdate = false;
  6945. force = true;
  6946. }
  6947. // update children
  6948. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6949. var child = this.children[ i ];
  6950. if ( child instanceof THREE.Bone ) {
  6951. child.update( this.identityMatrix, false );
  6952. } else {
  6953. child.updateMatrixWorld( true );
  6954. }
  6955. }
  6956. // make a snapshot of the bones' rest position
  6957. if ( this.boneInverses == undefined ) {
  6958. this.boneInverses = [];
  6959. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6960. var inverse = new THREE.Matrix4();
  6961. inverse.getInverse( this.bones[ b ].skinMatrix );
  6962. this.boneInverses.push( inverse );
  6963. }
  6964. }
  6965. // flatten bone matrices to array
  6966. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6967. // compute the offset between the current and the original transform;
  6968. //TODO: we could get rid of this multiplication step if the skinMatrix
  6969. // was already representing the offset; however, this requires some
  6970. // major changes to the animation system
  6971. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  6972. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  6973. }
  6974. if ( this.useVertexTexture ) {
  6975. this.boneTexture.needsUpdate = true;
  6976. }
  6977. };
  6978. THREE.SkinnedMesh.prototype.pose = function() {
  6979. this.updateMatrixWorld( true );
  6980. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  6981. // normalize weights
  6982. var sw = this.geometry.skinWeights[ i ];
  6983. var scale = 1.0 / sw.lengthManhattan();
  6984. if ( scale !== Infinity ) {
  6985. sw.multiplyScalar( scale );
  6986. } else {
  6987. sw.set( 1 ); // this will be normalized by the shader anyway
  6988. }
  6989. }
  6990. };
  6991. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  6992. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  6993. THREE.Mesh.prototype.clone.call( this, object );
  6994. return object;
  6995. };
  6996. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  6997. /**
  6998. * @author alteredq / http://alteredqualia.com/
  6999. */
  7000. THREE.MorphAnimMesh = function ( geometry, material ) {
  7001. THREE.Mesh.call( this, geometry, material );
  7002. // API
  7003. this.duration = 1000; // milliseconds
  7004. this.mirroredLoop = false;
  7005. this.time = 0;
  7006. // internals
  7007. this.lastKeyframe = 0;
  7008. this.currentKeyframe = 0;
  7009. this.direction = 1;
  7010. this.directionBackwards = false;
  7011. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7012. };
  7013. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7014. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7015. this.startKeyframe = start;
  7016. this.endKeyframe = end;
  7017. this.length = this.endKeyframe - this.startKeyframe + 1;
  7018. };
  7019. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7020. this.direction = 1;
  7021. this.directionBackwards = false;
  7022. };
  7023. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7024. this.direction = -1;
  7025. this.directionBackwards = true;
  7026. };
  7027. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7028. var geometry = this.geometry;
  7029. if ( ! geometry.animations ) geometry.animations = {};
  7030. var firstAnimation, animations = geometry.animations;
  7031. var pattern = /([a-z]+)(\d+)/;
  7032. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7033. var morph = geometry.morphTargets[ i ];
  7034. var parts = morph.name.match( pattern );
  7035. if ( parts && parts.length > 1 ) {
  7036. var label = parts[ 1 ];
  7037. var num = parts[ 2 ];
  7038. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7039. var animation = animations[ label ];
  7040. if ( i < animation.start ) animation.start = i;
  7041. if ( i > animation.end ) animation.end = i;
  7042. if ( ! firstAnimation ) firstAnimation = label;
  7043. }
  7044. }
  7045. geometry.firstAnimation = firstAnimation;
  7046. };
  7047. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7048. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7049. this.geometry.animations[ label ] = { start: start, end: end };
  7050. };
  7051. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7052. var animation = this.geometry.animations[ label ];
  7053. if ( animation ) {
  7054. this.setFrameRange( animation.start, animation.end );
  7055. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7056. this.time = 0;
  7057. } else {
  7058. console.warn( "animation[" + label + "] undefined" );
  7059. }
  7060. };
  7061. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7062. var frameTime = this.duration / this.length;
  7063. this.time += this.direction * delta;
  7064. if ( this.mirroredLoop ) {
  7065. if ( this.time > this.duration || this.time < 0 ) {
  7066. this.direction *= -1;
  7067. if ( this.time > this.duration ) {
  7068. this.time = this.duration;
  7069. this.directionBackwards = true;
  7070. }
  7071. if ( this.time < 0 ) {
  7072. this.time = 0;
  7073. this.directionBackwards = false;
  7074. }
  7075. }
  7076. } else {
  7077. this.time = this.time % this.duration;
  7078. if ( this.time < 0 ) this.time += this.duration;
  7079. }
  7080. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7081. if ( keyframe !== this.currentKeyframe ) {
  7082. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7083. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7084. this.morphTargetInfluences[ keyframe ] = 0;
  7085. this.lastKeyframe = this.currentKeyframe;
  7086. this.currentKeyframe = keyframe;
  7087. }
  7088. var mix = ( this.time % frameTime ) / frameTime;
  7089. if ( this.directionBackwards ) {
  7090. mix = 1 - mix;
  7091. }
  7092. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7093. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7094. };
  7095. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7096. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7097. object.duration = this.duration;
  7098. object.mirroredLoop = this.mirroredLoop;
  7099. object.time = this.time;
  7100. object.lastKeyframe = this.lastKeyframe;
  7101. object.currentKeyframe = this.currentKeyframe;
  7102. object.direction = this.direction;
  7103. object.directionBackwards = this.directionBackwards;
  7104. THREE.Mesh.prototype.clone.call( this, object );
  7105. return object;
  7106. };
  7107. /**
  7108. * @author alteredq / http://alteredqualia.com/
  7109. */
  7110. THREE.Ribbon = function ( geometry, material ) {
  7111. THREE.Object3D.call( this );
  7112. this.geometry = geometry;
  7113. this.material = material;
  7114. };
  7115. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7116. THREE.Ribbon.prototype.clone = function ( object ) {
  7117. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7118. THREE.Object3D.prototype.clone.call( this, object );
  7119. return object;
  7120. };
  7121. /**
  7122. * @author mikael emtinger / http://gomo.se/
  7123. * @author alteredq / http://alteredqualia.com/
  7124. * @author mrdoob / http://mrdoob.com/
  7125. */
  7126. THREE.LOD = function () {
  7127. THREE.Object3D.call( this );
  7128. this.LODs = [];
  7129. };
  7130. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7131. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7132. if ( visibleAtDistance === undefined ) {
  7133. visibleAtDistance = 0;
  7134. }
  7135. visibleAtDistance = Math.abs( visibleAtDistance );
  7136. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7137. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7138. break;
  7139. }
  7140. }
  7141. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7142. this.add( object3D );
  7143. };
  7144. THREE.LOD.prototype.update = function ( camera ) {
  7145. if ( this.LODs.length > 1 ) {
  7146. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7147. var inverse = camera.matrixWorldInverse;
  7148. 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] );
  7149. this.LODs[ 0 ].object3D.visible = true;
  7150. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7151. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7152. this.LODs[ l - 1 ].object3D.visible = false;
  7153. this.LODs[ l ].object3D.visible = true;
  7154. } else {
  7155. break;
  7156. }
  7157. }
  7158. for( ; l < this.LODs.length; l ++ ) {
  7159. this.LODs[ l ].object3D.visible = false;
  7160. }
  7161. }
  7162. };
  7163. THREE.LOD.prototype.clone = function () {
  7164. // TODO
  7165. };
  7166. /**
  7167. * @author mikael emtinger / http://gomo.se/
  7168. * @author alteredq / http://alteredqualia.com/
  7169. */
  7170. THREE.Sprite = function ( material ) {
  7171. THREE.Object3D.call( this );
  7172. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7173. this.rotation3d = this.rotation;
  7174. this.rotation = 0;
  7175. };
  7176. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7177. /*
  7178. * Custom update matrix
  7179. */
  7180. THREE.Sprite.prototype.updateMatrix = function () {
  7181. this.matrix.setPosition( this.position );
  7182. this.rotation3d.set( 0, 0, this.rotation );
  7183. this.matrix.setRotationFromEuler( this.rotation3d );
  7184. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7185. this.matrix.scale( this.scale );
  7186. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  7187. }
  7188. this.matrixWorldNeedsUpdate = true;
  7189. };
  7190. THREE.Sprite.prototype.clone = function ( object ) {
  7191. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7192. THREE.Object3D.prototype.clone.call( this, object );
  7193. return object;
  7194. };
  7195. /**
  7196. * @author mrdoob / http://mrdoob.com/
  7197. */
  7198. THREE.Scene = function () {
  7199. THREE.Object3D.call( this );
  7200. this.fog = null;
  7201. this.overrideMaterial = null;
  7202. this.matrixAutoUpdate = false;
  7203. this.__objects = [];
  7204. this.__lights = [];
  7205. this.__objectsAdded = [];
  7206. this.__objectsRemoved = [];
  7207. };
  7208. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7209. THREE.Scene.prototype.__addObject = function ( object ) {
  7210. if ( object instanceof THREE.Light ) {
  7211. if ( this.__lights.indexOf( object ) === - 1 ) {
  7212. this.__lights.push( object );
  7213. }
  7214. if ( object.target && object.target.parent === undefined ) {
  7215. this.add( object.target );
  7216. }
  7217. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7218. if ( this.__objects.indexOf( object ) === - 1 ) {
  7219. this.__objects.push( object );
  7220. this.__objectsAdded.push( object );
  7221. // check if previously removed
  7222. var i = this.__objectsRemoved.indexOf( object );
  7223. if ( i !== -1 ) {
  7224. this.__objectsRemoved.splice( i, 1 );
  7225. }
  7226. }
  7227. }
  7228. for ( var c = 0; c < object.children.length; c ++ ) {
  7229. this.__addObject( object.children[ c ] );
  7230. }
  7231. };
  7232. THREE.Scene.prototype.__removeObject = function ( object ) {
  7233. if ( object instanceof THREE.Light ) {
  7234. var i = this.__lights.indexOf( object );
  7235. if ( i !== -1 ) {
  7236. this.__lights.splice( i, 1 );
  7237. }
  7238. } else if ( !( object instanceof THREE.Camera ) ) {
  7239. var i = this.__objects.indexOf( object );
  7240. if( i !== -1 ) {
  7241. this.__objects.splice( i, 1 );
  7242. this.__objectsRemoved.push( object );
  7243. // check if previously added
  7244. var ai = this.__objectsAdded.indexOf( object );
  7245. if ( ai !== -1 ) {
  7246. this.__objectsAdded.splice( ai, 1 );
  7247. }
  7248. }
  7249. }
  7250. for ( var c = 0; c < object.children.length; c ++ ) {
  7251. this.__removeObject( object.children[ c ] );
  7252. }
  7253. };
  7254. /**
  7255. * @author mrdoob / http://mrdoob.com/
  7256. * @author alteredq / http://alteredqualia.com/
  7257. */
  7258. THREE.Fog = function ( hex, near, far ) {
  7259. this.name = '';
  7260. this.color = new THREE.Color( hex );
  7261. this.near = ( near !== undefined ) ? near : 1;
  7262. this.far = ( far !== undefined ) ? far : 1000;
  7263. };
  7264. THREE.Fog.prototype.clone = function () {
  7265. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7266. };
  7267. /**
  7268. * @author mrdoob / http://mrdoob.com/
  7269. * @author alteredq / http://alteredqualia.com/
  7270. */
  7271. THREE.FogExp2 = function ( hex, density ) {
  7272. this.name = '';
  7273. this.color = new THREE.Color( hex );
  7274. this.density = ( density !== undefined ) ? density : 0.00025;
  7275. };
  7276. THREE.FogExp2.prototype.clone = function () {
  7277. return new THREE.FogExp2( this.color.getHex(), this.density );
  7278. };
  7279. /**
  7280. * @author mrdoob / http://mrdoob.com/
  7281. */
  7282. THREE.CanvasRenderer = function ( parameters ) {
  7283. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7284. parameters = parameters || {};
  7285. var _this = this,
  7286. _renderData, _elements, _lights,
  7287. _projector = new THREE.Projector(),
  7288. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  7289. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7290. _context = _canvas.getContext( '2d' ),
  7291. _clearColor = new THREE.Color( 0x000000 ),
  7292. _clearOpacity = 0,
  7293. _contextGlobalAlpha = 1,
  7294. _contextGlobalCompositeOperation = 0,
  7295. _contextStrokeStyle = null,
  7296. _contextFillStyle = null,
  7297. _contextLineWidth = null,
  7298. _contextLineCap = null,
  7299. _contextLineJoin = null,
  7300. _v1, _v2, _v3, _v4,
  7301. _v5 = new THREE.RenderableVertex(),
  7302. _v6 = new THREE.RenderableVertex(),
  7303. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7304. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7305. _color = new THREE.Color(),
  7306. _color1 = new THREE.Color(),
  7307. _color2 = new THREE.Color(),
  7308. _color3 = new THREE.Color(),
  7309. _color4 = new THREE.Color(),
  7310. _diffuseColor = new THREE.Color(),
  7311. _emissiveColor = new THREE.Color(),
  7312. _patterns = {}, _imagedatas = {},
  7313. _near, _far,
  7314. _image, _uvs,
  7315. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7316. _clipRect = new THREE.Rectangle(),
  7317. _clearRect = new THREE.Rectangle(),
  7318. _bboxRect = new THREE.Rectangle(),
  7319. _enableLighting = false,
  7320. _ambientLight = new THREE.Color(),
  7321. _directionalLights = new THREE.Color(),
  7322. _pointLights = new THREE.Color(),
  7323. _pi2 = Math.PI * 2,
  7324. _vector3 = new THREE.Vector3(), // Needed for PointLight
  7325. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  7326. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  7327. _pixelMap = document.createElement( 'canvas' );
  7328. _pixelMap.width = _pixelMap.height = 2;
  7329. _pixelMapContext = _pixelMap.getContext( '2d' );
  7330. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  7331. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  7332. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  7333. _pixelMapData = _pixelMapImage.data;
  7334. _gradientMap = document.createElement( 'canvas' );
  7335. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  7336. _gradientMapContext = _gradientMap.getContext( '2d' );
  7337. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  7338. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  7339. _gradientMapQuality --; // Fix UVs
  7340. this.domElement = _canvas;
  7341. this.autoClear = true;
  7342. this.sortObjects = true;
  7343. this.sortElements = true;
  7344. this.info = {
  7345. render: {
  7346. vertices: 0,
  7347. faces: 0
  7348. }
  7349. }
  7350. this.setSize = function ( width, height ) {
  7351. _canvasWidth = width;
  7352. _canvasHeight = height;
  7353. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  7354. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  7355. _canvas.width = _canvasWidth;
  7356. _canvas.height = _canvasHeight;
  7357. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7358. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7359. _contextGlobalAlpha = 1;
  7360. _contextGlobalCompositeOperation = 0;
  7361. _contextStrokeStyle = null;
  7362. _contextFillStyle = null;
  7363. _contextLineWidth = null;
  7364. _contextLineCap = null;
  7365. _contextLineJoin = null;
  7366. };
  7367. this.setClearColor = function ( color, opacity ) {
  7368. _clearColor.copy( color );
  7369. _clearOpacity = opacity !== undefined ? opacity : 1;
  7370. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7371. };
  7372. this.setClearColorHex = function ( hex, opacity ) {
  7373. _clearColor.setHex( hex );
  7374. _clearOpacity = opacity !== undefined ? opacity : 1;
  7375. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7376. };
  7377. this.getMaxAnisotropy = function () {
  7378. return 0;
  7379. };
  7380. this.clear = function () {
  7381. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7382. if ( _clearRect.isEmpty() === false ) {
  7383. _clearRect.minSelf( _clipRect );
  7384. _clearRect.inflate( 2 );
  7385. if ( _clearOpacity < 1 ) {
  7386. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7387. }
  7388. if ( _clearOpacity > 0 ) {
  7389. setBlending( THREE.NormalBlending );
  7390. setOpacity( 1 );
  7391. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  7392. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7393. }
  7394. _clearRect.empty();
  7395. }
  7396. };
  7397. this.render = function ( scene, camera ) {
  7398. if ( camera instanceof THREE.Camera === false ) {
  7399. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  7400. return;
  7401. }
  7402. var e, el, element, material;
  7403. this.autoClear === true
  7404. ? this.clear()
  7405. : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7406. _this.info.render.vertices = 0;
  7407. _this.info.render.faces = 0;
  7408. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  7409. _elements = _renderData.elements;
  7410. _lights = _renderData.lights;
  7411. /* DEBUG
  7412. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  7413. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  7414. */
  7415. _enableLighting = _lights.length > 0;
  7416. if ( _enableLighting === true ) {
  7417. calculateLights();
  7418. }
  7419. for ( e = 0, el = _elements.length; e < el; e++ ) {
  7420. element = _elements[ e ];
  7421. material = element.material;
  7422. if ( material === undefined || material.visible === false ) continue;
  7423. _bboxRect.empty();
  7424. if ( element instanceof THREE.RenderableParticle ) {
  7425. _v1 = element;
  7426. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  7427. renderParticle( _v1, element, material, scene );
  7428. } else if ( element instanceof THREE.RenderableLine ) {
  7429. _v1 = element.v1; _v2 = element.v2;
  7430. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7431. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7432. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7433. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7434. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7435. renderLine( _v1, _v2, element, material, scene );
  7436. }
  7437. } else if ( element instanceof THREE.RenderableFace3 ) {
  7438. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  7439. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7440. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7441. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7442. if ( material.overdraw === true ) {
  7443. expand( _v1.positionScreen, _v2.positionScreen );
  7444. expand( _v2.positionScreen, _v3.positionScreen );
  7445. expand( _v3.positionScreen, _v1.positionScreen );
  7446. }
  7447. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  7448. _v2.positionScreen.x, _v2.positionScreen.y,
  7449. _v3.positionScreen.x, _v3.positionScreen.y );
  7450. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7451. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  7452. }
  7453. } else if ( element instanceof THREE.RenderableFace4 ) {
  7454. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  7455. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7456. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7457. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7458. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  7459. _v5.positionScreen.copy( _v2.positionScreen );
  7460. _v6.positionScreen.copy( _v4.positionScreen );
  7461. if ( material.overdraw === true ) {
  7462. expand( _v1.positionScreen, _v2.positionScreen );
  7463. expand( _v2.positionScreen, _v4.positionScreen );
  7464. expand( _v4.positionScreen, _v1.positionScreen );
  7465. expand( _v3.positionScreen, _v5.positionScreen );
  7466. expand( _v3.positionScreen, _v6.positionScreen );
  7467. }
  7468. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7469. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7470. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  7471. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  7472. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7473. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  7474. }
  7475. }
  7476. /* DEBUG
  7477. _context.lineWidth = 1;
  7478. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  7479. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  7480. */
  7481. _clearRect.addRectangle( _bboxRect );
  7482. }
  7483. /* DEBUG
  7484. _context.lineWidth = 1;
  7485. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  7486. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  7487. */
  7488. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  7489. //
  7490. function calculateLights() {
  7491. _ambientLight.setRGB( 0, 0, 0 );
  7492. _directionalLights.setRGB( 0, 0, 0 );
  7493. _pointLights.setRGB( 0, 0, 0 );
  7494. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7495. var light = _lights[ l ];
  7496. var lightColor = light.color;
  7497. if ( light instanceof THREE.AmbientLight ) {
  7498. _ambientLight.r += lightColor.r;
  7499. _ambientLight.g += lightColor.g;
  7500. _ambientLight.b += lightColor.b;
  7501. } else if ( light instanceof THREE.DirectionalLight ) {
  7502. // for particles
  7503. _directionalLights.r += lightColor.r;
  7504. _directionalLights.g += lightColor.g;
  7505. _directionalLights.b += lightColor.b;
  7506. } else if ( light instanceof THREE.PointLight ) {
  7507. // for particles
  7508. _pointLights.r += lightColor.r;
  7509. _pointLights.g += lightColor.g;
  7510. _pointLights.b += lightColor.b;
  7511. }
  7512. }
  7513. }
  7514. function calculateLight( position, normal, color ) {
  7515. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7516. var light = _lights[ l ];
  7517. var lightColor = light.color;
  7518. if ( light instanceof THREE.DirectionalLight ) {
  7519. var lightPosition = light.matrixWorld.getPosition().normalize();
  7520. var amount = normal.dot( lightPosition );
  7521. if ( amount <= 0 ) continue;
  7522. amount *= light.intensity;
  7523. color.r += lightColor.r * amount;
  7524. color.g += lightColor.g * amount;
  7525. color.b += lightColor.b * amount;
  7526. } else if ( light instanceof THREE.PointLight ) {
  7527. var lightPosition = light.matrixWorld.getPosition();
  7528. var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  7529. if ( amount <= 0 ) continue;
  7530. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  7531. if ( amount == 0 ) continue;
  7532. amount *= light.intensity;
  7533. color.r += lightColor.r * amount;
  7534. color.g += lightColor.g * amount;
  7535. color.b += lightColor.b * amount;
  7536. }
  7537. }
  7538. }
  7539. function renderParticle( v1, element, material, scene ) {
  7540. setOpacity( material.opacity );
  7541. setBlending( material.blending );
  7542. var width, height, scaleX, scaleY,
  7543. bitmap, bitmapWidth, bitmapHeight;
  7544. if ( material instanceof THREE.ParticleBasicMaterial ) {
  7545. if ( material.map === null ) {
  7546. scaleX = element.object.scale.x;
  7547. scaleY = element.object.scale.y;
  7548. // TODO: Be able to disable this
  7549. scaleX *= element.scale.x * _canvasWidthHalf;
  7550. scaleY *= element.scale.y * _canvasHeightHalf;
  7551. _bboxRect.set( v1.x - scaleX, v1.y - scaleY, v1.x + scaleX, v1.y + scaleY );
  7552. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7553. return;
  7554. }
  7555. setFillStyle( material.color.getStyle() );
  7556. _context.save();
  7557. _context.translate( v1.x, v1.y );
  7558. _context.rotate( - element.rotation );
  7559. _context.scale( scaleX, scaleY );
  7560. _context.fillRect( -1, -1, 2, 2 );
  7561. _context.restore();
  7562. } else {
  7563. bitmap = material.map.image;
  7564. bitmapWidth = bitmap.width >> 1;
  7565. bitmapHeight = bitmap.height >> 1;
  7566. scaleX = element.scale.x * _canvasWidthHalf;
  7567. scaleY = element.scale.y * _canvasHeightHalf;
  7568. width = scaleX * bitmapWidth;
  7569. height = scaleY * bitmapHeight;
  7570. // TODO: Rotations break this...
  7571. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7572. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7573. return;
  7574. }
  7575. _context.save();
  7576. _context.translate( v1.x, v1.y );
  7577. _context.rotate( - element.rotation );
  7578. _context.scale( scaleX, - scaleY );
  7579. _context.translate( - bitmapWidth, - bitmapHeight );
  7580. _context.drawImage( bitmap, 0, 0 );
  7581. _context.restore();
  7582. }
  7583. /* DEBUG
  7584. setStrokeStyle( 'rgb(255,255,0)' );
  7585. _context.beginPath();
  7586. _context.moveTo( v1.x - 10, v1.y );
  7587. _context.lineTo( v1.x + 10, v1.y );
  7588. _context.moveTo( v1.x, v1.y - 10 );
  7589. _context.lineTo( v1.x, v1.y + 10 );
  7590. _context.stroke();
  7591. */
  7592. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  7593. width = element.scale.x * _canvasWidthHalf;
  7594. height = element.scale.y * _canvasHeightHalf;
  7595. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7596. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7597. return;
  7598. }
  7599. setStrokeStyle( material.color.getStyle() );
  7600. setFillStyle( material.color.getStyle() );
  7601. _context.save();
  7602. _context.translate( v1.x, v1.y );
  7603. _context.rotate( - element.rotation );
  7604. _context.scale( width, height );
  7605. material.program( _context );
  7606. _context.restore();
  7607. }
  7608. }
  7609. function renderLine( v1, v2, element, material, scene ) {
  7610. setOpacity( material.opacity );
  7611. setBlending( material.blending );
  7612. _context.beginPath();
  7613. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  7614. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  7615. if ( material instanceof THREE.LineBasicMaterial ) {
  7616. setLineWidth( material.linewidth );
  7617. setLineCap( material.linecap );
  7618. setLineJoin( material.linejoin );
  7619. setStrokeStyle( material.color.getStyle() );
  7620. _context.stroke();
  7621. _bboxRect.inflate( material.linewidth * 2 );
  7622. }
  7623. }
  7624. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  7625. _this.info.render.vertices += 3;
  7626. _this.info.render.faces ++;
  7627. setOpacity( material.opacity );
  7628. setBlending( material.blending );
  7629. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7630. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7631. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7632. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  7633. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  7634. _diffuseColor.copy( material.color );
  7635. _emissiveColor.copy( material.emissive );
  7636. if ( material.vertexColors === THREE.FaceColors ) {
  7637. _diffuseColor.r *= element.color.r;
  7638. _diffuseColor.g *= element.color.g;
  7639. _diffuseColor.b *= element.color.b;
  7640. }
  7641. if ( _enableLighting === true ) {
  7642. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  7643. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  7644. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  7645. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  7646. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7647. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7648. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  7649. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7650. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7651. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7652. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7653. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7654. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7655. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7656. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7657. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7658. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7659. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7660. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7661. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7662. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7663. } else {
  7664. _color.r = _ambientLight.r;
  7665. _color.g = _ambientLight.g;
  7666. _color.b = _ambientLight.b;
  7667. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7668. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7669. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7670. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7671. material.wireframe === true
  7672. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7673. : fillPath( _color );
  7674. }
  7675. } else {
  7676. material.wireframe === true
  7677. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7678. : fillPath( material.color );
  7679. }
  7680. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7681. if ( material.map !== null ) {
  7682. if ( material.map.mapping instanceof THREE.UVMapping ) {
  7683. _uvs = element.uvs[ 0 ];
  7684. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].u, _uvs[ uv1 ].v, _uvs[ uv2 ].u, _uvs[ uv2 ].v, _uvs[ uv3 ].u, _uvs[ uv3 ].v, material.map );
  7685. }
  7686. } else if ( material.envMap !== null ) {
  7687. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  7688. var cameraMatrix = camera.matrixWorldInverse;
  7689. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  7690. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7691. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7692. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  7693. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7694. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7695. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  7696. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7697. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7698. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  7699. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  7700. }*/
  7701. } else {
  7702. _color.copy( material.color );
  7703. if ( material.vertexColors === THREE.FaceColors ) {
  7704. _color.r *= element.color.r;
  7705. _color.g *= element.color.g;
  7706. _color.b *= element.color.b;
  7707. }
  7708. material.wireframe === true
  7709. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7710. : fillPath( _color );
  7711. }
  7712. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7713. _near = camera.near;
  7714. _far = camera.far;
  7715. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7716. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7717. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7718. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7719. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7720. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7721. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7722. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7723. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7724. _color.r = normalToComponent( element.normalWorld.x );
  7725. _color.g = normalToComponent( element.normalWorld.y );
  7726. _color.b = normalToComponent( element.normalWorld.z );
  7727. material.wireframe === true
  7728. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7729. : fillPath( _color );
  7730. }
  7731. }
  7732. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  7733. _this.info.render.vertices += 4;
  7734. _this.info.render.faces ++;
  7735. setOpacity( material.opacity );
  7736. setBlending( material.blending );
  7737. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  7738. // Let renderFace3() handle this
  7739. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  7740. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  7741. return;
  7742. }
  7743. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7744. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7745. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7746. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  7747. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  7748. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  7749. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7750. _diffuseColor.copy( material.color );
  7751. _emissiveColor.copy( material.emissive );
  7752. if ( material.vertexColors === THREE.FaceColors ) {
  7753. _diffuseColor.r *= element.color.r;
  7754. _diffuseColor.g *= element.color.g;
  7755. _diffuseColor.b *= element.color.b;
  7756. }
  7757. if ( _enableLighting === true ) {
  7758. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  7759. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  7760. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  7761. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  7762. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7763. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7764. calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  7765. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  7766. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7767. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7768. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7769. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7770. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7771. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7772. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7773. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7774. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7775. _color4.r = _color4.r * _diffuseColor.r + _emissiveColor.r;
  7776. _color4.g = _color4.g * _diffuseColor.g + _emissiveColor.g;
  7777. _color4.b = _color4.b * _diffuseColor.b + _emissiveColor.b;
  7778. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7779. // TODO: UVs are incorrect, v4->v3?
  7780. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7781. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7782. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7783. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7784. } else {
  7785. _color.r = _ambientLight.r;
  7786. _color.g = _ambientLight.g;
  7787. _color.b = _ambientLight.b;
  7788. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7789. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7790. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7791. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7792. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7793. material.wireframe === true
  7794. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7795. : fillPath( _color );
  7796. }
  7797. } else {
  7798. _color.r = _diffuseColor.r + _emissiveColor.r;
  7799. _color.g = _diffuseColor.g + _emissiveColor.g;
  7800. _color.b = _diffuseColor.b + _emissiveColor.b;
  7801. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7802. material.wireframe === true
  7803. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7804. : fillPath( _color );
  7805. }
  7806. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  7807. _color.copy( material.color );
  7808. if ( material.vertexColors === THREE.FaceColors ) {
  7809. _color.r *= element.color.r;
  7810. _color.g *= element.color.g;
  7811. _color.b *= element.color.b;
  7812. }
  7813. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7814. material.wireframe === true
  7815. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7816. : fillPath( _color );
  7817. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7818. _color.r = normalToComponent( element.normalWorld.x );
  7819. _color.g = normalToComponent( element.normalWorld.y );
  7820. _color.b = normalToComponent( element.normalWorld.z );
  7821. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7822. material.wireframe === true
  7823. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7824. : fillPath( _color );
  7825. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7826. _near = camera.near;
  7827. _far = camera.far;
  7828. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7829. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7830. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  7831. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7832. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7833. // TODO: UVs are incorrect, v4->v3?
  7834. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7835. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7836. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7837. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7838. }
  7839. }
  7840. //
  7841. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  7842. _context.beginPath();
  7843. _context.moveTo( x0, y0 );
  7844. _context.lineTo( x1, y1 );
  7845. _context.lineTo( x2, y2 );
  7846. _context.closePath();
  7847. }
  7848. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  7849. _context.beginPath();
  7850. _context.moveTo( x0, y0 );
  7851. _context.lineTo( x1, y1 );
  7852. _context.lineTo( x2, y2 );
  7853. _context.lineTo( x3, y3 );
  7854. _context.closePath();
  7855. }
  7856. function strokePath( color, linewidth, linecap, linejoin ) {
  7857. setLineWidth( linewidth );
  7858. setLineCap( linecap );
  7859. setLineJoin( linejoin );
  7860. setStrokeStyle( color.getStyle() );
  7861. _context.stroke();
  7862. _bboxRect.inflate( linewidth * 2 );
  7863. }
  7864. function fillPath( color ) {
  7865. setFillStyle( color.getStyle() );
  7866. _context.fill();
  7867. }
  7868. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  7869. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  7870. if ( texture.needsUpdate === true ) {
  7871. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  7872. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  7873. _patterns[ texture.id ] = _context.createPattern(
  7874. texture.image, repeatX === true && repeatY === true
  7875. ? 'repeat'
  7876. : repeatX === true && repeatY === false
  7877. ? 'repeat-x'
  7878. : repeatX === false && repeatY === true
  7879. ? 'repeat-y'
  7880. : 'no-repeat'
  7881. );
  7882. texture.needsUpdate = false;
  7883. }
  7884. _patterns[ texture.id ] === undefined
  7885. ? setFillStyle( 'rgba(0,0,0,1)' )
  7886. : setFillStyle( _patterns[ texture.id ] );
  7887. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7888. var a, b, c, d, e, f, det, idet,
  7889. offsetX = texture.offset.x / texture.repeat.x,
  7890. offsetY = texture.offset.y / texture.repeat.y,
  7891. width = texture.image.width * texture.repeat.x,
  7892. height = texture.image.height * texture.repeat.y;
  7893. u0 = ( u0 + offsetX ) * width;
  7894. v0 = ( 1.0 - v0 + offsetY ) * height;
  7895. u1 = ( u1 + offsetX ) * width;
  7896. v1 = ( 1.0 - v1 + offsetY ) * height;
  7897. u2 = ( u2 + offsetX ) * width;
  7898. v2 = ( 1.0 - v2 + offsetY ) * height;
  7899. x1 -= x0; y1 -= y0;
  7900. x2 -= x0; y2 -= y0;
  7901. u1 -= u0; v1 -= v0;
  7902. u2 -= u0; v2 -= v0;
  7903. det = u1 * v2 - u2 * v1;
  7904. if ( det === 0 ) {
  7905. if ( _imagedatas[ texture.id ] === undefined ) {
  7906. var canvas = document.createElement( 'canvas' )
  7907. canvas.width = texture.image.width;
  7908. canvas.height = texture.image.height;
  7909. var context = canvas.getContext( '2d' );
  7910. context.drawImage( texture.image, 0, 0 );
  7911. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  7912. }
  7913. var data = _imagedatas[ texture.id ];
  7914. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  7915. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  7916. fillPath( _color );
  7917. return;
  7918. }
  7919. idet = 1 / det;
  7920. a = ( v2 * x1 - v1 * x2 ) * idet;
  7921. b = ( v2 * y1 - v1 * y2 ) * idet;
  7922. c = ( u1 * x2 - u2 * x1 ) * idet;
  7923. d = ( u1 * y2 - u2 * y1 ) * idet;
  7924. e = x0 - a * u0 - c * v0;
  7925. f = y0 - b * u0 - d * v0;
  7926. _context.save();
  7927. _context.transform( a, b, c, d, e, f );
  7928. _context.fill();
  7929. _context.restore();
  7930. }
  7931. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  7932. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7933. var a, b, c, d, e, f, det, idet,
  7934. width = image.width - 1,
  7935. height = image.height - 1;
  7936. u0 *= width; v0 *= height;
  7937. u1 *= width; v1 *= height;
  7938. u2 *= width; v2 *= height;
  7939. x1 -= x0; y1 -= y0;
  7940. x2 -= x0; y2 -= y0;
  7941. u1 -= u0; v1 -= v0;
  7942. u2 -= u0; v2 -= v0;
  7943. det = u1 * v2 - u2 * v1;
  7944. idet = 1 / det;
  7945. a = ( v2 * x1 - v1 * x2 ) * idet;
  7946. b = ( v2 * y1 - v1 * y2 ) * idet;
  7947. c = ( u1 * x2 - u2 * x1 ) * idet;
  7948. d = ( u1 * y2 - u2 * y1 ) * idet;
  7949. e = x0 - a * u0 - c * v0;
  7950. f = y0 - b * u0 - d * v0;
  7951. _context.save();
  7952. _context.transform( a, b, c, d, e, f );
  7953. _context.clip();
  7954. _context.drawImage( image, 0, 0 );
  7955. _context.restore();
  7956. }
  7957. function getGradientTexture( color1, color2, color3, color4 ) {
  7958. // http://mrdoob.com/blog/post/710
  7959. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  7960. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  7961. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  7962. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  7963. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  7964. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  7965. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  7966. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  7967. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  7968. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  7969. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  7970. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  7971. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  7972. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  7973. return _gradientMap;
  7974. }
  7975. function smoothstep( value, min, max ) {
  7976. var x = ( value - min ) / ( max - min );
  7977. return x * x * ( 3 - 2 * x );
  7978. }
  7979. function normalToComponent( normal ) {
  7980. var component = ( normal + 1 ) * 0.5;
  7981. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  7982. }
  7983. // Hide anti-alias gaps
  7984. function expand( v1, v2 ) {
  7985. var x = v2.x - v1.x, y = v2.y - v1.y,
  7986. det = x * x + y * y, idet;
  7987. if ( det === 0 ) return;
  7988. idet = 1 / Math.sqrt( det );
  7989. x *= idet; y *= idet;
  7990. v2.x += x; v2.y += y;
  7991. v1.x -= x; v1.y -= y;
  7992. }
  7993. };
  7994. // Context cached methods.
  7995. function setOpacity( value ) {
  7996. if ( _contextGlobalAlpha !== value ) {
  7997. _context.globalAlpha = value;
  7998. _contextGlobalAlpha = value;
  7999. }
  8000. }
  8001. function setBlending( value ) {
  8002. if ( _contextGlobalCompositeOperation !== value ) {
  8003. if ( value === THREE.NormalBlending ) {
  8004. _context.globalCompositeOperation = 'source-over';
  8005. } else if ( value === THREE.AdditiveBlending ) {
  8006. _context.globalCompositeOperation = 'lighter';
  8007. } else if ( value === THREE.SubtractiveBlending ) {
  8008. _context.globalCompositeOperation = 'darker';
  8009. }
  8010. _contextGlobalCompositeOperation = value;
  8011. }
  8012. }
  8013. function setLineWidth( value ) {
  8014. if ( _contextLineWidth !== value ) {
  8015. _context.lineWidth = value;
  8016. _contextLineWidth = value;
  8017. }
  8018. }
  8019. function setLineCap( value ) {
  8020. // "butt", "round", "square"
  8021. if ( _contextLineCap !== value ) {
  8022. _context.lineCap = value;
  8023. _contextLineCap = value;
  8024. }
  8025. }
  8026. function setLineJoin( value ) {
  8027. // "round", "bevel", "miter"
  8028. if ( _contextLineJoin !== value ) {
  8029. _context.lineJoin = value;
  8030. _contextLineJoin = value;
  8031. }
  8032. }
  8033. function setStrokeStyle( value ) {
  8034. if ( _contextStrokeStyle !== value ) {
  8035. _context.strokeStyle = value;
  8036. _contextStrokeStyle = value;
  8037. }
  8038. }
  8039. function setFillStyle( value ) {
  8040. if ( _contextFillStyle !== value ) {
  8041. _context.fillStyle = value;
  8042. _contextFillStyle = value;
  8043. }
  8044. }
  8045. };
  8046. /**
  8047. * @author alteredq / http://alteredqualia.com/
  8048. * @author mrdoob / http://mrdoob.com/
  8049. * @author mikael emtinger / http://gomo.se/
  8050. */
  8051. THREE.ShaderChunk = {
  8052. // FOG
  8053. fog_pars_fragment: [
  8054. "#ifdef USE_FOG",
  8055. "uniform vec3 fogColor;",
  8056. "#ifdef FOG_EXP2",
  8057. "uniform float fogDensity;",
  8058. "#else",
  8059. "uniform float fogNear;",
  8060. "uniform float fogFar;",
  8061. "#endif",
  8062. "#endif"
  8063. ].join("\n"),
  8064. fog_fragment: [
  8065. "#ifdef USE_FOG",
  8066. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8067. "#ifdef FOG_EXP2",
  8068. "const float LOG2 = 1.442695;",
  8069. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8070. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8071. "#else",
  8072. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8073. "#endif",
  8074. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8075. "#endif"
  8076. ].join("\n"),
  8077. // ENVIRONMENT MAP
  8078. envmap_pars_fragment: [
  8079. "#ifdef USE_ENVMAP",
  8080. "uniform float reflectivity;",
  8081. "uniform samplerCube envMap;",
  8082. "uniform float flipEnvMap;",
  8083. "uniform int combine;",
  8084. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8085. "uniform bool useRefract;",
  8086. "uniform float refractionRatio;",
  8087. "#else",
  8088. "varying vec3 vReflect;",
  8089. "#endif",
  8090. "#endif"
  8091. ].join("\n"),
  8092. envmap_fragment: [
  8093. "#ifdef USE_ENVMAP",
  8094. "vec3 reflectVec;",
  8095. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8096. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8097. "if ( useRefract ) {",
  8098. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8099. "} else { ",
  8100. "reflectVec = reflect( cameraToVertex, normal );",
  8101. "}",
  8102. "#else",
  8103. "reflectVec = vReflect;",
  8104. "#endif",
  8105. "#ifdef DOUBLE_SIDED",
  8106. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8107. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8108. "#else",
  8109. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8110. "#endif",
  8111. "#ifdef GAMMA_INPUT",
  8112. "cubeColor.xyz *= cubeColor.xyz;",
  8113. "#endif",
  8114. "if ( combine == 1 ) {",
  8115. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8116. "} else if ( combine == 2 ) {",
  8117. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8118. "} else {",
  8119. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8120. "}",
  8121. "#endif"
  8122. ].join("\n"),
  8123. envmap_pars_vertex: [
  8124. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8125. "varying vec3 vReflect;",
  8126. "uniform float refractionRatio;",
  8127. "uniform bool useRefract;",
  8128. "#endif"
  8129. ].join("\n"),
  8130. worldpos_vertex : [
  8131. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8132. "#ifdef USE_SKINNING",
  8133. "vec4 worldPosition = modelMatrix * skinned;",
  8134. "#endif",
  8135. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8136. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8137. "#endif",
  8138. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8139. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8140. "#endif",
  8141. "#endif"
  8142. ].join("\n"),
  8143. envmap_vertex : [
  8144. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8145. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8146. "worldNormal = normalize( worldNormal );",
  8147. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8148. "if ( useRefract ) {",
  8149. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8150. "} else {",
  8151. "vReflect = reflect( cameraToVertex, worldNormal );",
  8152. "}",
  8153. "#endif"
  8154. ].join("\n"),
  8155. // COLOR MAP (particles)
  8156. map_particle_pars_fragment: [
  8157. "#ifdef USE_MAP",
  8158. "uniform sampler2D map;",
  8159. "#endif"
  8160. ].join("\n"),
  8161. map_particle_fragment: [
  8162. "#ifdef USE_MAP",
  8163. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8164. "#endif"
  8165. ].join("\n"),
  8166. // COLOR MAP (triangles)
  8167. map_pars_vertex: [
  8168. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8169. "varying vec2 vUv;",
  8170. "uniform vec4 offsetRepeat;",
  8171. "#endif"
  8172. ].join("\n"),
  8173. map_pars_fragment: [
  8174. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8175. "varying vec2 vUv;",
  8176. "#endif",
  8177. "#ifdef USE_MAP",
  8178. "uniform sampler2D map;",
  8179. "#endif"
  8180. ].join("\n"),
  8181. map_vertex: [
  8182. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8183. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8184. "#endif"
  8185. ].join("\n"),
  8186. map_fragment: [
  8187. "#ifdef USE_MAP",
  8188. "#ifdef GAMMA_INPUT",
  8189. "vec4 texelColor = texture2D( map, vUv );",
  8190. "texelColor.xyz *= texelColor.xyz;",
  8191. "gl_FragColor = gl_FragColor * texelColor;",
  8192. "#else",
  8193. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  8194. "#endif",
  8195. "#endif"
  8196. ].join("\n"),
  8197. // LIGHT MAP
  8198. lightmap_pars_fragment: [
  8199. "#ifdef USE_LIGHTMAP",
  8200. "varying vec2 vUv2;",
  8201. "uniform sampler2D lightMap;",
  8202. "#endif"
  8203. ].join("\n"),
  8204. lightmap_pars_vertex: [
  8205. "#ifdef USE_LIGHTMAP",
  8206. "varying vec2 vUv2;",
  8207. "#endif"
  8208. ].join("\n"),
  8209. lightmap_fragment: [
  8210. "#ifdef USE_LIGHTMAP",
  8211. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8212. "#endif"
  8213. ].join("\n"),
  8214. lightmap_vertex: [
  8215. "#ifdef USE_LIGHTMAP",
  8216. "vUv2 = uv2;",
  8217. "#endif"
  8218. ].join("\n"),
  8219. // BUMP MAP
  8220. bumpmap_pars_fragment: [
  8221. "#ifdef USE_BUMPMAP",
  8222. "uniform sampler2D bumpMap;",
  8223. "uniform float bumpScale;",
  8224. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8225. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8226. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8227. "vec2 dHdxy_fwd() {",
  8228. "vec2 dSTdx = dFdx( vUv );",
  8229. "vec2 dSTdy = dFdy( vUv );",
  8230. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8231. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8232. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8233. "return vec2( dBx, dBy );",
  8234. "}",
  8235. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8236. "vec3 vSigmaX = dFdx( surf_pos );",
  8237. "vec3 vSigmaY = dFdy( surf_pos );",
  8238. "vec3 vN = surf_norm;", // normalized
  8239. "vec3 R1 = cross( vSigmaY, vN );",
  8240. "vec3 R2 = cross( vN, vSigmaX );",
  8241. "float fDet = dot( vSigmaX, R1 );",
  8242. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8243. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8244. "}",
  8245. "#endif"
  8246. ].join("\n"),
  8247. // NORMAL MAP
  8248. normalmap_pars_fragment: [
  8249. "#ifdef USE_NORMALMAP",
  8250. "uniform sampler2D normalMap;",
  8251. "uniform vec2 normalScale;",
  8252. // Per-Pixel Tangent Space Normal Mapping
  8253. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8254. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8255. "vec3 q0 = dFdx( eye_pos.xyz );",
  8256. "vec3 q1 = dFdy( eye_pos.xyz );",
  8257. "vec2 st0 = dFdx( vUv.st );",
  8258. "vec2 st1 = dFdy( vUv.st );",
  8259. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8260. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8261. "vec3 N = normalize( surf_norm );",
  8262. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8263. "mapN.xy = normalScale * mapN.xy;",
  8264. "mat3 tsn = mat3( S, T, N );",
  8265. "return normalize( tsn * mapN );",
  8266. "}",
  8267. "#endif"
  8268. ].join("\n"),
  8269. // SPECULAR MAP
  8270. specularmap_pars_fragment: [
  8271. "#ifdef USE_SPECULARMAP",
  8272. "uniform sampler2D specularMap;",
  8273. "#endif"
  8274. ].join("\n"),
  8275. specularmap_fragment: [
  8276. "float specularStrength;",
  8277. "#ifdef USE_SPECULARMAP",
  8278. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8279. "specularStrength = texelSpecular.r;",
  8280. "#else",
  8281. "specularStrength = 1.0;",
  8282. "#endif"
  8283. ].join("\n"),
  8284. // LIGHTS LAMBERT
  8285. lights_lambert_pars_vertex: [
  8286. "uniform vec3 ambient;",
  8287. "uniform vec3 diffuse;",
  8288. "uniform vec3 emissive;",
  8289. "uniform vec3 ambientLightColor;",
  8290. "#if MAX_DIR_LIGHTS > 0",
  8291. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8292. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8293. "#endif",
  8294. "#if MAX_HEMI_LIGHTS > 0",
  8295. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8296. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8297. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8298. "#endif",
  8299. "#if MAX_POINT_LIGHTS > 0",
  8300. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8301. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8302. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8303. "#endif",
  8304. "#if MAX_SPOT_LIGHTS > 0",
  8305. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8306. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8307. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8308. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8309. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8310. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8311. "#endif",
  8312. "#ifdef WRAP_AROUND",
  8313. "uniform vec3 wrapRGB;",
  8314. "#endif"
  8315. ].join("\n"),
  8316. lights_lambert_vertex: [
  8317. "vLightFront = vec3( 0.0 );",
  8318. "#ifdef DOUBLE_SIDED",
  8319. "vLightBack = vec3( 0.0 );",
  8320. "#endif",
  8321. "transformedNormal = normalize( transformedNormal );",
  8322. "#if MAX_DIR_LIGHTS > 0",
  8323. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8324. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8325. "vec3 dirVector = normalize( lDirection.xyz );",
  8326. "float dotProduct = dot( transformedNormal, dirVector );",
  8327. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8328. "#ifdef DOUBLE_SIDED",
  8329. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8330. "#ifdef WRAP_AROUND",
  8331. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8332. "#endif",
  8333. "#endif",
  8334. "#ifdef WRAP_AROUND",
  8335. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8336. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  8337. "#ifdef DOUBLE_SIDED",
  8338. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  8339. "#endif",
  8340. "#endif",
  8341. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  8342. "#ifdef DOUBLE_SIDED",
  8343. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  8344. "#endif",
  8345. "}",
  8346. "#endif",
  8347. "#if MAX_POINT_LIGHTS > 0",
  8348. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8349. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8350. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8351. "float lDistance = 1.0;",
  8352. "if ( pointLightDistance[ i ] > 0.0 )",
  8353. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8354. "lVector = normalize( lVector );",
  8355. "float dotProduct = dot( transformedNormal, lVector );",
  8356. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8357. "#ifdef DOUBLE_SIDED",
  8358. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8359. "#ifdef WRAP_AROUND",
  8360. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8361. "#endif",
  8362. "#endif",
  8363. "#ifdef WRAP_AROUND",
  8364. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8365. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  8366. "#ifdef DOUBLE_SIDED",
  8367. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  8368. "#endif",
  8369. "#endif",
  8370. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  8371. "#ifdef DOUBLE_SIDED",
  8372. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  8373. "#endif",
  8374. "}",
  8375. "#endif",
  8376. "#if MAX_SPOT_LIGHTS > 0",
  8377. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8378. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8379. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8380. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  8381. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8382. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8383. "float lDistance = 1.0;",
  8384. "if ( spotLightDistance[ i ] > 0.0 )",
  8385. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8386. "lVector = normalize( lVector );",
  8387. "float dotProduct = dot( transformedNormal, lVector );",
  8388. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8389. "#ifdef DOUBLE_SIDED",
  8390. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8391. "#ifdef WRAP_AROUND",
  8392. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8393. "#endif",
  8394. "#endif",
  8395. "#ifdef WRAP_AROUND",
  8396. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8397. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  8398. "#ifdef DOUBLE_SIDED",
  8399. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  8400. "#endif",
  8401. "#endif",
  8402. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  8403. "#ifdef DOUBLE_SIDED",
  8404. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  8405. "#endif",
  8406. "}",
  8407. "}",
  8408. "#endif",
  8409. "#if MAX_HEMI_LIGHTS > 0",
  8410. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8411. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8412. "vec3 lVector = normalize( lDirection.xyz );",
  8413. "float dotProduct = dot( transformedNormal, lVector );",
  8414. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8415. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  8416. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8417. "#ifdef DOUBLE_SIDED",
  8418. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  8419. "#endif",
  8420. "}",
  8421. "#endif",
  8422. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  8423. "#ifdef DOUBLE_SIDED",
  8424. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  8425. "#endif"
  8426. ].join("\n"),
  8427. // LIGHTS PHONG
  8428. lights_phong_pars_vertex: [
  8429. "#ifndef PHONG_PER_PIXEL",
  8430. "#if MAX_POINT_LIGHTS > 0",
  8431. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8432. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8433. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8434. "#endif",
  8435. "#if MAX_SPOT_LIGHTS > 0",
  8436. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8437. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8438. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8439. "#endif",
  8440. "#endif",
  8441. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8442. "varying vec3 vWorldPosition;",
  8443. "#endif"
  8444. ].join("\n"),
  8445. lights_phong_vertex: [
  8446. "#ifndef PHONG_PER_PIXEL",
  8447. "#if MAX_POINT_LIGHTS > 0",
  8448. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8449. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8450. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8451. "float lDistance = 1.0;",
  8452. "if ( pointLightDistance[ i ] > 0.0 )",
  8453. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8454. "vPointLight[ i ] = vec4( lVector, lDistance );",
  8455. "}",
  8456. "#endif",
  8457. "#if MAX_SPOT_LIGHTS > 0",
  8458. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8459. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8460. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8461. "float lDistance = 1.0;",
  8462. "if ( spotLightDistance[ i ] > 0.0 )",
  8463. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8464. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  8465. "}",
  8466. "#endif",
  8467. "#endif",
  8468. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8469. "vWorldPosition = worldPosition.xyz;",
  8470. "#endif"
  8471. ].join("\n"),
  8472. lights_phong_pars_fragment: [
  8473. "uniform vec3 ambientLightColor;",
  8474. "#if MAX_DIR_LIGHTS > 0",
  8475. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8476. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8477. "#endif",
  8478. "#if MAX_HEMI_LIGHTS > 0",
  8479. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8480. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8481. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8482. "#endif",
  8483. "#if MAX_POINT_LIGHTS > 0",
  8484. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8485. "#ifdef PHONG_PER_PIXEL",
  8486. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8487. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8488. "#else",
  8489. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8490. "#endif",
  8491. "#endif",
  8492. "#if MAX_SPOT_LIGHTS > 0",
  8493. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8494. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8495. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8496. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8497. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8498. "#ifdef PHONG_PER_PIXEL",
  8499. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8500. "#else",
  8501. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8502. "#endif",
  8503. "#endif",
  8504. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8505. "varying vec3 vWorldPosition;",
  8506. "#endif",
  8507. "#ifdef WRAP_AROUND",
  8508. "uniform vec3 wrapRGB;",
  8509. "#endif",
  8510. "varying vec3 vViewPosition;",
  8511. "varying vec3 vNormal;"
  8512. ].join("\n"),
  8513. lights_phong_fragment: [
  8514. "vec3 normal = normalize( vNormal );",
  8515. "vec3 viewPosition = normalize( vViewPosition );",
  8516. "#ifdef DOUBLE_SIDED",
  8517. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8518. "#endif",
  8519. "#ifdef USE_NORMALMAP",
  8520. "normal = perturbNormal2Arb( -viewPosition, normal );",
  8521. "#elif defined( USE_BUMPMAP )",
  8522. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  8523. "#endif",
  8524. "#if MAX_POINT_LIGHTS > 0",
  8525. "vec3 pointDiffuse = vec3( 0.0 );",
  8526. "vec3 pointSpecular = vec3( 0.0 );",
  8527. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8528. "#ifdef PHONG_PER_PIXEL",
  8529. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8530. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8531. "float lDistance = 1.0;",
  8532. "if ( pointLightDistance[ i ] > 0.0 )",
  8533. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8534. "lVector = normalize( lVector );",
  8535. "#else",
  8536. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  8537. "float lDistance = vPointLight[ i ].w;",
  8538. "#endif",
  8539. // diffuse
  8540. "float dotProduct = dot( normal, lVector );",
  8541. "#ifdef WRAP_AROUND",
  8542. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  8543. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8544. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  8545. "#else",
  8546. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  8547. "#endif",
  8548. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  8549. // specular
  8550. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  8551. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  8552. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  8553. "#ifdef PHYSICALLY_BASED_SHADING",
  8554. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8555. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8556. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  8557. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  8558. "#else",
  8559. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  8560. "#endif",
  8561. "}",
  8562. "#endif",
  8563. "#if MAX_SPOT_LIGHTS > 0",
  8564. "vec3 spotDiffuse = vec3( 0.0 );",
  8565. "vec3 spotSpecular = vec3( 0.0 );",
  8566. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8567. "#ifdef PHONG_PER_PIXEL",
  8568. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8569. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8570. "float lDistance = 1.0;",
  8571. "if ( spotLightDistance[ i ] > 0.0 )",
  8572. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8573. "lVector = normalize( lVector );",
  8574. "#else",
  8575. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  8576. "float lDistance = vSpotLight[ i ].w;",
  8577. "#endif",
  8578. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  8579. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8580. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8581. // diffuse
  8582. "float dotProduct = dot( normal, lVector );",
  8583. "#ifdef WRAP_AROUND",
  8584. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  8585. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8586. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  8587. "#else",
  8588. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  8589. "#endif",
  8590. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  8591. // specular
  8592. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  8593. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  8594. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  8595. "#ifdef PHYSICALLY_BASED_SHADING",
  8596. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8597. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8598. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  8599. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  8600. "#else",
  8601. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  8602. "#endif",
  8603. "}",
  8604. "}",
  8605. "#endif",
  8606. "#if MAX_DIR_LIGHTS > 0",
  8607. "vec3 dirDiffuse = vec3( 0.0 );",
  8608. "vec3 dirSpecular = vec3( 0.0 );" ,
  8609. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8610. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8611. "vec3 dirVector = normalize( lDirection.xyz );",
  8612. // diffuse
  8613. "float dotProduct = dot( normal, dirVector );",
  8614. "#ifdef WRAP_AROUND",
  8615. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  8616. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8617. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  8618. "#else",
  8619. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  8620. "#endif",
  8621. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  8622. // specular
  8623. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  8624. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  8625. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  8626. "#ifdef PHYSICALLY_BASED_SHADING",
  8627. /*
  8628. // fresnel term from skin shader
  8629. "const float F0 = 0.128;",
  8630. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  8631. "float exponential = pow( base, 5.0 );",
  8632. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  8633. */
  8634. /*
  8635. // fresnel term from fresnel shader
  8636. "const float mFresnelBias = 0.08;",
  8637. "const float mFresnelScale = 0.3;",
  8638. "const float mFresnelPower = 5.0;",
  8639. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  8640. */
  8641. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8642. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8643. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  8644. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  8645. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  8646. "#else",
  8647. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  8648. "#endif",
  8649. "}",
  8650. "#endif",
  8651. "#if MAX_HEMI_LIGHTS > 0",
  8652. "vec3 hemiDiffuse = vec3( 0.0 );",
  8653. "vec3 hemiSpecular = vec3( 0.0 );" ,
  8654. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8655. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8656. "vec3 lVector = normalize( lDirection.xyz );",
  8657. // diffuse
  8658. "float dotProduct = dot( normal, lVector );",
  8659. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8660. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8661. "hemiDiffuse += diffuse * hemiColor;",
  8662. // specular (sky light)
  8663. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  8664. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  8665. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  8666. // specular (ground light)
  8667. "vec3 lVectorGround = -lVector;",
  8668. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  8669. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  8670. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  8671. "#ifdef PHYSICALLY_BASED_SHADING",
  8672. "float dotProductGround = dot( normal, lVectorGround );",
  8673. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8674. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8675. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  8676. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  8677. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  8678. "#else",
  8679. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  8680. "#endif",
  8681. "}",
  8682. "#endif",
  8683. "vec3 totalDiffuse = vec3( 0.0 );",
  8684. "vec3 totalSpecular = vec3( 0.0 );",
  8685. "#if MAX_DIR_LIGHTS > 0",
  8686. "totalDiffuse += dirDiffuse;",
  8687. "totalSpecular += dirSpecular;",
  8688. "#endif",
  8689. "#if MAX_HEMI_LIGHTS > 0",
  8690. "totalDiffuse += hemiDiffuse;",
  8691. "totalSpecular += hemiSpecular;",
  8692. "#endif",
  8693. "#if MAX_POINT_LIGHTS > 0",
  8694. "totalDiffuse += pointDiffuse;",
  8695. "totalSpecular += pointSpecular;",
  8696. "#endif",
  8697. "#if MAX_SPOT_LIGHTS > 0",
  8698. "totalDiffuse += spotDiffuse;",
  8699. "totalSpecular += spotSpecular;",
  8700. "#endif",
  8701. "#ifdef METAL",
  8702. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  8703. "#else",
  8704. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  8705. "#endif"
  8706. ].join("\n"),
  8707. // VERTEX COLORS
  8708. color_pars_fragment: [
  8709. "#ifdef USE_COLOR",
  8710. "varying vec3 vColor;",
  8711. "#endif"
  8712. ].join("\n"),
  8713. color_fragment: [
  8714. "#ifdef USE_COLOR",
  8715. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  8716. "#endif"
  8717. ].join("\n"),
  8718. color_pars_vertex: [
  8719. "#ifdef USE_COLOR",
  8720. "varying vec3 vColor;",
  8721. "#endif"
  8722. ].join("\n"),
  8723. color_vertex: [
  8724. "#ifdef USE_COLOR",
  8725. "#ifdef GAMMA_INPUT",
  8726. "vColor = color * color;",
  8727. "#else",
  8728. "vColor = color;",
  8729. "#endif",
  8730. "#endif"
  8731. ].join("\n"),
  8732. // SKINNING
  8733. skinning_pars_vertex: [
  8734. "#ifdef USE_SKINNING",
  8735. "#ifdef BONE_TEXTURE",
  8736. "uniform sampler2D boneTexture;",
  8737. "mat4 getBoneMatrix( const in float i ) {",
  8738. "float j = i * 4.0;",
  8739. "float x = mod( j, N_BONE_PIXEL_X );",
  8740. "float y = floor( j / N_BONE_PIXEL_X );",
  8741. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  8742. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  8743. "y = dy * ( y + 0.5 );",
  8744. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  8745. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  8746. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  8747. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  8748. "mat4 bone = mat4( v1, v2, v3, v4 );",
  8749. "return bone;",
  8750. "}",
  8751. "#else",
  8752. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  8753. "mat4 getBoneMatrix( const in float i ) {",
  8754. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  8755. "return bone;",
  8756. "}",
  8757. "#endif",
  8758. "#endif"
  8759. ].join("\n"),
  8760. skinbase_vertex: [
  8761. "#ifdef USE_SKINNING",
  8762. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  8763. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  8764. "#endif"
  8765. ].join("\n"),
  8766. skinning_vertex: [
  8767. "#ifdef USE_SKINNING",
  8768. "#ifdef USE_MORPHTARGETS",
  8769. "vec4 skinVertex = vec4( morphed, 1.0 );",
  8770. "#else",
  8771. "vec4 skinVertex = vec4( position, 1.0 );",
  8772. "#endif",
  8773. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  8774. "skinned += boneMatY * skinVertex * skinWeight.y;",
  8775. "#endif"
  8776. ].join("\n"),
  8777. // MORPHING
  8778. morphtarget_pars_vertex: [
  8779. "#ifdef USE_MORPHTARGETS",
  8780. "#ifndef USE_MORPHNORMALS",
  8781. "uniform float morphTargetInfluences[ 8 ];",
  8782. "#else",
  8783. "uniform float morphTargetInfluences[ 4 ];",
  8784. "#endif",
  8785. "#endif"
  8786. ].join("\n"),
  8787. morphtarget_vertex: [
  8788. "#ifdef USE_MORPHTARGETS",
  8789. "vec3 morphed = vec3( 0.0 );",
  8790. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  8791. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  8792. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  8793. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  8794. "#ifndef USE_MORPHNORMALS",
  8795. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  8796. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  8797. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  8798. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  8799. "#endif",
  8800. "morphed += position;",
  8801. "#endif"
  8802. ].join("\n"),
  8803. default_vertex : [
  8804. "vec4 mvPosition;",
  8805. "#ifdef USE_SKINNING",
  8806. "mvPosition = modelViewMatrix * skinned;",
  8807. "#endif",
  8808. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  8809. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  8810. "#endif",
  8811. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  8812. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8813. "#endif",
  8814. "gl_Position = projectionMatrix * mvPosition;"
  8815. ].join("\n"),
  8816. morphnormal_vertex: [
  8817. "#ifdef USE_MORPHNORMALS",
  8818. "vec3 morphedNormal = vec3( 0.0 );",
  8819. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  8820. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  8821. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  8822. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  8823. "morphedNormal += normal;",
  8824. "#endif"
  8825. ].join("\n"),
  8826. skinnormal_vertex: [
  8827. "#ifdef USE_SKINNING",
  8828. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  8829. "skinMatrix += skinWeight.y * boneMatY;",
  8830. "#ifdef USE_MORPHNORMALS",
  8831. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  8832. "#else",
  8833. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  8834. "#endif",
  8835. "#endif"
  8836. ].join("\n"),
  8837. defaultnormal_vertex: [
  8838. "vec3 objectNormal;",
  8839. "#ifdef USE_SKINNING",
  8840. "objectNormal = skinnedNormal.xyz;",
  8841. "#endif",
  8842. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  8843. "objectNormal = morphedNormal;",
  8844. "#endif",
  8845. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  8846. "objectNormal = normal;",
  8847. "#endif",
  8848. "#ifdef FLIP_SIDED",
  8849. "objectNormal = -objectNormal;",
  8850. "#endif",
  8851. "vec3 transformedNormal = normalMatrix * objectNormal;"
  8852. ].join("\n"),
  8853. // SHADOW MAP
  8854. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  8855. // http://spidergl.org/example.php?id=6
  8856. // http://fabiensanglard.net/shadowmapping
  8857. shadowmap_pars_fragment: [
  8858. "#ifdef USE_SHADOWMAP",
  8859. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  8860. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  8861. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  8862. "uniform float shadowBias[ MAX_SHADOWS ];",
  8863. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8864. "float unpackDepth( const in vec4 rgba_depth ) {",
  8865. "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 );",
  8866. "float depth = dot( rgba_depth, bit_shift );",
  8867. "return depth;",
  8868. "}",
  8869. "#endif"
  8870. ].join("\n"),
  8871. shadowmap_fragment: [
  8872. "#ifdef USE_SHADOWMAP",
  8873. "#ifdef SHADOWMAP_DEBUG",
  8874. "vec3 frustumColors[3];",
  8875. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  8876. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  8877. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  8878. "#endif",
  8879. "#ifdef SHADOWMAP_CASCADE",
  8880. "int inFrustumCount = 0;",
  8881. "#endif",
  8882. "float fDepth;",
  8883. "vec3 shadowColor = vec3( 1.0 );",
  8884. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8885. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  8886. // "if ( something && something )" breaks ATI OpenGL shader compiler
  8887. // "if ( all( something, something ) )" using this instead
  8888. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  8889. "bool inFrustum = all( inFrustumVec );",
  8890. // don't shadow pixels outside of light frustum
  8891. // use just first frustum (for cascades)
  8892. // don't shadow pixels behind far plane of light frustum
  8893. "#ifdef SHADOWMAP_CASCADE",
  8894. "inFrustumCount += int( inFrustum );",
  8895. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  8896. "#else",
  8897. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  8898. "#endif",
  8899. "bool frustumTest = all( frustumTestVec );",
  8900. "if ( frustumTest ) {",
  8901. "shadowCoord.z += shadowBias[ i ];",
  8902. "#ifdef SHADOWMAP_SOFT",
  8903. // Percentage-close filtering
  8904. // (9 pixel kernel)
  8905. // http://fabiensanglard.net/shadowmappingPCF/
  8906. "float shadow = 0.0;",
  8907. /*
  8908. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  8909. // must enroll loop manually
  8910. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  8911. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  8912. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  8913. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  8914. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  8915. "float fDepth = unpackDepth( rgbaDepth );",
  8916. "if ( fDepth < shadowCoord.z )",
  8917. "shadow += 1.0;",
  8918. "}",
  8919. "shadow /= 9.0;",
  8920. */
  8921. "const float shadowDelta = 1.0 / 9.0;",
  8922. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  8923. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  8924. "float dx0 = -1.25 * xPixelOffset;",
  8925. "float dy0 = -1.25 * yPixelOffset;",
  8926. "float dx1 = 1.25 * xPixelOffset;",
  8927. "float dy1 = 1.25 * yPixelOffset;",
  8928. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  8929. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8930. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  8931. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8932. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  8933. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8934. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  8935. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8936. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  8937. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8938. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  8939. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8940. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  8941. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8942. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  8943. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8944. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  8945. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8946. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  8947. "#else",
  8948. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  8949. "float fDepth = unpackDepth( rgbaDepth );",
  8950. "if ( fDepth < shadowCoord.z )",
  8951. // spot with multiple shadows is darker
  8952. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  8953. // spot with multiple shadows has the same color as single shadow spot
  8954. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  8955. "#endif",
  8956. "}",
  8957. "#ifdef SHADOWMAP_DEBUG",
  8958. "#ifdef SHADOWMAP_CASCADE",
  8959. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  8960. "#else",
  8961. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  8962. "#endif",
  8963. "#endif",
  8964. "}",
  8965. "#ifdef GAMMA_OUTPUT",
  8966. "shadowColor *= shadowColor;",
  8967. "#endif",
  8968. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  8969. "#endif"
  8970. ].join("\n"),
  8971. shadowmap_pars_vertex: [
  8972. "#ifdef USE_SHADOWMAP",
  8973. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8974. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  8975. "#endif"
  8976. ].join("\n"),
  8977. shadowmap_vertex: [
  8978. "#ifdef USE_SHADOWMAP",
  8979. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8980. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  8981. "}",
  8982. "#endif"
  8983. ].join("\n"),
  8984. // ALPHATEST
  8985. alphatest_fragment: [
  8986. "#ifdef ALPHATEST",
  8987. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  8988. "#endif"
  8989. ].join("\n"),
  8990. // LINEAR SPACE
  8991. linear_to_gamma_fragment: [
  8992. "#ifdef GAMMA_OUTPUT",
  8993. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  8994. "#endif"
  8995. ].join("\n")
  8996. };
  8997. THREE.UniformsUtils = {
  8998. merge: function ( uniforms ) {
  8999. var u, p, tmp, merged = {};
  9000. for ( u = 0; u < uniforms.length; u ++ ) {
  9001. tmp = this.clone( uniforms[ u ] );
  9002. for ( p in tmp ) {
  9003. merged[ p ] = tmp[ p ];
  9004. }
  9005. }
  9006. return merged;
  9007. },
  9008. clone: function ( uniforms_src ) {
  9009. var u, p, parameter, parameter_src, uniforms_dst = {};
  9010. for ( u in uniforms_src ) {
  9011. uniforms_dst[ u ] = {};
  9012. for ( p in uniforms_src[ u ] ) {
  9013. parameter_src = uniforms_src[ u ][ p ];
  9014. if ( parameter_src instanceof THREE.Color ||
  9015. parameter_src instanceof THREE.Vector2 ||
  9016. parameter_src instanceof THREE.Vector3 ||
  9017. parameter_src instanceof THREE.Vector4 ||
  9018. parameter_src instanceof THREE.Matrix4 ||
  9019. parameter_src instanceof THREE.Texture ) {
  9020. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9021. } else if ( parameter_src instanceof Array ) {
  9022. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9023. } else {
  9024. uniforms_dst[ u ][ p ] = parameter_src;
  9025. }
  9026. }
  9027. }
  9028. return uniforms_dst;
  9029. }
  9030. };
  9031. THREE.UniformsLib = {
  9032. common: {
  9033. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9034. "opacity" : { type: "f", value: 1.0 },
  9035. "map" : { type: "t", value: null },
  9036. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9037. "lightMap" : { type: "t", value: null },
  9038. "specularMap" : { type: "t", value: null },
  9039. "envMap" : { type: "t", value: null },
  9040. "flipEnvMap" : { type: "f", value: -1 },
  9041. "useRefract" : { type: "i", value: 0 },
  9042. "reflectivity" : { type: "f", value: 1.0 },
  9043. "refractionRatio" : { type: "f", value: 0.98 },
  9044. "combine" : { type: "i", value: 0 },
  9045. "morphTargetInfluences" : { type: "f", value: 0 }
  9046. },
  9047. bump: {
  9048. "bumpMap" : { type: "t", value: null },
  9049. "bumpScale" : { type: "f", value: 1 }
  9050. },
  9051. normalmap: {
  9052. "normalMap" : { type: "t", value: null },
  9053. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9054. },
  9055. fog : {
  9056. "fogDensity" : { type: "f", value: 0.00025 },
  9057. "fogNear" : { type: "f", value: 1 },
  9058. "fogFar" : { type: "f", value: 2000 },
  9059. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9060. },
  9061. lights: {
  9062. "ambientLightColor" : { type: "fv", value: [] },
  9063. "directionalLightDirection" : { type: "fv", value: [] },
  9064. "directionalLightColor" : { type: "fv", value: [] },
  9065. "hemisphereLightDirection" : { type: "fv", value: [] },
  9066. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9067. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9068. "pointLightColor" : { type: "fv", value: [] },
  9069. "pointLightPosition" : { type: "fv", value: [] },
  9070. "pointLightDistance" : { type: "fv1", value: [] },
  9071. "spotLightColor" : { type: "fv", value: [] },
  9072. "spotLightPosition" : { type: "fv", value: [] },
  9073. "spotLightDirection" : { type: "fv", value: [] },
  9074. "spotLightDistance" : { type: "fv1", value: [] },
  9075. "spotLightAngleCos" : { type: "fv1", value: [] },
  9076. "spotLightExponent" : { type: "fv1", value: [] }
  9077. },
  9078. particle: {
  9079. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9080. "opacity" : { type: "f", value: 1.0 },
  9081. "size" : { type: "f", value: 1.0 },
  9082. "scale" : { type: "f", value: 1.0 },
  9083. "map" : { type: "t", value: null },
  9084. "fogDensity" : { type: "f", value: 0.00025 },
  9085. "fogNear" : { type: "f", value: 1 },
  9086. "fogFar" : { type: "f", value: 2000 },
  9087. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9088. },
  9089. shadowmap: {
  9090. "shadowMap": { type: "tv", value: [] },
  9091. "shadowMapSize": { type: "v2v", value: [] },
  9092. "shadowBias" : { type: "fv1", value: [] },
  9093. "shadowDarkness": { type: "fv1", value: [] },
  9094. "shadowMatrix" : { type: "m4v", value: [] }
  9095. }
  9096. };
  9097. THREE.ShaderLib = {
  9098. 'depth': {
  9099. uniforms: {
  9100. "mNear": { type: "f", value: 1.0 },
  9101. "mFar" : { type: "f", value: 2000.0 },
  9102. "opacity" : { type: "f", value: 1.0 }
  9103. },
  9104. vertexShader: [
  9105. "void main() {",
  9106. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  9107. "}"
  9108. ].join("\n"),
  9109. fragmentShader: [
  9110. "uniform float mNear;",
  9111. "uniform float mFar;",
  9112. "uniform float opacity;",
  9113. "void main() {",
  9114. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9115. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  9116. "gl_FragColor = vec4( vec3( color ), opacity );",
  9117. "}"
  9118. ].join("\n")
  9119. },
  9120. 'normal': {
  9121. uniforms: {
  9122. "opacity" : { type: "f", value: 1.0 }
  9123. },
  9124. vertexShader: [
  9125. "varying vec3 vNormal;",
  9126. "void main() {",
  9127. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9128. "vNormal = normalize( normalMatrix * normal );",
  9129. "gl_Position = projectionMatrix * mvPosition;",
  9130. "}"
  9131. ].join("\n"),
  9132. fragmentShader: [
  9133. "uniform float opacity;",
  9134. "varying vec3 vNormal;",
  9135. "void main() {",
  9136. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  9137. "}"
  9138. ].join("\n")
  9139. },
  9140. 'basic': {
  9141. uniforms: THREE.UniformsUtils.merge( [
  9142. THREE.UniformsLib[ "common" ],
  9143. THREE.UniformsLib[ "fog" ],
  9144. THREE.UniformsLib[ "shadowmap" ]
  9145. ] ),
  9146. vertexShader: [
  9147. THREE.ShaderChunk[ "map_pars_vertex" ],
  9148. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9149. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9150. THREE.ShaderChunk[ "color_pars_vertex" ],
  9151. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9152. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9153. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9154. "void main() {",
  9155. THREE.ShaderChunk[ "map_vertex" ],
  9156. THREE.ShaderChunk[ "lightmap_vertex" ],
  9157. THREE.ShaderChunk[ "color_vertex" ],
  9158. "#ifdef USE_ENVMAP",
  9159. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9160. THREE.ShaderChunk[ "skinbase_vertex" ],
  9161. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9162. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9163. "#endif",
  9164. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9165. THREE.ShaderChunk[ "skinning_vertex" ],
  9166. THREE.ShaderChunk[ "default_vertex" ],
  9167. THREE.ShaderChunk[ "worldpos_vertex" ],
  9168. THREE.ShaderChunk[ "envmap_vertex" ],
  9169. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9170. "}"
  9171. ].join("\n"),
  9172. fragmentShader: [
  9173. "uniform vec3 diffuse;",
  9174. "uniform float opacity;",
  9175. THREE.ShaderChunk[ "color_pars_fragment" ],
  9176. THREE.ShaderChunk[ "map_pars_fragment" ],
  9177. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9178. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9179. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9180. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9181. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9182. "void main() {",
  9183. "gl_FragColor = vec4( diffuse, opacity );",
  9184. THREE.ShaderChunk[ "map_fragment" ],
  9185. THREE.ShaderChunk[ "alphatest_fragment" ],
  9186. THREE.ShaderChunk[ "specularmap_fragment" ],
  9187. THREE.ShaderChunk[ "lightmap_fragment" ],
  9188. THREE.ShaderChunk[ "color_fragment" ],
  9189. THREE.ShaderChunk[ "envmap_fragment" ],
  9190. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9191. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9192. THREE.ShaderChunk[ "fog_fragment" ],
  9193. "}"
  9194. ].join("\n")
  9195. },
  9196. 'lambert': {
  9197. uniforms: THREE.UniformsUtils.merge( [
  9198. THREE.UniformsLib[ "common" ],
  9199. THREE.UniformsLib[ "fog" ],
  9200. THREE.UniformsLib[ "lights" ],
  9201. THREE.UniformsLib[ "shadowmap" ],
  9202. {
  9203. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9204. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9205. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9206. }
  9207. ] ),
  9208. vertexShader: [
  9209. "#define LAMBERT",
  9210. "varying vec3 vLightFront;",
  9211. "#ifdef DOUBLE_SIDED",
  9212. "varying vec3 vLightBack;",
  9213. "#endif",
  9214. THREE.ShaderChunk[ "map_pars_vertex" ],
  9215. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9216. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9217. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9218. THREE.ShaderChunk[ "color_pars_vertex" ],
  9219. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9220. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9221. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9222. "void main() {",
  9223. THREE.ShaderChunk[ "map_vertex" ],
  9224. THREE.ShaderChunk[ "lightmap_vertex" ],
  9225. THREE.ShaderChunk[ "color_vertex" ],
  9226. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9227. THREE.ShaderChunk[ "skinbase_vertex" ],
  9228. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9229. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9230. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9231. THREE.ShaderChunk[ "skinning_vertex" ],
  9232. THREE.ShaderChunk[ "default_vertex" ],
  9233. THREE.ShaderChunk[ "worldpos_vertex" ],
  9234. THREE.ShaderChunk[ "envmap_vertex" ],
  9235. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9236. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9237. "}"
  9238. ].join("\n"),
  9239. fragmentShader: [
  9240. "uniform float opacity;",
  9241. "varying vec3 vLightFront;",
  9242. "#ifdef DOUBLE_SIDED",
  9243. "varying vec3 vLightBack;",
  9244. "#endif",
  9245. THREE.ShaderChunk[ "color_pars_fragment" ],
  9246. THREE.ShaderChunk[ "map_pars_fragment" ],
  9247. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9248. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9249. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9250. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9251. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9252. "void main() {",
  9253. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9254. THREE.ShaderChunk[ "map_fragment" ],
  9255. THREE.ShaderChunk[ "alphatest_fragment" ],
  9256. THREE.ShaderChunk[ "specularmap_fragment" ],
  9257. "#ifdef DOUBLE_SIDED",
  9258. //"float isFront = float( gl_FrontFacing );",
  9259. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9260. "if ( gl_FrontFacing )",
  9261. "gl_FragColor.xyz *= vLightFront;",
  9262. "else",
  9263. "gl_FragColor.xyz *= vLightBack;",
  9264. "#else",
  9265. "gl_FragColor.xyz *= vLightFront;",
  9266. "#endif",
  9267. THREE.ShaderChunk[ "lightmap_fragment" ],
  9268. THREE.ShaderChunk[ "color_fragment" ],
  9269. THREE.ShaderChunk[ "envmap_fragment" ],
  9270. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9271. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9272. THREE.ShaderChunk[ "fog_fragment" ],
  9273. "}"
  9274. ].join("\n")
  9275. },
  9276. 'phong': {
  9277. uniforms: THREE.UniformsUtils.merge( [
  9278. THREE.UniformsLib[ "common" ],
  9279. THREE.UniformsLib[ "bump" ],
  9280. THREE.UniformsLib[ "normalmap" ],
  9281. THREE.UniformsLib[ "fog" ],
  9282. THREE.UniformsLib[ "lights" ],
  9283. THREE.UniformsLib[ "shadowmap" ],
  9284. {
  9285. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9286. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9287. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  9288. "shininess": { type: "f", value: 30 },
  9289. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9290. }
  9291. ] ),
  9292. vertexShader: [
  9293. "#define PHONG",
  9294. "varying vec3 vViewPosition;",
  9295. "varying vec3 vNormal;",
  9296. THREE.ShaderChunk[ "map_pars_vertex" ],
  9297. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9298. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9299. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  9300. THREE.ShaderChunk[ "color_pars_vertex" ],
  9301. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9302. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9303. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9304. "void main() {",
  9305. THREE.ShaderChunk[ "map_vertex" ],
  9306. THREE.ShaderChunk[ "lightmap_vertex" ],
  9307. THREE.ShaderChunk[ "color_vertex" ],
  9308. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9309. THREE.ShaderChunk[ "skinbase_vertex" ],
  9310. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9311. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9312. "vNormal = normalize( transformedNormal );",
  9313. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9314. THREE.ShaderChunk[ "skinning_vertex" ],
  9315. THREE.ShaderChunk[ "default_vertex" ],
  9316. "vViewPosition = -mvPosition.xyz;",
  9317. THREE.ShaderChunk[ "worldpos_vertex" ],
  9318. THREE.ShaderChunk[ "envmap_vertex" ],
  9319. THREE.ShaderChunk[ "lights_phong_vertex" ],
  9320. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9321. "}"
  9322. ].join("\n"),
  9323. fragmentShader: [
  9324. "uniform vec3 diffuse;",
  9325. "uniform float opacity;",
  9326. "uniform vec3 ambient;",
  9327. "uniform vec3 emissive;",
  9328. "uniform vec3 specular;",
  9329. "uniform float shininess;",
  9330. THREE.ShaderChunk[ "color_pars_fragment" ],
  9331. THREE.ShaderChunk[ "map_pars_fragment" ],
  9332. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9333. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9334. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9335. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  9336. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9337. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  9338. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  9339. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9340. "void main() {",
  9341. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9342. THREE.ShaderChunk[ "map_fragment" ],
  9343. THREE.ShaderChunk[ "alphatest_fragment" ],
  9344. THREE.ShaderChunk[ "specularmap_fragment" ],
  9345. THREE.ShaderChunk[ "lights_phong_fragment" ],
  9346. THREE.ShaderChunk[ "lightmap_fragment" ],
  9347. THREE.ShaderChunk[ "color_fragment" ],
  9348. THREE.ShaderChunk[ "envmap_fragment" ],
  9349. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9350. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9351. THREE.ShaderChunk[ "fog_fragment" ],
  9352. "}"
  9353. ].join("\n")
  9354. },
  9355. 'particle_basic': {
  9356. uniforms: THREE.UniformsUtils.merge( [
  9357. THREE.UniformsLib[ "particle" ],
  9358. THREE.UniformsLib[ "shadowmap" ]
  9359. ] ),
  9360. vertexShader: [
  9361. "uniform float size;",
  9362. "uniform float scale;",
  9363. THREE.ShaderChunk[ "color_pars_vertex" ],
  9364. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9365. "void main() {",
  9366. THREE.ShaderChunk[ "color_vertex" ],
  9367. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9368. "#ifdef USE_SIZEATTENUATION",
  9369. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  9370. "#else",
  9371. "gl_PointSize = size;",
  9372. "#endif",
  9373. "gl_Position = projectionMatrix * mvPosition;",
  9374. THREE.ShaderChunk[ "worldpos_vertex" ],
  9375. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9376. "}"
  9377. ].join("\n"),
  9378. fragmentShader: [
  9379. "uniform vec3 psColor;",
  9380. "uniform float opacity;",
  9381. THREE.ShaderChunk[ "color_pars_fragment" ],
  9382. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  9383. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9384. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9385. "void main() {",
  9386. "gl_FragColor = vec4( psColor, opacity );",
  9387. THREE.ShaderChunk[ "map_particle_fragment" ],
  9388. THREE.ShaderChunk[ "alphatest_fragment" ],
  9389. THREE.ShaderChunk[ "color_fragment" ],
  9390. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9391. THREE.ShaderChunk[ "fog_fragment" ],
  9392. "}"
  9393. ].join("\n")
  9394. },
  9395. 'dashed': {
  9396. uniforms: THREE.UniformsUtils.merge( [
  9397. THREE.UniformsLib[ "common" ],
  9398. THREE.UniformsLib[ "fog" ],
  9399. {
  9400. "scale": { type: "f", value: 1 },
  9401. "dashSize": { type: "f", value: 1 },
  9402. "totalSize": { type: "f", value: 2 }
  9403. }
  9404. ] ),
  9405. vertexShader: [
  9406. "uniform float scale;",
  9407. "attribute float lineDistance;",
  9408. "varying float vLineDistance;",
  9409. THREE.ShaderChunk[ "color_pars_vertex" ],
  9410. "void main() {",
  9411. THREE.ShaderChunk[ "color_vertex" ],
  9412. "vLineDistance = scale * lineDistance;",
  9413. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9414. "gl_Position = projectionMatrix * mvPosition;",
  9415. "}"
  9416. ].join("\n"),
  9417. fragmentShader: [
  9418. "uniform vec3 diffuse;",
  9419. "uniform float opacity;",
  9420. "uniform float dashSize;",
  9421. "uniform float totalSize;",
  9422. "varying float vLineDistance;",
  9423. THREE.ShaderChunk[ "color_pars_fragment" ],
  9424. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9425. "void main() {",
  9426. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  9427. "discard;",
  9428. "}",
  9429. "gl_FragColor = vec4( diffuse, opacity );",
  9430. THREE.ShaderChunk[ "color_fragment" ],
  9431. THREE.ShaderChunk[ "fog_fragment" ],
  9432. "}"
  9433. ].join("\n")
  9434. },
  9435. // Depth encoding into RGBA texture
  9436. // based on SpiderGL shadow map example
  9437. // http://spidergl.org/example.php?id=6
  9438. // originally from
  9439. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  9440. // see also here:
  9441. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  9442. 'depthRGBA': {
  9443. uniforms: {},
  9444. vertexShader: [
  9445. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9446. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9447. "void main() {",
  9448. THREE.ShaderChunk[ "skinbase_vertex" ],
  9449. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9450. THREE.ShaderChunk[ "skinning_vertex" ],
  9451. THREE.ShaderChunk[ "default_vertex" ],
  9452. "}"
  9453. ].join("\n"),
  9454. fragmentShader: [
  9455. "vec4 pack_depth( const in float depth ) {",
  9456. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  9457. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  9458. "vec4 res = fract( depth * bit_shift );",
  9459. "res -= res.xxyz * bit_mask;",
  9460. "return res;",
  9461. "}",
  9462. "void main() {",
  9463. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  9464. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  9465. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  9466. //"gl_FragData[ 0 ] = pack_depth( z );",
  9467. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  9468. "}"
  9469. ].join("\n")
  9470. }
  9471. };
  9472. /**
  9473. * @author supereggbert / http://www.paulbrunt.co.uk/
  9474. * @author mrdoob / http://mrdoob.com/
  9475. * @author alteredq / http://alteredqualia.com/
  9476. * @author szimek / https://github.com/szimek/
  9477. */
  9478. THREE.WebGLRenderer = function ( parameters ) {
  9479. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  9480. parameters = parameters || {};
  9481. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  9482. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  9483. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  9484. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  9485. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  9486. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  9487. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  9488. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  9489. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  9490. // public properties
  9491. this.domElement = _canvas;
  9492. this.context = null;
  9493. // clearing
  9494. this.autoClear = true;
  9495. this.autoClearColor = true;
  9496. this.autoClearDepth = true;
  9497. this.autoClearStencil = true;
  9498. // scene graph
  9499. this.sortObjects = true;
  9500. this.autoUpdateObjects = true;
  9501. this.autoUpdateScene = true;
  9502. // physically based shading
  9503. this.gammaInput = false;
  9504. this.gammaOutput = false;
  9505. this.physicallyBasedShading = false;
  9506. // shadow map
  9507. this.shadowMapEnabled = false;
  9508. this.shadowMapAutoUpdate = true;
  9509. this.shadowMapSoft = true;
  9510. this.shadowMapCullFace = THREE.CullFaceFront;
  9511. this.shadowMapDebug = false;
  9512. this.shadowMapCascade = false;
  9513. // morphs
  9514. this.maxMorphTargets = 8;
  9515. this.maxMorphNormals = 4;
  9516. // flags
  9517. this.autoScaleCubemaps = true;
  9518. // custom render plugins
  9519. this.renderPluginsPre = [];
  9520. this.renderPluginsPost = [];
  9521. // info
  9522. this.info = {
  9523. memory: {
  9524. programs: 0,
  9525. geometries: 0,
  9526. textures: 0
  9527. },
  9528. render: {
  9529. calls: 0,
  9530. vertices: 0,
  9531. faces: 0,
  9532. points: 0
  9533. }
  9534. };
  9535. // internal properties
  9536. var _this = this,
  9537. _programs = [],
  9538. _programs_counter = 0,
  9539. // internal state cache
  9540. _currentProgram = null,
  9541. _currentFramebuffer = null,
  9542. _currentMaterialId = -1,
  9543. _currentGeometryGroupHash = null,
  9544. _currentCamera = null,
  9545. _geometryGroupCounter = 0,
  9546. _usedTextureUnits = 0,
  9547. // GL state cache
  9548. _oldDoubleSided = -1,
  9549. _oldFlipSided = -1,
  9550. _oldBlending = -1,
  9551. _oldBlendEquation = -1,
  9552. _oldBlendSrc = -1,
  9553. _oldBlendDst = -1,
  9554. _oldDepthTest = -1,
  9555. _oldDepthWrite = -1,
  9556. _oldPolygonOffset = null,
  9557. _oldPolygonOffsetFactor = null,
  9558. _oldPolygonOffsetUnits = null,
  9559. _oldLineWidth = null,
  9560. _viewportX = 0,
  9561. _viewportY = 0,
  9562. _viewportWidth = 0,
  9563. _viewportHeight = 0,
  9564. _currentWidth = 0,
  9565. _currentHeight = 0,
  9566. _enabledAttributes = {},
  9567. // frustum
  9568. _frustum = new THREE.Frustum(),
  9569. // camera matrices cache
  9570. _projScreenMatrix = new THREE.Matrix4(),
  9571. _projScreenMatrixPS = new THREE.Matrix4(),
  9572. _vector3 = new THREE.Vector4(),
  9573. // light arrays cache
  9574. _direction = new THREE.Vector3(),
  9575. _lightsNeedUpdate = true,
  9576. _lights = {
  9577. ambient: [ 0, 0, 0 ],
  9578. directional: { length: 0, colors: new Array(), positions: new Array() },
  9579. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  9580. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  9581. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  9582. };
  9583. // initialize
  9584. var _gl;
  9585. var _glExtensionTextureFloat;
  9586. var _glExtensionStandardDerivatives;
  9587. var _glExtensionTextureFilterAnisotropic;
  9588. var _glExtensionCompressedTextureS3TC;
  9589. initGL();
  9590. setDefaultGLState();
  9591. this.context = _gl;
  9592. // GPU capabilities
  9593. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  9594. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9595. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  9596. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9597. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  9598. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  9599. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  9600. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  9601. // API
  9602. this.getContext = function () {
  9603. return _gl;
  9604. };
  9605. this.supportsVertexTextures = function () {
  9606. return _supportsVertexTextures;
  9607. };
  9608. this.getMaxAnisotropy = function () {
  9609. return _maxAnisotropy;
  9610. };
  9611. this.setSize = function ( width, height ) {
  9612. _canvas.width = width;
  9613. _canvas.height = height;
  9614. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  9615. };
  9616. this.setViewport = function ( x, y, width, height ) {
  9617. _viewportX = x !== undefined ? x : 0;
  9618. _viewportY = y !== undefined ? y : 0;
  9619. _viewportWidth = width !== undefined ? width : _canvas.width;
  9620. _viewportHeight = height !== undefined ? height : _canvas.height;
  9621. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  9622. };
  9623. this.setScissor = function ( x, y, width, height ) {
  9624. _gl.scissor( x, y, width, height );
  9625. };
  9626. this.enableScissorTest = function ( enable ) {
  9627. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  9628. };
  9629. // Clearing
  9630. this.setClearColorHex = function ( hex, alpha ) {
  9631. _clearColor.setHex( hex );
  9632. _clearAlpha = alpha;
  9633. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9634. };
  9635. this.setClearColor = function ( color, alpha ) {
  9636. _clearColor.copy( color );
  9637. _clearAlpha = alpha;
  9638. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9639. };
  9640. this.getClearColor = function () {
  9641. return _clearColor;
  9642. };
  9643. this.getClearAlpha = function () {
  9644. return _clearAlpha;
  9645. };
  9646. this.clear = function ( color, depth, stencil ) {
  9647. var bits = 0;
  9648. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  9649. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  9650. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  9651. _gl.clear( bits );
  9652. };
  9653. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  9654. this.setRenderTarget( renderTarget );
  9655. this.clear( color, depth, stencil );
  9656. };
  9657. // Plugins
  9658. this.addPostPlugin = function ( plugin ) {
  9659. plugin.init( this );
  9660. this.renderPluginsPost.push( plugin );
  9661. };
  9662. this.addPrePlugin = function ( plugin ) {
  9663. plugin.init( this );
  9664. this.renderPluginsPre.push( plugin );
  9665. };
  9666. // Deallocation
  9667. this.deallocateObject = function ( object ) {
  9668. if ( ! object.__webglInit ) return;
  9669. object.__webglInit = false;
  9670. delete object._modelViewMatrix;
  9671. delete object._normalMatrix;
  9672. if ( object instanceof THREE.Mesh ) {
  9673. for ( var g in object.geometry.geometryGroups ) {
  9674. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  9675. }
  9676. } else if ( object instanceof THREE.Ribbon ) {
  9677. deleteRibbonBuffers( object.geometry );
  9678. } else if ( object instanceof THREE.Line ) {
  9679. deleteLineBuffers( object.geometry );
  9680. } else if ( object instanceof THREE.ParticleSystem ) {
  9681. deleteParticleBuffers( object.geometry );
  9682. }
  9683. };
  9684. this.deallocateTexture = function ( texture ) {
  9685. // cube texture
  9686. if ( texture.image && texture.image.__webglTextureCube ) {
  9687. _gl.deleteTexture( texture.image.__webglTextureCube );
  9688. // 2D texture
  9689. } else {
  9690. if ( ! texture.__webglInit ) return;
  9691. texture.__webglInit = false;
  9692. _gl.deleteTexture( texture.__webglTexture );
  9693. }
  9694. _this.info.memory.textures --;
  9695. };
  9696. this.deallocateRenderTarget = function ( renderTarget ) {
  9697. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  9698. _gl.deleteTexture( renderTarget.__webglTexture );
  9699. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9700. for ( var i = 0; i < 6; i ++ ) {
  9701. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  9702. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  9703. }
  9704. } else {
  9705. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  9706. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  9707. }
  9708. };
  9709. this.deallocateMaterial = function ( material ) {
  9710. var program = material.program;
  9711. if ( ! program ) return;
  9712. material.program = undefined;
  9713. // only deallocate GL program if this was the last use of shared program
  9714. // assumed there is only single copy of any program in the _programs list
  9715. // (that's how it's constructed)
  9716. var i, il, programInfo;
  9717. var deleteProgram = false;
  9718. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9719. programInfo = _programs[ i ];
  9720. if ( programInfo.program === program ) {
  9721. programInfo.usedTimes --;
  9722. if ( programInfo.usedTimes === 0 ) {
  9723. deleteProgram = true;
  9724. }
  9725. break;
  9726. }
  9727. }
  9728. if ( deleteProgram ) {
  9729. // avoid using array.splice, this is costlier than creating new array from scratch
  9730. var newPrograms = [];
  9731. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9732. programInfo = _programs[ i ];
  9733. if ( programInfo.program !== program ) {
  9734. newPrograms.push( programInfo );
  9735. }
  9736. }
  9737. _programs = newPrograms;
  9738. _gl.deleteProgram( program );
  9739. _this.info.memory.programs --;
  9740. }
  9741. };
  9742. // Rendering
  9743. this.updateShadowMap = function ( scene, camera ) {
  9744. _currentProgram = null;
  9745. _oldBlending = -1;
  9746. _oldDepthTest = -1;
  9747. _oldDepthWrite = -1;
  9748. _currentGeometryGroupHash = -1;
  9749. _currentMaterialId = -1;
  9750. _lightsNeedUpdate = true;
  9751. _oldDoubleSided = -1;
  9752. _oldFlipSided = -1;
  9753. this.shadowMapPlugin.update( scene, camera );
  9754. };
  9755. // Internal functions
  9756. // Buffer allocation
  9757. function createParticleBuffers ( geometry ) {
  9758. geometry.__webglVertexBuffer = _gl.createBuffer();
  9759. geometry.__webglColorBuffer = _gl.createBuffer();
  9760. _this.info.memory.geometries ++;
  9761. };
  9762. function createLineBuffers ( geometry ) {
  9763. geometry.__webglVertexBuffer = _gl.createBuffer();
  9764. geometry.__webglColorBuffer = _gl.createBuffer();
  9765. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  9766. _this.info.memory.geometries ++;
  9767. };
  9768. function createRibbonBuffers ( geometry ) {
  9769. geometry.__webglVertexBuffer = _gl.createBuffer();
  9770. geometry.__webglColorBuffer = _gl.createBuffer();
  9771. geometry.__webglNormalBuffer = _gl.createBuffer();
  9772. _this.info.memory.geometries ++;
  9773. };
  9774. function createMeshBuffers ( geometryGroup ) {
  9775. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  9776. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  9777. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  9778. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  9779. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  9780. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  9781. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  9782. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  9783. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  9784. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  9785. var m, ml;
  9786. if ( geometryGroup.numMorphTargets ) {
  9787. geometryGroup.__webglMorphTargetsBuffers = [];
  9788. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9789. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  9790. }
  9791. }
  9792. if ( geometryGroup.numMorphNormals ) {
  9793. geometryGroup.__webglMorphNormalsBuffers = [];
  9794. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9795. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  9796. }
  9797. }
  9798. _this.info.memory.geometries ++;
  9799. };
  9800. // Buffer deallocation
  9801. function deleteParticleBuffers ( geometry ) {
  9802. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9803. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9804. deleteCustomAttributesBuffers( geometry );
  9805. _this.info.memory.geometries --;
  9806. };
  9807. function deleteLineBuffers ( geometry ) {
  9808. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9809. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9810. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  9811. deleteCustomAttributesBuffers( geometry );
  9812. _this.info.memory.geometries --;
  9813. };
  9814. function deleteRibbonBuffers ( geometry ) {
  9815. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9816. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9817. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  9818. deleteCustomAttributesBuffers( geometry );
  9819. _this.info.memory.geometries --;
  9820. };
  9821. function deleteMeshBuffers ( geometryGroup ) {
  9822. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  9823. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  9824. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  9825. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  9826. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  9827. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  9828. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  9829. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  9830. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  9831. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  9832. var m, ml;
  9833. if ( geometryGroup.numMorphTargets ) {
  9834. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9835. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  9836. }
  9837. }
  9838. if ( geometryGroup.numMorphNormals ) {
  9839. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9840. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  9841. }
  9842. }
  9843. deleteCustomAttributesBuffers( geometryGroup );
  9844. _this.info.memory.geometries --;
  9845. };
  9846. function deleteCustomAttributesBuffers( geometry ) {
  9847. if ( geometry.__webglCustomAttributesList ) {
  9848. for ( var id in geometry.__webglCustomAttributesList ) {
  9849. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  9850. }
  9851. }
  9852. };
  9853. // Buffer initialization
  9854. function initCustomAttributes ( geometry, object ) {
  9855. var nvertices = geometry.vertices.length;
  9856. var material = object.material;
  9857. if ( material.attributes ) {
  9858. if ( geometry.__webglCustomAttributesList === undefined ) {
  9859. geometry.__webglCustomAttributesList = [];
  9860. }
  9861. for ( var a in material.attributes ) {
  9862. var attribute = material.attributes[ a ];
  9863. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9864. attribute.__webglInitialized = true;
  9865. var size = 1; // "f" and "i"
  9866. if ( attribute.type === "v2" ) size = 2;
  9867. else if ( attribute.type === "v3" ) size = 3;
  9868. else if ( attribute.type === "v4" ) size = 4;
  9869. else if ( attribute.type === "c" ) size = 3;
  9870. attribute.size = size;
  9871. attribute.array = new Float32Array( nvertices * size );
  9872. attribute.buffer = _gl.createBuffer();
  9873. attribute.buffer.belongsToAttribute = a;
  9874. attribute.needsUpdate = true;
  9875. }
  9876. geometry.__webglCustomAttributesList.push( attribute );
  9877. }
  9878. }
  9879. };
  9880. function initParticleBuffers ( geometry, object ) {
  9881. var nvertices = geometry.vertices.length;
  9882. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9883. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9884. geometry.__sortArray = [];
  9885. geometry.__webglParticleCount = nvertices;
  9886. initCustomAttributes ( geometry, object );
  9887. };
  9888. function initLineBuffers ( geometry, object ) {
  9889. var nvertices = geometry.vertices.length;
  9890. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9891. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9892. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  9893. geometry.__webglLineCount = nvertices;
  9894. initCustomAttributes ( geometry, object );
  9895. };
  9896. function initRibbonBuffers ( geometry, object ) {
  9897. var nvertices = geometry.vertices.length;
  9898. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9899. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9900. geometry.__normalArray = new Float32Array( nvertices * 3 );
  9901. geometry.__webglVertexCount = nvertices;
  9902. initCustomAttributes ( geometry, object );
  9903. };
  9904. function initMeshBuffers ( geometryGroup, object ) {
  9905. var geometry = object.geometry,
  9906. faces3 = geometryGroup.faces3,
  9907. faces4 = geometryGroup.faces4,
  9908. nvertices = faces3.length * 3 + faces4.length * 4,
  9909. ntris = faces3.length * 1 + faces4.length * 2,
  9910. nlines = faces3.length * 3 + faces4.length * 4,
  9911. material = getBufferMaterial( object, geometryGroup ),
  9912. uvType = bufferGuessUVType( material ),
  9913. normalType = bufferGuessNormalType( material ),
  9914. vertexColorType = bufferGuessVertexColorType( material );
  9915. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  9916. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  9917. if ( normalType ) {
  9918. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  9919. }
  9920. if ( geometry.hasTangents ) {
  9921. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  9922. }
  9923. if ( vertexColorType ) {
  9924. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  9925. }
  9926. if ( uvType ) {
  9927. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  9928. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  9929. }
  9930. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  9931. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  9932. }
  9933. }
  9934. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  9935. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  9936. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  9937. }
  9938. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  9939. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  9940. var m, ml;
  9941. if ( geometryGroup.numMorphTargets ) {
  9942. geometryGroup.__morphTargetsArrays = [];
  9943. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9944. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  9945. }
  9946. }
  9947. if ( geometryGroup.numMorphNormals ) {
  9948. geometryGroup.__morphNormalsArrays = [];
  9949. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9950. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  9951. }
  9952. }
  9953. geometryGroup.__webglFaceCount = ntris * 3;
  9954. geometryGroup.__webglLineCount = nlines * 2;
  9955. // custom attributes
  9956. if ( material.attributes ) {
  9957. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  9958. geometryGroup.__webglCustomAttributesList = [];
  9959. }
  9960. for ( var a in material.attributes ) {
  9961. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  9962. // attribute buffers which are correctly indexed in the setMeshBuffers function
  9963. var originalAttribute = material.attributes[ a ];
  9964. var attribute = {};
  9965. for ( var property in originalAttribute ) {
  9966. attribute[ property ] = originalAttribute[ property ];
  9967. }
  9968. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9969. attribute.__webglInitialized = true;
  9970. var size = 1; // "f" and "i"
  9971. if( attribute.type === "v2" ) size = 2;
  9972. else if( attribute.type === "v3" ) size = 3;
  9973. else if( attribute.type === "v4" ) size = 4;
  9974. else if( attribute.type === "c" ) size = 3;
  9975. attribute.size = size;
  9976. attribute.array = new Float32Array( nvertices * size );
  9977. attribute.buffer = _gl.createBuffer();
  9978. attribute.buffer.belongsToAttribute = a;
  9979. originalAttribute.needsUpdate = true;
  9980. attribute.__original = originalAttribute;
  9981. }
  9982. geometryGroup.__webglCustomAttributesList.push( attribute );
  9983. }
  9984. }
  9985. geometryGroup.__inittedArrays = true;
  9986. };
  9987. function getBufferMaterial( object, geometryGroup ) {
  9988. return object.material instanceof THREE.MeshFaceMaterial
  9989. ? object.material.materials[ geometryGroup.materialIndex ]
  9990. : object.material;
  9991. };
  9992. function materialNeedsSmoothNormals ( material ) {
  9993. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  9994. };
  9995. function bufferGuessNormalType ( material ) {
  9996. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  9997. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  9998. return false;
  9999. }
  10000. if ( materialNeedsSmoothNormals( material ) ) {
  10001. return THREE.SmoothShading;
  10002. } else {
  10003. return THREE.FlatShading;
  10004. }
  10005. };
  10006. function bufferGuessVertexColorType ( material ) {
  10007. if ( material.vertexColors ) {
  10008. return material.vertexColors;
  10009. }
  10010. return false;
  10011. };
  10012. function bufferGuessUVType ( material ) {
  10013. // material must use some texture to require uvs
  10014. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  10015. return true;
  10016. }
  10017. return false;
  10018. };
  10019. //
  10020. function initDirectBuffers( geometry ) {
  10021. var a, attribute, type;
  10022. for ( a in geometry.attributes ) {
  10023. if ( a === "index" ) {
  10024. type = _gl.ELEMENT_ARRAY_BUFFER;
  10025. } else {
  10026. type = _gl.ARRAY_BUFFER;
  10027. }
  10028. attribute = geometry.attributes[ a ];
  10029. attribute.buffer = _gl.createBuffer();
  10030. _gl.bindBuffer( type, attribute.buffer );
  10031. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  10032. }
  10033. };
  10034. // Buffer setting
  10035. function setParticleBuffers ( geometry, hint, object ) {
  10036. var v, c, vertex, offset, index, color,
  10037. vertices = geometry.vertices,
  10038. vl = vertices.length,
  10039. colors = geometry.colors,
  10040. cl = colors.length,
  10041. vertexArray = geometry.__vertexArray,
  10042. colorArray = geometry.__colorArray,
  10043. sortArray = geometry.__sortArray,
  10044. dirtyVertices = geometry.verticesNeedUpdate,
  10045. dirtyElements = geometry.elementsNeedUpdate,
  10046. dirtyColors = geometry.colorsNeedUpdate,
  10047. customAttributes = geometry.__webglCustomAttributesList,
  10048. i, il,
  10049. a, ca, cal, value,
  10050. customAttribute;
  10051. if ( object.sortParticles ) {
  10052. _projScreenMatrixPS.copy( _projScreenMatrix );
  10053. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  10054. for ( v = 0; v < vl; v ++ ) {
  10055. vertex = vertices[ v ];
  10056. _vector3.copy( vertex );
  10057. _projScreenMatrixPS.multiplyVector3( _vector3 );
  10058. sortArray[ v ] = [ _vector3.z, v ];
  10059. }
  10060. sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
  10061. for ( v = 0; v < vl; v ++ ) {
  10062. vertex = vertices[ sortArray[v][1] ];
  10063. offset = v * 3;
  10064. vertexArray[ offset ] = vertex.x;
  10065. vertexArray[ offset + 1 ] = vertex.y;
  10066. vertexArray[ offset + 2 ] = vertex.z;
  10067. }
  10068. for ( c = 0; c < cl; c ++ ) {
  10069. offset = c * 3;
  10070. color = colors[ sortArray[c][1] ];
  10071. colorArray[ offset ] = color.r;
  10072. colorArray[ offset + 1 ] = color.g;
  10073. colorArray[ offset + 2 ] = color.b;
  10074. }
  10075. if ( customAttributes ) {
  10076. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10077. customAttribute = customAttributes[ i ];
  10078. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  10079. offset = 0;
  10080. cal = customAttribute.value.length;
  10081. if ( customAttribute.size === 1 ) {
  10082. for ( ca = 0; ca < cal; ca ++ ) {
  10083. index = sortArray[ ca ][ 1 ];
  10084. customAttribute.array[ ca ] = customAttribute.value[ index ];
  10085. }
  10086. } else if ( customAttribute.size === 2 ) {
  10087. for ( ca = 0; ca < cal; ca ++ ) {
  10088. index = sortArray[ ca ][ 1 ];
  10089. value = customAttribute.value[ index ];
  10090. customAttribute.array[ offset ] = value.x;
  10091. customAttribute.array[ offset + 1 ] = value.y;
  10092. offset += 2;
  10093. }
  10094. } else if ( customAttribute.size === 3 ) {
  10095. if ( customAttribute.type === "c" ) {
  10096. for ( ca = 0; ca < cal; ca ++ ) {
  10097. index = sortArray[ ca ][ 1 ];
  10098. value = customAttribute.value[ index ];
  10099. customAttribute.array[ offset ] = value.r;
  10100. customAttribute.array[ offset + 1 ] = value.g;
  10101. customAttribute.array[ offset + 2 ] = value.b;
  10102. offset += 3;
  10103. }
  10104. } else {
  10105. for ( ca = 0; ca < cal; ca ++ ) {
  10106. index = sortArray[ ca ][ 1 ];
  10107. value = customAttribute.value[ index ];
  10108. customAttribute.array[ offset ] = value.x;
  10109. customAttribute.array[ offset + 1 ] = value.y;
  10110. customAttribute.array[ offset + 2 ] = value.z;
  10111. offset += 3;
  10112. }
  10113. }
  10114. } else if ( customAttribute.size === 4 ) {
  10115. for ( ca = 0; ca < cal; ca ++ ) {
  10116. index = sortArray[ ca ][ 1 ];
  10117. value = customAttribute.value[ index ];
  10118. customAttribute.array[ offset ] = value.x;
  10119. customAttribute.array[ offset + 1 ] = value.y;
  10120. customAttribute.array[ offset + 2 ] = value.z;
  10121. customAttribute.array[ offset + 3 ] = value.w;
  10122. offset += 4;
  10123. }
  10124. }
  10125. }
  10126. }
  10127. } else {
  10128. if ( dirtyVertices ) {
  10129. for ( v = 0; v < vl; v ++ ) {
  10130. vertex = vertices[ v ];
  10131. offset = v * 3;
  10132. vertexArray[ offset ] = vertex.x;
  10133. vertexArray[ offset + 1 ] = vertex.y;
  10134. vertexArray[ offset + 2 ] = vertex.z;
  10135. }
  10136. }
  10137. if ( dirtyColors ) {
  10138. for ( c = 0; c < cl; c ++ ) {
  10139. color = colors[ c ];
  10140. offset = c * 3;
  10141. colorArray[ offset ] = color.r;
  10142. colorArray[ offset + 1 ] = color.g;
  10143. colorArray[ offset + 2 ] = color.b;
  10144. }
  10145. }
  10146. if ( customAttributes ) {
  10147. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10148. customAttribute = customAttributes[ i ];
  10149. if ( customAttribute.needsUpdate &&
  10150. ( customAttribute.boundTo === undefined ||
  10151. customAttribute.boundTo === "vertices") ) {
  10152. cal = customAttribute.value.length;
  10153. offset = 0;
  10154. if ( customAttribute.size === 1 ) {
  10155. for ( ca = 0; ca < cal; ca ++ ) {
  10156. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10157. }
  10158. } else if ( customAttribute.size === 2 ) {
  10159. for ( ca = 0; ca < cal; ca ++ ) {
  10160. value = customAttribute.value[ ca ];
  10161. customAttribute.array[ offset ] = value.x;
  10162. customAttribute.array[ offset + 1 ] = value.y;
  10163. offset += 2;
  10164. }
  10165. } else if ( customAttribute.size === 3 ) {
  10166. if ( customAttribute.type === "c" ) {
  10167. for ( ca = 0; ca < cal; ca ++ ) {
  10168. value = customAttribute.value[ ca ];
  10169. customAttribute.array[ offset ] = value.r;
  10170. customAttribute.array[ offset + 1 ] = value.g;
  10171. customAttribute.array[ offset + 2 ] = value.b;
  10172. offset += 3;
  10173. }
  10174. } else {
  10175. for ( ca = 0; ca < cal; ca ++ ) {
  10176. value = customAttribute.value[ ca ];
  10177. customAttribute.array[ offset ] = value.x;
  10178. customAttribute.array[ offset + 1 ] = value.y;
  10179. customAttribute.array[ offset + 2 ] = value.z;
  10180. offset += 3;
  10181. }
  10182. }
  10183. } else if ( customAttribute.size === 4 ) {
  10184. for ( ca = 0; ca < cal; ca ++ ) {
  10185. value = customAttribute.value[ ca ];
  10186. customAttribute.array[ offset ] = value.x;
  10187. customAttribute.array[ offset + 1 ] = value.y;
  10188. customAttribute.array[ offset + 2 ] = value.z;
  10189. customAttribute.array[ offset + 3 ] = value.w;
  10190. offset += 4;
  10191. }
  10192. }
  10193. }
  10194. }
  10195. }
  10196. }
  10197. if ( dirtyVertices || object.sortParticles ) {
  10198. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10199. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10200. }
  10201. if ( dirtyColors || object.sortParticles ) {
  10202. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10203. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10204. }
  10205. if ( customAttributes ) {
  10206. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10207. customAttribute = customAttributes[ i ];
  10208. if ( customAttribute.needsUpdate || object.sortParticles ) {
  10209. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10210. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10211. }
  10212. }
  10213. }
  10214. };
  10215. function setLineBuffers ( geometry, hint ) {
  10216. var v, c, d, vertex, offset, color,
  10217. vertices = geometry.vertices,
  10218. colors = geometry.colors,
  10219. lineDistances = geometry.lineDistances,
  10220. vl = vertices.length,
  10221. cl = colors.length,
  10222. dl = lineDistances.length,
  10223. vertexArray = geometry.__vertexArray,
  10224. colorArray = geometry.__colorArray,
  10225. lineDistanceArray = geometry.__lineDistanceArray,
  10226. dirtyVertices = geometry.verticesNeedUpdate,
  10227. dirtyColors = geometry.colorsNeedUpdate,
  10228. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  10229. customAttributes = geometry.__webglCustomAttributesList,
  10230. i, il,
  10231. a, ca, cal, value,
  10232. customAttribute;
  10233. if ( dirtyVertices ) {
  10234. for ( v = 0; v < vl; v ++ ) {
  10235. vertex = vertices[ v ];
  10236. offset = v * 3;
  10237. vertexArray[ offset ] = vertex.x;
  10238. vertexArray[ offset + 1 ] = vertex.y;
  10239. vertexArray[ offset + 2 ] = vertex.z;
  10240. }
  10241. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10242. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10243. }
  10244. if ( dirtyColors ) {
  10245. for ( c = 0; c < cl; c ++ ) {
  10246. color = colors[ c ];
  10247. offset = c * 3;
  10248. colorArray[ offset ] = color.r;
  10249. colorArray[ offset + 1 ] = color.g;
  10250. colorArray[ offset + 2 ] = color.b;
  10251. }
  10252. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10253. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10254. }
  10255. if ( dirtyLineDistances ) {
  10256. for ( d = 0; d < dl; d ++ ) {
  10257. lineDistanceArray[ d ] = lineDistances[ d ];
  10258. }
  10259. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  10260. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  10261. }
  10262. if ( customAttributes ) {
  10263. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10264. customAttribute = customAttributes[ i ];
  10265. if ( customAttribute.needsUpdate &&
  10266. ( customAttribute.boundTo === undefined ||
  10267. customAttribute.boundTo === "vertices" ) ) {
  10268. offset = 0;
  10269. cal = customAttribute.value.length;
  10270. if ( customAttribute.size === 1 ) {
  10271. for ( ca = 0; ca < cal; ca ++ ) {
  10272. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10273. }
  10274. } else if ( customAttribute.size === 2 ) {
  10275. for ( ca = 0; ca < cal; ca ++ ) {
  10276. value = customAttribute.value[ ca ];
  10277. customAttribute.array[ offset ] = value.x;
  10278. customAttribute.array[ offset + 1 ] = value.y;
  10279. offset += 2;
  10280. }
  10281. } else if ( customAttribute.size === 3 ) {
  10282. if ( customAttribute.type === "c" ) {
  10283. for ( ca = 0; ca < cal; ca ++ ) {
  10284. value = customAttribute.value[ ca ];
  10285. customAttribute.array[ offset ] = value.r;
  10286. customAttribute.array[ offset + 1 ] = value.g;
  10287. customAttribute.array[ offset + 2 ] = value.b;
  10288. offset += 3;
  10289. }
  10290. } else {
  10291. for ( ca = 0; ca < cal; ca ++ ) {
  10292. value = customAttribute.value[ ca ];
  10293. customAttribute.array[ offset ] = value.x;
  10294. customAttribute.array[ offset + 1 ] = value.y;
  10295. customAttribute.array[ offset + 2 ] = value.z;
  10296. offset += 3;
  10297. }
  10298. }
  10299. } else if ( customAttribute.size === 4 ) {
  10300. for ( ca = 0; ca < cal; ca ++ ) {
  10301. value = customAttribute.value[ ca ];
  10302. customAttribute.array[ offset ] = value.x;
  10303. customAttribute.array[ offset + 1 ] = value.y;
  10304. customAttribute.array[ offset + 2 ] = value.z;
  10305. customAttribute.array[ offset + 3 ] = value.w;
  10306. offset += 4;
  10307. }
  10308. }
  10309. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10310. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10311. }
  10312. }
  10313. }
  10314. };
  10315. function setRibbonBuffers ( geometry, hint ) {
  10316. var v, c, n, vertex, offset, color, normal,
  10317. i, il, ca, cal, customAttribute, value,
  10318. vertices = geometry.vertices,
  10319. colors = geometry.colors,
  10320. normals = geometry.normals,
  10321. vl = vertices.length,
  10322. cl = colors.length,
  10323. nl = normals.length,
  10324. vertexArray = geometry.__vertexArray,
  10325. colorArray = geometry.__colorArray,
  10326. normalArray = geometry.__normalArray,
  10327. dirtyVertices = geometry.verticesNeedUpdate,
  10328. dirtyColors = geometry.colorsNeedUpdate,
  10329. dirtyNormals = geometry.normalsNeedUpdate,
  10330. customAttributes = geometry.__webglCustomAttributesList;
  10331. if ( dirtyVertices ) {
  10332. for ( v = 0; v < vl; v ++ ) {
  10333. vertex = vertices[ v ];
  10334. offset = v * 3;
  10335. vertexArray[ offset ] = vertex.x;
  10336. vertexArray[ offset + 1 ] = vertex.y;
  10337. vertexArray[ offset + 2 ] = vertex.z;
  10338. }
  10339. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10340. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10341. }
  10342. if ( dirtyColors ) {
  10343. for ( c = 0; c < cl; c ++ ) {
  10344. color = colors[ c ];
  10345. offset = c * 3;
  10346. colorArray[ offset ] = color.r;
  10347. colorArray[ offset + 1 ] = color.g;
  10348. colorArray[ offset + 2 ] = color.b;
  10349. }
  10350. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10351. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10352. }
  10353. if ( dirtyNormals ) {
  10354. for ( n = 0; n < nl; n ++ ) {
  10355. normal = normals[ n ];
  10356. offset = n * 3;
  10357. normalArray[ offset ] = normal.x;
  10358. normalArray[ offset + 1 ] = normal.y;
  10359. normalArray[ offset + 2 ] = normal.z;
  10360. }
  10361. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  10362. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10363. }
  10364. if ( customAttributes ) {
  10365. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10366. customAttribute = customAttributes[ i ];
  10367. if ( customAttribute.needsUpdate &&
  10368. ( customAttribute.boundTo === undefined ||
  10369. customAttribute.boundTo === "vertices" ) ) {
  10370. offset = 0;
  10371. cal = customAttribute.value.length;
  10372. if ( customAttribute.size === 1 ) {
  10373. for ( ca = 0; ca < cal; ca ++ ) {
  10374. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10375. }
  10376. } else if ( customAttribute.size === 2 ) {
  10377. for ( ca = 0; ca < cal; ca ++ ) {
  10378. value = customAttribute.value[ ca ];
  10379. customAttribute.array[ offset ] = value.x;
  10380. customAttribute.array[ offset + 1 ] = value.y;
  10381. offset += 2;
  10382. }
  10383. } else if ( customAttribute.size === 3 ) {
  10384. if ( customAttribute.type === "c" ) {
  10385. for ( ca = 0; ca < cal; ca ++ ) {
  10386. value = customAttribute.value[ ca ];
  10387. customAttribute.array[ offset ] = value.r;
  10388. customAttribute.array[ offset + 1 ] = value.g;
  10389. customAttribute.array[ offset + 2 ] = value.b;
  10390. offset += 3;
  10391. }
  10392. } else {
  10393. for ( ca = 0; ca < cal; ca ++ ) {
  10394. value = customAttribute.value[ ca ];
  10395. customAttribute.array[ offset ] = value.x;
  10396. customAttribute.array[ offset + 1 ] = value.y;
  10397. customAttribute.array[ offset + 2 ] = value.z;
  10398. offset += 3;
  10399. }
  10400. }
  10401. } else if ( customAttribute.size === 4 ) {
  10402. for ( ca = 0; ca < cal; ca ++ ) {
  10403. value = customAttribute.value[ ca ];
  10404. customAttribute.array[ offset ] = value.x;
  10405. customAttribute.array[ offset + 1 ] = value.y;
  10406. customAttribute.array[ offset + 2 ] = value.z;
  10407. customAttribute.array[ offset + 3 ] = value.w;
  10408. offset += 4;
  10409. }
  10410. }
  10411. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10412. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10413. }
  10414. }
  10415. }
  10416. };
  10417. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  10418. if ( ! geometryGroup.__inittedArrays ) {
  10419. return;
  10420. }
  10421. var normalType = bufferGuessNormalType( material ),
  10422. vertexColorType = bufferGuessVertexColorType( material ),
  10423. uvType = bufferGuessUVType( material ),
  10424. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  10425. var f, fl, fi, face,
  10426. vertexNormals, faceNormal, normal,
  10427. vertexColors, faceColor,
  10428. vertexTangents,
  10429. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  10430. c1, c2, c3, c4,
  10431. sw1, sw2, sw3, sw4,
  10432. si1, si2, si3, si4,
  10433. sa1, sa2, sa3, sa4,
  10434. sb1, sb2, sb3, sb4,
  10435. m, ml, i, il,
  10436. vn, uvi, uv2i,
  10437. vk, vkl, vka,
  10438. nka, chf, faceVertexNormals,
  10439. a,
  10440. vertexIndex = 0,
  10441. offset = 0,
  10442. offset_uv = 0,
  10443. offset_uv2 = 0,
  10444. offset_face = 0,
  10445. offset_normal = 0,
  10446. offset_tangent = 0,
  10447. offset_line = 0,
  10448. offset_color = 0,
  10449. offset_skin = 0,
  10450. offset_morphTarget = 0,
  10451. offset_custom = 0,
  10452. offset_customSrc = 0,
  10453. value,
  10454. vertexArray = geometryGroup.__vertexArray,
  10455. uvArray = geometryGroup.__uvArray,
  10456. uv2Array = geometryGroup.__uv2Array,
  10457. normalArray = geometryGroup.__normalArray,
  10458. tangentArray = geometryGroup.__tangentArray,
  10459. colorArray = geometryGroup.__colorArray,
  10460. skinIndexArray = geometryGroup.__skinIndexArray,
  10461. skinWeightArray = geometryGroup.__skinWeightArray,
  10462. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  10463. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  10464. customAttributes = geometryGroup.__webglCustomAttributesList,
  10465. customAttribute,
  10466. faceArray = geometryGroup.__faceArray,
  10467. lineArray = geometryGroup.__lineArray,
  10468. geometry = object.geometry, // this is shared for all chunks
  10469. dirtyVertices = geometry.verticesNeedUpdate,
  10470. dirtyElements = geometry.elementsNeedUpdate,
  10471. dirtyUvs = geometry.uvsNeedUpdate,
  10472. dirtyNormals = geometry.normalsNeedUpdate,
  10473. dirtyTangents = geometry.tangentsNeedUpdate,
  10474. dirtyColors = geometry.colorsNeedUpdate,
  10475. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  10476. vertices = geometry.vertices,
  10477. chunk_faces3 = geometryGroup.faces3,
  10478. chunk_faces4 = geometryGroup.faces4,
  10479. obj_faces = geometry.faces,
  10480. obj_uvs = geometry.faceVertexUvs[ 0 ],
  10481. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  10482. obj_colors = geometry.colors,
  10483. obj_skinIndices = geometry.skinIndices,
  10484. obj_skinWeights = geometry.skinWeights,
  10485. morphTargets = geometry.morphTargets,
  10486. morphNormals = geometry.morphNormals;
  10487. if ( dirtyVertices ) {
  10488. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10489. face = obj_faces[ chunk_faces3[ f ] ];
  10490. v1 = vertices[ face.a ];
  10491. v2 = vertices[ face.b ];
  10492. v3 = vertices[ face.c ];
  10493. vertexArray[ offset ] = v1.x;
  10494. vertexArray[ offset + 1 ] = v1.y;
  10495. vertexArray[ offset + 2 ] = v1.z;
  10496. vertexArray[ offset + 3 ] = v2.x;
  10497. vertexArray[ offset + 4 ] = v2.y;
  10498. vertexArray[ offset + 5 ] = v2.z;
  10499. vertexArray[ offset + 6 ] = v3.x;
  10500. vertexArray[ offset + 7 ] = v3.y;
  10501. vertexArray[ offset + 8 ] = v3.z;
  10502. offset += 9;
  10503. }
  10504. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10505. face = obj_faces[ chunk_faces4[ f ] ];
  10506. v1 = vertices[ face.a ];
  10507. v2 = vertices[ face.b ];
  10508. v3 = vertices[ face.c ];
  10509. v4 = vertices[ face.d ];
  10510. vertexArray[ offset ] = v1.x;
  10511. vertexArray[ offset + 1 ] = v1.y;
  10512. vertexArray[ offset + 2 ] = v1.z;
  10513. vertexArray[ offset + 3 ] = v2.x;
  10514. vertexArray[ offset + 4 ] = v2.y;
  10515. vertexArray[ offset + 5 ] = v2.z;
  10516. vertexArray[ offset + 6 ] = v3.x;
  10517. vertexArray[ offset + 7 ] = v3.y;
  10518. vertexArray[ offset + 8 ] = v3.z;
  10519. vertexArray[ offset + 9 ] = v4.x;
  10520. vertexArray[ offset + 10 ] = v4.y;
  10521. vertexArray[ offset + 11 ] = v4.z;
  10522. offset += 12;
  10523. }
  10524. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  10525. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10526. }
  10527. if ( dirtyMorphTargets ) {
  10528. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  10529. offset_morphTarget = 0;
  10530. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10531. chf = chunk_faces3[ f ];
  10532. face = obj_faces[ chf ];
  10533. // morph positions
  10534. v1 = morphTargets[ vk ].vertices[ face.a ];
  10535. v2 = morphTargets[ vk ].vertices[ face.b ];
  10536. v3 = morphTargets[ vk ].vertices[ face.c ];
  10537. vka = morphTargetsArrays[ vk ];
  10538. vka[ offset_morphTarget ] = v1.x;
  10539. vka[ offset_morphTarget + 1 ] = v1.y;
  10540. vka[ offset_morphTarget + 2 ] = v1.z;
  10541. vka[ offset_morphTarget + 3 ] = v2.x;
  10542. vka[ offset_morphTarget + 4 ] = v2.y;
  10543. vka[ offset_morphTarget + 5 ] = v2.z;
  10544. vka[ offset_morphTarget + 6 ] = v3.x;
  10545. vka[ offset_morphTarget + 7 ] = v3.y;
  10546. vka[ offset_morphTarget + 8 ] = v3.z;
  10547. // morph normals
  10548. if ( material.morphNormals ) {
  10549. if ( needsSmoothNormals ) {
  10550. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10551. n1 = faceVertexNormals.a;
  10552. n2 = faceVertexNormals.b;
  10553. n3 = faceVertexNormals.c;
  10554. } else {
  10555. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10556. n2 = n1;
  10557. n3 = n1;
  10558. }
  10559. nka = morphNormalsArrays[ vk ];
  10560. nka[ offset_morphTarget ] = n1.x;
  10561. nka[ offset_morphTarget + 1 ] = n1.y;
  10562. nka[ offset_morphTarget + 2 ] = n1.z;
  10563. nka[ offset_morphTarget + 3 ] = n2.x;
  10564. nka[ offset_morphTarget + 4 ] = n2.y;
  10565. nka[ offset_morphTarget + 5 ] = n2.z;
  10566. nka[ offset_morphTarget + 6 ] = n3.x;
  10567. nka[ offset_morphTarget + 7 ] = n3.y;
  10568. nka[ offset_morphTarget + 8 ] = n3.z;
  10569. }
  10570. //
  10571. offset_morphTarget += 9;
  10572. }
  10573. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10574. chf = chunk_faces4[ f ];
  10575. face = obj_faces[ chf ];
  10576. // morph positions
  10577. v1 = morphTargets[ vk ].vertices[ face.a ];
  10578. v2 = morphTargets[ vk ].vertices[ face.b ];
  10579. v3 = morphTargets[ vk ].vertices[ face.c ];
  10580. v4 = morphTargets[ vk ].vertices[ face.d ];
  10581. vka = morphTargetsArrays[ vk ];
  10582. vka[ offset_morphTarget ] = v1.x;
  10583. vka[ offset_morphTarget + 1 ] = v1.y;
  10584. vka[ offset_morphTarget + 2 ] = v1.z;
  10585. vka[ offset_morphTarget + 3 ] = v2.x;
  10586. vka[ offset_morphTarget + 4 ] = v2.y;
  10587. vka[ offset_morphTarget + 5 ] = v2.z;
  10588. vka[ offset_morphTarget + 6 ] = v3.x;
  10589. vka[ offset_morphTarget + 7 ] = v3.y;
  10590. vka[ offset_morphTarget + 8 ] = v3.z;
  10591. vka[ offset_morphTarget + 9 ] = v4.x;
  10592. vka[ offset_morphTarget + 10 ] = v4.y;
  10593. vka[ offset_morphTarget + 11 ] = v4.z;
  10594. // morph normals
  10595. if ( material.morphNormals ) {
  10596. if ( needsSmoothNormals ) {
  10597. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10598. n1 = faceVertexNormals.a;
  10599. n2 = faceVertexNormals.b;
  10600. n3 = faceVertexNormals.c;
  10601. n4 = faceVertexNormals.d;
  10602. } else {
  10603. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10604. n2 = n1;
  10605. n3 = n1;
  10606. n4 = n1;
  10607. }
  10608. nka = morphNormalsArrays[ vk ];
  10609. nka[ offset_morphTarget ] = n1.x;
  10610. nka[ offset_morphTarget + 1 ] = n1.y;
  10611. nka[ offset_morphTarget + 2 ] = n1.z;
  10612. nka[ offset_morphTarget + 3 ] = n2.x;
  10613. nka[ offset_morphTarget + 4 ] = n2.y;
  10614. nka[ offset_morphTarget + 5 ] = n2.z;
  10615. nka[ offset_morphTarget + 6 ] = n3.x;
  10616. nka[ offset_morphTarget + 7 ] = n3.y;
  10617. nka[ offset_morphTarget + 8 ] = n3.z;
  10618. nka[ offset_morphTarget + 9 ] = n4.x;
  10619. nka[ offset_morphTarget + 10 ] = n4.y;
  10620. nka[ offset_morphTarget + 11 ] = n4.z;
  10621. }
  10622. //
  10623. offset_morphTarget += 12;
  10624. }
  10625. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  10626. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  10627. if ( material.morphNormals ) {
  10628. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  10629. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  10630. }
  10631. }
  10632. }
  10633. if ( obj_skinWeights.length ) {
  10634. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10635. face = obj_faces[ chunk_faces3[ f ] ];
  10636. // weights
  10637. sw1 = obj_skinWeights[ face.a ];
  10638. sw2 = obj_skinWeights[ face.b ];
  10639. sw3 = obj_skinWeights[ face.c ];
  10640. skinWeightArray[ offset_skin ] = sw1.x;
  10641. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10642. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10643. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10644. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10645. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10646. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10647. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10648. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10649. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10650. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10651. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10652. // indices
  10653. si1 = obj_skinIndices[ face.a ];
  10654. si2 = obj_skinIndices[ face.b ];
  10655. si3 = obj_skinIndices[ face.c ];
  10656. skinIndexArray[ offset_skin ] = si1.x;
  10657. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10658. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10659. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10660. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10661. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10662. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10663. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10664. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10665. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10666. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10667. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10668. offset_skin += 12;
  10669. }
  10670. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10671. face = obj_faces[ chunk_faces4[ f ] ];
  10672. // weights
  10673. sw1 = obj_skinWeights[ face.a ];
  10674. sw2 = obj_skinWeights[ face.b ];
  10675. sw3 = obj_skinWeights[ face.c ];
  10676. sw4 = obj_skinWeights[ face.d ];
  10677. skinWeightArray[ offset_skin ] = sw1.x;
  10678. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10679. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10680. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10681. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10682. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10683. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10684. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10685. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10686. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10687. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10688. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10689. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  10690. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  10691. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  10692. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  10693. // indices
  10694. si1 = obj_skinIndices[ face.a ];
  10695. si2 = obj_skinIndices[ face.b ];
  10696. si3 = obj_skinIndices[ face.c ];
  10697. si4 = obj_skinIndices[ face.d ];
  10698. skinIndexArray[ offset_skin ] = si1.x;
  10699. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10700. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10701. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10702. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10703. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10704. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10705. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10706. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10707. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10708. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10709. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10710. skinIndexArray[ offset_skin + 12 ] = si4.x;
  10711. skinIndexArray[ offset_skin + 13 ] = si4.y;
  10712. skinIndexArray[ offset_skin + 14 ] = si4.z;
  10713. skinIndexArray[ offset_skin + 15 ] = si4.w;
  10714. offset_skin += 16;
  10715. }
  10716. if ( offset_skin > 0 ) {
  10717. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10718. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  10719. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10720. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  10721. }
  10722. }
  10723. if ( dirtyColors && vertexColorType ) {
  10724. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10725. face = obj_faces[ chunk_faces3[ f ] ];
  10726. vertexColors = face.vertexColors;
  10727. faceColor = face.color;
  10728. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  10729. c1 = vertexColors[ 0 ];
  10730. c2 = vertexColors[ 1 ];
  10731. c3 = vertexColors[ 2 ];
  10732. } else {
  10733. c1 = faceColor;
  10734. c2 = faceColor;
  10735. c3 = faceColor;
  10736. }
  10737. colorArray[ offset_color ] = c1.r;
  10738. colorArray[ offset_color + 1 ] = c1.g;
  10739. colorArray[ offset_color + 2 ] = c1.b;
  10740. colorArray[ offset_color + 3 ] = c2.r;
  10741. colorArray[ offset_color + 4 ] = c2.g;
  10742. colorArray[ offset_color + 5 ] = c2.b;
  10743. colorArray[ offset_color + 6 ] = c3.r;
  10744. colorArray[ offset_color + 7 ] = c3.g;
  10745. colorArray[ offset_color + 8 ] = c3.b;
  10746. offset_color += 9;
  10747. }
  10748. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10749. face = obj_faces[ chunk_faces4[ f ] ];
  10750. vertexColors = face.vertexColors;
  10751. faceColor = face.color;
  10752. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  10753. c1 = vertexColors[ 0 ];
  10754. c2 = vertexColors[ 1 ];
  10755. c3 = vertexColors[ 2 ];
  10756. c4 = vertexColors[ 3 ];
  10757. } else {
  10758. c1 = faceColor;
  10759. c2 = faceColor;
  10760. c3 = faceColor;
  10761. c4 = faceColor;
  10762. }
  10763. colorArray[ offset_color ] = c1.r;
  10764. colorArray[ offset_color + 1 ] = c1.g;
  10765. colorArray[ offset_color + 2 ] = c1.b;
  10766. colorArray[ offset_color + 3 ] = c2.r;
  10767. colorArray[ offset_color + 4 ] = c2.g;
  10768. colorArray[ offset_color + 5 ] = c2.b;
  10769. colorArray[ offset_color + 6 ] = c3.r;
  10770. colorArray[ offset_color + 7 ] = c3.g;
  10771. colorArray[ offset_color + 8 ] = c3.b;
  10772. colorArray[ offset_color + 9 ] = c4.r;
  10773. colorArray[ offset_color + 10 ] = c4.g;
  10774. colorArray[ offset_color + 11 ] = c4.b;
  10775. offset_color += 12;
  10776. }
  10777. if ( offset_color > 0 ) {
  10778. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  10779. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10780. }
  10781. }
  10782. if ( dirtyTangents && geometry.hasTangents ) {
  10783. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10784. face = obj_faces[ chunk_faces3[ f ] ];
  10785. vertexTangents = face.vertexTangents;
  10786. t1 = vertexTangents[ 0 ];
  10787. t2 = vertexTangents[ 1 ];
  10788. t3 = vertexTangents[ 2 ];
  10789. tangentArray[ offset_tangent ] = t1.x;
  10790. tangentArray[ offset_tangent + 1 ] = t1.y;
  10791. tangentArray[ offset_tangent + 2 ] = t1.z;
  10792. tangentArray[ offset_tangent + 3 ] = t1.w;
  10793. tangentArray[ offset_tangent + 4 ] = t2.x;
  10794. tangentArray[ offset_tangent + 5 ] = t2.y;
  10795. tangentArray[ offset_tangent + 6 ] = t2.z;
  10796. tangentArray[ offset_tangent + 7 ] = t2.w;
  10797. tangentArray[ offset_tangent + 8 ] = t3.x;
  10798. tangentArray[ offset_tangent + 9 ] = t3.y;
  10799. tangentArray[ offset_tangent + 10 ] = t3.z;
  10800. tangentArray[ offset_tangent + 11 ] = t3.w;
  10801. offset_tangent += 12;
  10802. }
  10803. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10804. face = obj_faces[ chunk_faces4[ f ] ];
  10805. vertexTangents = face.vertexTangents;
  10806. t1 = vertexTangents[ 0 ];
  10807. t2 = vertexTangents[ 1 ];
  10808. t3 = vertexTangents[ 2 ];
  10809. t4 = vertexTangents[ 3 ];
  10810. tangentArray[ offset_tangent ] = t1.x;
  10811. tangentArray[ offset_tangent + 1 ] = t1.y;
  10812. tangentArray[ offset_tangent + 2 ] = t1.z;
  10813. tangentArray[ offset_tangent + 3 ] = t1.w;
  10814. tangentArray[ offset_tangent + 4 ] = t2.x;
  10815. tangentArray[ offset_tangent + 5 ] = t2.y;
  10816. tangentArray[ offset_tangent + 6 ] = t2.z;
  10817. tangentArray[ offset_tangent + 7 ] = t2.w;
  10818. tangentArray[ offset_tangent + 8 ] = t3.x;
  10819. tangentArray[ offset_tangent + 9 ] = t3.y;
  10820. tangentArray[ offset_tangent + 10 ] = t3.z;
  10821. tangentArray[ offset_tangent + 11 ] = t3.w;
  10822. tangentArray[ offset_tangent + 12 ] = t4.x;
  10823. tangentArray[ offset_tangent + 13 ] = t4.y;
  10824. tangentArray[ offset_tangent + 14 ] = t4.z;
  10825. tangentArray[ offset_tangent + 15 ] = t4.w;
  10826. offset_tangent += 16;
  10827. }
  10828. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  10829. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  10830. }
  10831. if ( dirtyNormals && normalType ) {
  10832. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10833. face = obj_faces[ chunk_faces3[ f ] ];
  10834. vertexNormals = face.vertexNormals;
  10835. faceNormal = face.normal;
  10836. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  10837. for ( i = 0; i < 3; i ++ ) {
  10838. vn = vertexNormals[ i ];
  10839. normalArray[ offset_normal ] = vn.x;
  10840. normalArray[ offset_normal + 1 ] = vn.y;
  10841. normalArray[ offset_normal + 2 ] = vn.z;
  10842. offset_normal += 3;
  10843. }
  10844. } else {
  10845. for ( i = 0; i < 3; i ++ ) {
  10846. normalArray[ offset_normal ] = faceNormal.x;
  10847. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10848. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10849. offset_normal += 3;
  10850. }
  10851. }
  10852. }
  10853. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10854. face = obj_faces[ chunk_faces4[ f ] ];
  10855. vertexNormals = face.vertexNormals;
  10856. faceNormal = face.normal;
  10857. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  10858. for ( i = 0; i < 4; i ++ ) {
  10859. vn = vertexNormals[ i ];
  10860. normalArray[ offset_normal ] = vn.x;
  10861. normalArray[ offset_normal + 1 ] = vn.y;
  10862. normalArray[ offset_normal + 2 ] = vn.z;
  10863. offset_normal += 3;
  10864. }
  10865. } else {
  10866. for ( i = 0; i < 4; i ++ ) {
  10867. normalArray[ offset_normal ] = faceNormal.x;
  10868. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10869. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10870. offset_normal += 3;
  10871. }
  10872. }
  10873. }
  10874. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  10875. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10876. }
  10877. if ( dirtyUvs && obj_uvs && uvType ) {
  10878. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10879. fi = chunk_faces3[ f ];
  10880. uv = obj_uvs[ fi ];
  10881. if ( uv === undefined ) continue;
  10882. for ( i = 0; i < 3; i ++ ) {
  10883. uvi = uv[ i ];
  10884. uvArray[ offset_uv ] = uvi.u;
  10885. uvArray[ offset_uv + 1 ] = uvi.v;
  10886. offset_uv += 2;
  10887. }
  10888. }
  10889. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10890. fi = chunk_faces4[ f ];
  10891. uv = obj_uvs[ fi ];
  10892. if ( uv === undefined ) continue;
  10893. for ( i = 0; i < 4; i ++ ) {
  10894. uvi = uv[ i ];
  10895. uvArray[ offset_uv ] = uvi.u;
  10896. uvArray[ offset_uv + 1 ] = uvi.v;
  10897. offset_uv += 2;
  10898. }
  10899. }
  10900. if ( offset_uv > 0 ) {
  10901. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  10902. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  10903. }
  10904. }
  10905. if ( dirtyUvs && obj_uvs2 && uvType ) {
  10906. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10907. fi = chunk_faces3[ f ];
  10908. uv2 = obj_uvs2[ fi ];
  10909. if ( uv2 === undefined ) continue;
  10910. for ( i = 0; i < 3; i ++ ) {
  10911. uv2i = uv2[ i ];
  10912. uv2Array[ offset_uv2 ] = uv2i.u;
  10913. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10914. offset_uv2 += 2;
  10915. }
  10916. }
  10917. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10918. fi = chunk_faces4[ f ];
  10919. uv2 = obj_uvs2[ fi ];
  10920. if ( uv2 === undefined ) continue;
  10921. for ( i = 0; i < 4; i ++ ) {
  10922. uv2i = uv2[ i ];
  10923. uv2Array[ offset_uv2 ] = uv2i.u;
  10924. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10925. offset_uv2 += 2;
  10926. }
  10927. }
  10928. if ( offset_uv2 > 0 ) {
  10929. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  10930. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  10931. }
  10932. }
  10933. if ( dirtyElements ) {
  10934. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10935. faceArray[ offset_face ] = vertexIndex;
  10936. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10937. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  10938. offset_face += 3;
  10939. lineArray[ offset_line ] = vertexIndex;
  10940. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10941. lineArray[ offset_line + 2 ] = vertexIndex;
  10942. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  10943. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10944. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10945. offset_line += 6;
  10946. vertexIndex += 3;
  10947. }
  10948. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10949. faceArray[ offset_face ] = vertexIndex;
  10950. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10951. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  10952. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  10953. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  10954. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  10955. offset_face += 6;
  10956. lineArray[ offset_line ] = vertexIndex;
  10957. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10958. lineArray[ offset_line + 2 ] = vertexIndex;
  10959. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  10960. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10961. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10962. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  10963. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  10964. offset_line += 8;
  10965. vertexIndex += 4;
  10966. }
  10967. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  10968. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  10969. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  10970. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  10971. }
  10972. if ( customAttributes ) {
  10973. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10974. customAttribute = customAttributes[ i ];
  10975. if ( ! customAttribute.__original.needsUpdate ) continue;
  10976. offset_custom = 0;
  10977. offset_customSrc = 0;
  10978. if ( customAttribute.size === 1 ) {
  10979. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10980. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10981. face = obj_faces[ chunk_faces3[ f ] ];
  10982. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10983. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10984. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10985. offset_custom += 3;
  10986. }
  10987. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10988. face = obj_faces[ chunk_faces4[ f ] ];
  10989. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10990. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10991. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10992. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  10993. offset_custom += 4;
  10994. }
  10995. } else if ( customAttribute.boundTo === "faces" ) {
  10996. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10997. value = customAttribute.value[ chunk_faces3[ f ] ];
  10998. customAttribute.array[ offset_custom ] = value;
  10999. customAttribute.array[ offset_custom + 1 ] = value;
  11000. customAttribute.array[ offset_custom + 2 ] = value;
  11001. offset_custom += 3;
  11002. }
  11003. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11004. value = customAttribute.value[ chunk_faces4[ f ] ];
  11005. customAttribute.array[ offset_custom ] = value;
  11006. customAttribute.array[ offset_custom + 1 ] = value;
  11007. customAttribute.array[ offset_custom + 2 ] = value;
  11008. customAttribute.array[ offset_custom + 3 ] = value;
  11009. offset_custom += 4;
  11010. }
  11011. }
  11012. } else if ( customAttribute.size === 2 ) {
  11013. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11014. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11015. face = obj_faces[ chunk_faces3[ f ] ];
  11016. v1 = customAttribute.value[ face.a ];
  11017. v2 = customAttribute.value[ face.b ];
  11018. v3 = customAttribute.value[ face.c ];
  11019. customAttribute.array[ offset_custom ] = v1.x;
  11020. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11021. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11022. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11023. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11024. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11025. offset_custom += 6;
  11026. }
  11027. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11028. face = obj_faces[ chunk_faces4[ f ] ];
  11029. v1 = customAttribute.value[ face.a ];
  11030. v2 = customAttribute.value[ face.b ];
  11031. v3 = customAttribute.value[ face.c ];
  11032. v4 = customAttribute.value[ face.d ];
  11033. customAttribute.array[ offset_custom ] = v1.x;
  11034. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11035. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11036. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11037. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11038. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11039. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11040. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11041. offset_custom += 8;
  11042. }
  11043. } else if ( customAttribute.boundTo === "faces" ) {
  11044. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11045. value = customAttribute.value[ chunk_faces3[ f ] ];
  11046. v1 = value;
  11047. v2 = value;
  11048. v3 = value;
  11049. customAttribute.array[ offset_custom ] = v1.x;
  11050. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11051. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11052. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11053. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11054. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11055. offset_custom += 6;
  11056. }
  11057. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11058. value = customAttribute.value[ chunk_faces4[ f ] ];
  11059. v1 = value;
  11060. v2 = value;
  11061. v3 = value;
  11062. v4 = value;
  11063. customAttribute.array[ offset_custom ] = v1.x;
  11064. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11065. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11066. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11067. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11068. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11069. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11070. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11071. offset_custom += 8;
  11072. }
  11073. }
  11074. } else if ( customAttribute.size === 3 ) {
  11075. var pp;
  11076. if ( customAttribute.type === "c" ) {
  11077. pp = [ "r", "g", "b" ];
  11078. } else {
  11079. pp = [ "x", "y", "z" ];
  11080. }
  11081. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11082. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11083. face = obj_faces[ chunk_faces3[ f ] ];
  11084. v1 = customAttribute.value[ face.a ];
  11085. v2 = customAttribute.value[ face.b ];
  11086. v3 = customAttribute.value[ face.c ];
  11087. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11088. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11089. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11090. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11091. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11092. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11093. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11094. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11095. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11096. offset_custom += 9;
  11097. }
  11098. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11099. face = obj_faces[ chunk_faces4[ f ] ];
  11100. v1 = customAttribute.value[ face.a ];
  11101. v2 = customAttribute.value[ face.b ];
  11102. v3 = customAttribute.value[ face.c ];
  11103. v4 = customAttribute.value[ face.d ];
  11104. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11105. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11106. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11107. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11108. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11109. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11110. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11111. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11112. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11113. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11114. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11115. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11116. offset_custom += 12;
  11117. }
  11118. } else if ( customAttribute.boundTo === "faces" ) {
  11119. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11120. value = customAttribute.value[ chunk_faces3[ f ] ];
  11121. v1 = value;
  11122. v2 = value;
  11123. v3 = value;
  11124. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11125. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11126. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11127. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11128. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11129. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11130. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11131. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11132. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11133. offset_custom += 9;
  11134. }
  11135. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11136. value = customAttribute.value[ chunk_faces4[ f ] ];
  11137. v1 = value;
  11138. v2 = value;
  11139. v3 = value;
  11140. v4 = value;
  11141. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11142. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11143. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11144. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11145. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11146. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11147. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11148. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11149. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11150. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11151. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11152. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11153. offset_custom += 12;
  11154. }
  11155. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11156. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11157. value = customAttribute.value[ chunk_faces3[ f ] ];
  11158. v1 = value[ 0 ];
  11159. v2 = value[ 1 ];
  11160. v3 = value[ 2 ];
  11161. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11162. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11163. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11164. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11165. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11166. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11167. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11168. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11169. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11170. offset_custom += 9;
  11171. }
  11172. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11173. value = customAttribute.value[ chunk_faces4[ f ] ];
  11174. v1 = value[ 0 ];
  11175. v2 = value[ 1 ];
  11176. v3 = value[ 2 ];
  11177. v4 = value[ 3 ];
  11178. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11179. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11180. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11181. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11182. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11183. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11184. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11185. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11186. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11187. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11188. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11189. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11190. offset_custom += 12;
  11191. }
  11192. }
  11193. } else if ( customAttribute.size === 4 ) {
  11194. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11195. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11196. face = obj_faces[ chunk_faces3[ f ] ];
  11197. v1 = customAttribute.value[ face.a ];
  11198. v2 = customAttribute.value[ face.b ];
  11199. v3 = customAttribute.value[ face.c ];
  11200. customAttribute.array[ offset_custom ] = v1.x;
  11201. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11202. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11203. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11204. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11205. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11206. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11207. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11208. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11209. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11210. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11211. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11212. offset_custom += 12;
  11213. }
  11214. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11215. face = obj_faces[ chunk_faces4[ f ] ];
  11216. v1 = customAttribute.value[ face.a ];
  11217. v2 = customAttribute.value[ face.b ];
  11218. v3 = customAttribute.value[ face.c ];
  11219. v4 = customAttribute.value[ face.d ];
  11220. customAttribute.array[ offset_custom ] = v1.x;
  11221. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11222. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11223. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11224. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11225. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11226. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11227. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11228. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11229. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11230. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11231. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11232. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11233. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11234. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11235. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11236. offset_custom += 16;
  11237. }
  11238. } else if ( customAttribute.boundTo === "faces" ) {
  11239. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11240. value = customAttribute.value[ chunk_faces3[ f ] ];
  11241. v1 = value;
  11242. v2 = value;
  11243. v3 = value;
  11244. customAttribute.array[ offset_custom ] = v1.x;
  11245. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11246. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11247. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11248. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11249. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11250. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11251. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11252. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11253. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11254. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11255. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11256. offset_custom += 12;
  11257. }
  11258. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11259. value = customAttribute.value[ chunk_faces4[ f ] ];
  11260. v1 = value;
  11261. v2 = value;
  11262. v3 = value;
  11263. v4 = value;
  11264. customAttribute.array[ offset_custom ] = v1.x;
  11265. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11266. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11267. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11268. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11269. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11270. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11271. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11272. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11273. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11274. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11275. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11276. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11277. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11278. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11279. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11280. offset_custom += 16;
  11281. }
  11282. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11283. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11284. value = customAttribute.value[ chunk_faces3[ f ] ];
  11285. v1 = value[ 0 ];
  11286. v2 = value[ 1 ];
  11287. v3 = value[ 2 ];
  11288. customAttribute.array[ offset_custom ] = v1.x;
  11289. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11290. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11291. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11292. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11293. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11294. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11295. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11296. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11297. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11298. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11299. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11300. offset_custom += 12;
  11301. }
  11302. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11303. value = customAttribute.value[ chunk_faces4[ f ] ];
  11304. v1 = value[ 0 ];
  11305. v2 = value[ 1 ];
  11306. v3 = value[ 2 ];
  11307. v4 = value[ 3 ];
  11308. customAttribute.array[ offset_custom ] = v1.x;
  11309. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11310. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11311. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11312. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11313. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11314. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11315. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11316. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11317. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11318. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11319. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11320. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11321. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11322. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11323. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11324. offset_custom += 16;
  11325. }
  11326. }
  11327. }
  11328. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11329. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11330. }
  11331. }
  11332. if ( dispose ) {
  11333. delete geometryGroup.__inittedArrays;
  11334. delete geometryGroup.__colorArray;
  11335. delete geometryGroup.__normalArray;
  11336. delete geometryGroup.__tangentArray;
  11337. delete geometryGroup.__uvArray;
  11338. delete geometryGroup.__uv2Array;
  11339. delete geometryGroup.__faceArray;
  11340. delete geometryGroup.__vertexArray;
  11341. delete geometryGroup.__lineArray;
  11342. delete geometryGroup.__skinIndexArray;
  11343. delete geometryGroup.__skinWeightArray;
  11344. }
  11345. };
  11346. function setDirectBuffers ( geometry, hint, dispose ) {
  11347. var attributes = geometry.attributes;
  11348. var index = attributes[ "index" ];
  11349. var position = attributes[ "position" ];
  11350. var normal = attributes[ "normal" ];
  11351. var uv = attributes[ "uv" ];
  11352. var color = attributes[ "color" ];
  11353. var tangent = attributes[ "tangent" ];
  11354. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  11355. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11356. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  11357. }
  11358. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  11359. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11360. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  11361. }
  11362. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  11363. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11364. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  11365. }
  11366. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  11367. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11368. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  11369. }
  11370. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  11371. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11372. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  11373. }
  11374. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  11375. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11376. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  11377. }
  11378. if ( dispose ) {
  11379. for ( var i in geometry.attributes ) {
  11380. delete geometry.attributes[ i ].array;
  11381. }
  11382. }
  11383. };
  11384. // Buffer rendering
  11385. this.renderBufferImmediate = function ( object, program, material ) {
  11386. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  11387. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  11388. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  11389. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  11390. if ( object.hasPositions ) {
  11391. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  11392. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11393. _gl.enableVertexAttribArray( program.attributes.position );
  11394. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11395. }
  11396. if ( object.hasNormals ) {
  11397. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  11398. if ( material.shading === THREE.FlatShading ) {
  11399. var nx, ny, nz,
  11400. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  11401. normalArray,
  11402. i, il = object.count * 3;
  11403. for( i = 0; i < il; i += 9 ) {
  11404. normalArray = object.normalArray;
  11405. nax = normalArray[ i ];
  11406. nay = normalArray[ i + 1 ];
  11407. naz = normalArray[ i + 2 ];
  11408. nbx = normalArray[ i + 3 ];
  11409. nby = normalArray[ i + 4 ];
  11410. nbz = normalArray[ i + 5 ];
  11411. ncx = normalArray[ i + 6 ];
  11412. ncy = normalArray[ i + 7 ];
  11413. ncz = normalArray[ i + 8 ];
  11414. nx = ( nax + nbx + ncx ) / 3;
  11415. ny = ( nay + nby + ncy ) / 3;
  11416. nz = ( naz + nbz + ncz ) / 3;
  11417. normalArray[ i ] = nx;
  11418. normalArray[ i + 1 ] = ny;
  11419. normalArray[ i + 2 ] = nz;
  11420. normalArray[ i + 3 ] = nx;
  11421. normalArray[ i + 4 ] = ny;
  11422. normalArray[ i + 5 ] = nz;
  11423. normalArray[ i + 6 ] = nx;
  11424. normalArray[ i + 7 ] = ny;
  11425. normalArray[ i + 8 ] = nz;
  11426. }
  11427. }
  11428. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11429. _gl.enableVertexAttribArray( program.attributes.normal );
  11430. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11431. }
  11432. if ( object.hasUvs && material.map ) {
  11433. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  11434. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11435. _gl.enableVertexAttribArray( program.attributes.uv );
  11436. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11437. }
  11438. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  11439. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  11440. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11441. _gl.enableVertexAttribArray( program.attributes.color );
  11442. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11443. }
  11444. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11445. object.count = 0;
  11446. };
  11447. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  11448. if ( material.visible === false ) return;
  11449. var program, attributes, linewidth, primitives, a, attribute;
  11450. program = setProgram( camera, lights, fog, material, object );
  11451. attributes = program.attributes;
  11452. var updateBuffers = false,
  11453. wireframeBit = material.wireframe ? 1 : 0,
  11454. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11455. if ( geometryHash !== _currentGeometryGroupHash ) {
  11456. _currentGeometryGroupHash = geometryHash;
  11457. updateBuffers = true;
  11458. }
  11459. if ( updateBuffers ) {
  11460. disableAttributes();
  11461. }
  11462. // render mesh
  11463. if ( object instanceof THREE.Mesh ) {
  11464. var index = geometry.attributes[ "index" ];
  11465. // indexed triangles
  11466. if ( index ) {
  11467. var offsets = geometry.offsets;
  11468. // if there is more than 1 chunk
  11469. // must set attribute pointers to use new offsets for each chunk
  11470. // even if geometry and materials didn't change
  11471. if ( offsets.length > 1 ) updateBuffers = true;
  11472. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  11473. var startIndex = offsets[ i ].index;
  11474. if ( updateBuffers ) {
  11475. // vertices
  11476. var position = geometry.attributes[ "position" ];
  11477. var positionSize = position.itemSize;
  11478. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11479. enableAttribute( attributes.position );
  11480. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  11481. // normals
  11482. var normal = geometry.attributes[ "normal" ];
  11483. if ( attributes.normal >= 0 && normal ) {
  11484. var normalSize = normal.itemSize;
  11485. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11486. enableAttribute( attributes.normal );
  11487. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  11488. }
  11489. // uvs
  11490. var uv = geometry.attributes[ "uv" ];
  11491. if ( attributes.uv >= 0 && uv ) {
  11492. var uvSize = uv.itemSize;
  11493. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11494. enableAttribute( attributes.uv );
  11495. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  11496. }
  11497. // colors
  11498. var color = geometry.attributes[ "color" ];
  11499. if ( attributes.color >= 0 && color ) {
  11500. var colorSize = color.itemSize;
  11501. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11502. enableAttribute( attributes.color );
  11503. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  11504. }
  11505. // tangents
  11506. var tangent = geometry.attributes[ "tangent" ];
  11507. if ( attributes.tangent >= 0 && tangent ) {
  11508. var tangentSize = tangent.itemSize;
  11509. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11510. enableAttribute( attributes.tangent );
  11511. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  11512. }
  11513. // indices
  11514. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11515. }
  11516. // render indexed triangles
  11517. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  11518. _this.info.render.calls ++;
  11519. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  11520. _this.info.render.faces += offsets[ i ].count / 3;
  11521. }
  11522. // non-indexed triangles
  11523. } else {
  11524. if ( updateBuffers ) {
  11525. // vertices
  11526. var position = geometry.attributes[ "position" ];
  11527. var positionSize = position.itemSize;
  11528. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11529. enableAttribute( attributes.position );
  11530. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  11531. // normals
  11532. var normal = geometry.attributes[ "normal" ];
  11533. if ( attributes.normal >= 0 && normal ) {
  11534. var normalSize = normal.itemSize;
  11535. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11536. enableAttribute( attributes.normal );
  11537. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, 0 );
  11538. }
  11539. // uvs
  11540. var uv = geometry.attributes[ "uv" ];
  11541. if ( attributes.uv >= 0 && uv ) {
  11542. var uvSize = uv.itemSize;
  11543. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11544. enableAttribute( attributes.uv );
  11545. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, 0 );
  11546. }
  11547. // colors
  11548. var color = geometry.attributes[ "color" ];
  11549. if ( attributes.color >= 0 && color ) {
  11550. var colorSize = color.itemSize;
  11551. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11552. enableAttribute( attributes.color );
  11553. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  11554. }
  11555. // tangents
  11556. var tangent = geometry.attributes[ "tangent" ];
  11557. if ( attributes.tangent >= 0 && tangent ) {
  11558. var tangentSize = tangent.itemSize;
  11559. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11560. enableAttribute( attributes.tangent );
  11561. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0 );
  11562. }
  11563. }
  11564. // render non-indexed triangles
  11565. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  11566. _this.info.render.calls ++;
  11567. _this.info.render.vertices += position.numItems / 3;
  11568. _this.info.render.faces += position.numItems / 3 / 3;
  11569. }
  11570. // render particles
  11571. } else if ( object instanceof THREE.ParticleSystem ) {
  11572. if ( updateBuffers ) {
  11573. // vertices
  11574. var position = geometry.attributes[ "position" ];
  11575. var positionSize = position.itemSize;
  11576. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11577. enableAttribute( attributes.position );
  11578. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  11579. // colors
  11580. var color = geometry.attributes[ "color" ];
  11581. if ( attributes.color >= 0 && color ) {
  11582. var colorSize = color.itemSize;
  11583. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11584. enableAttribute( attributes.color );
  11585. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  11586. }
  11587. // render particles
  11588. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  11589. _this.info.render.calls ++;
  11590. _this.info.render.points += position.numItems / 3;
  11591. }
  11592. }
  11593. };
  11594. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  11595. if ( material.visible === false ) return;
  11596. var program, attributes, linewidth, primitives, a, attribute, i, il;
  11597. program = setProgram( camera, lights, fog, material, object );
  11598. attributes = program.attributes;
  11599. var updateBuffers = false,
  11600. wireframeBit = material.wireframe ? 1 : 0,
  11601. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11602. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  11603. _currentGeometryGroupHash = geometryGroupHash;
  11604. updateBuffers = true;
  11605. }
  11606. if ( updateBuffers ) {
  11607. disableAttributes();
  11608. }
  11609. // vertices
  11610. if ( !material.morphTargets && attributes.position >= 0 ) {
  11611. if ( updateBuffers ) {
  11612. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11613. enableAttribute( attributes.position );
  11614. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11615. }
  11616. } else {
  11617. if ( object.morphTargetBase ) {
  11618. setupMorphTargets( material, geometryGroup, object );
  11619. }
  11620. }
  11621. if ( updateBuffers ) {
  11622. // custom attributes
  11623. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  11624. if ( geometryGroup.__webglCustomAttributesList ) {
  11625. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  11626. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  11627. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  11628. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  11629. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  11630. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  11631. }
  11632. }
  11633. }
  11634. // colors
  11635. if ( attributes.color >= 0 ) {
  11636. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11637. enableAttribute( attributes.color );
  11638. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11639. }
  11640. // normals
  11641. if ( attributes.normal >= 0 ) {
  11642. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11643. enableAttribute( attributes.normal );
  11644. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11645. }
  11646. // tangents
  11647. if ( attributes.tangent >= 0 ) {
  11648. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11649. enableAttribute( attributes.tangent );
  11650. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  11651. }
  11652. // uvs
  11653. if ( attributes.uv >= 0 ) {
  11654. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11655. enableAttribute( attributes.uv );
  11656. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11657. }
  11658. if ( attributes.uv2 >= 0 ) {
  11659. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11660. enableAttribute( attributes.uv2 );
  11661. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  11662. }
  11663. if ( material.skinning &&
  11664. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  11665. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11666. enableAttribute( attributes.skinIndex );
  11667. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  11668. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11669. enableAttribute( attributes.skinWeight );
  11670. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  11671. }
  11672. // line distances
  11673. if ( attributes.lineDistance >= 0 ) {
  11674. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  11675. enableAttribute( attributes.lineDistance );
  11676. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  11677. }
  11678. }
  11679. // render mesh
  11680. if ( object instanceof THREE.Mesh ) {
  11681. // wireframe
  11682. if ( material.wireframe ) {
  11683. setLineWidth( material.wireframeLinewidth );
  11684. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11685. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  11686. // triangles
  11687. } else {
  11688. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11689. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  11690. }
  11691. _this.info.render.calls ++;
  11692. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  11693. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  11694. // render lines
  11695. } else if ( object instanceof THREE.Line ) {
  11696. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  11697. setLineWidth( material.linewidth );
  11698. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  11699. _this.info.render.calls ++;
  11700. // render particles
  11701. } else if ( object instanceof THREE.ParticleSystem ) {
  11702. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  11703. _this.info.render.calls ++;
  11704. _this.info.render.points += geometryGroup.__webglParticleCount;
  11705. // render ribbon
  11706. } else if ( object instanceof THREE.Ribbon ) {
  11707. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  11708. _this.info.render.calls ++;
  11709. }
  11710. };
  11711. function enableAttribute( attribute ) {
  11712. if ( ! _enabledAttributes[ attribute ] ) {
  11713. _gl.enableVertexAttribArray( attribute );
  11714. _enabledAttributes[ attribute ] = true;
  11715. }
  11716. };
  11717. function disableAttributes() {
  11718. for ( var attribute in _enabledAttributes ) {
  11719. if ( _enabledAttributes[ attribute ] ) {
  11720. _gl.disableVertexAttribArray( attribute );
  11721. _enabledAttributes[ attribute ] = false;
  11722. }
  11723. }
  11724. };
  11725. function setupMorphTargets ( material, geometryGroup, object ) {
  11726. // set base
  11727. var attributes = material.program.attributes;
  11728. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  11729. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  11730. enableAttribute( attributes.position );
  11731. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11732. } else if ( attributes.position >= 0 ) {
  11733. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11734. enableAttribute( attributes.position );
  11735. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11736. }
  11737. if ( object.morphTargetForcedOrder.length ) {
  11738. // set forced order
  11739. var m = 0;
  11740. var order = object.morphTargetForcedOrder;
  11741. var influences = object.morphTargetInfluences;
  11742. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  11743. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  11744. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  11745. enableAttribute( attributes[ "morphTarget" + m ] );
  11746. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11747. }
  11748. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  11749. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  11750. enableAttribute( attributes[ "morphNormal" + m ] );
  11751. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11752. }
  11753. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  11754. m ++;
  11755. }
  11756. } else {
  11757. // find the most influencing
  11758. var influence, activeInfluenceIndices = [];
  11759. var influences = object.morphTargetInfluences;
  11760. var i, il = influences.length;
  11761. for ( i = 0; i < il; i ++ ) {
  11762. influence = influences[ i ];
  11763. if ( influence > 0 ) {
  11764. activeInfluenceIndices.push( [ i, influence ] );
  11765. }
  11766. }
  11767. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  11768. activeInfluenceIndices.sort( numericalSort );
  11769. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  11770. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  11771. activeInfluenceIndices.sort( numericalSort );
  11772. } else if ( activeInfluenceIndices.length === 0 ) {
  11773. activeInfluenceIndices.push( [ 0, 0 ] );
  11774. };
  11775. var influenceIndex, m = 0;
  11776. while ( m < material.numSupportedMorphTargets ) {
  11777. if ( activeInfluenceIndices[ m ] ) {
  11778. influenceIndex = activeInfluenceIndices[ m ][ 0 ];
  11779. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  11780. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  11781. enableAttribute( attributes[ "morphTarget" + m ] );
  11782. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11783. }
  11784. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  11785. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  11786. enableAttribute( attributes[ "morphNormal" + m ] );
  11787. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11788. }
  11789. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  11790. } else {
  11791. /*
  11792. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11793. if ( material.morphNormals ) {
  11794. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11795. }
  11796. */
  11797. object.__webglMorphTargetInfluences[ m ] = 0;
  11798. }
  11799. m ++;
  11800. }
  11801. }
  11802. // load updated influences uniform
  11803. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  11804. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  11805. }
  11806. };
  11807. // Sorting
  11808. function painterSortStable ( a, b ) {
  11809. if ( a.z !== b.z ) {
  11810. return b.z - a.z;
  11811. } else {
  11812. return b.id - a.id;
  11813. }
  11814. };
  11815. function numericalSort ( a, b ) {
  11816. return b[ 1 ] - a[ 1 ];
  11817. };
  11818. // Rendering
  11819. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11820. if ( camera instanceof THREE.Camera === false ) {
  11821. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  11822. return;
  11823. }
  11824. var i, il,
  11825. webglObject, object,
  11826. renderList,
  11827. lights = scene.__lights,
  11828. fog = scene.fog;
  11829. // reset caching for this frame
  11830. _currentMaterialId = -1;
  11831. _lightsNeedUpdate = true;
  11832. // update scene graph
  11833. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  11834. // update camera matrices and frustum
  11835. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  11836. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11837. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  11838. _frustum.setFromMatrix( _projScreenMatrix );
  11839. // update WebGL objects
  11840. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  11841. // custom render plugins (pre pass)
  11842. renderPlugins( this.renderPluginsPre, scene, camera );
  11843. //
  11844. _this.info.render.calls = 0;
  11845. _this.info.render.vertices = 0;
  11846. _this.info.render.faces = 0;
  11847. _this.info.render.points = 0;
  11848. this.setRenderTarget( renderTarget );
  11849. if ( this.autoClear || forceClear ) {
  11850. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  11851. }
  11852. // set matrices for regular objects (frustum culled)
  11853. renderList = scene.__webglObjects;
  11854. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11855. webglObject = renderList[ i ];
  11856. object = webglObject.object;
  11857. webglObject.render = false;
  11858. if ( object.visible ) {
  11859. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  11860. setupMatrices( object, camera );
  11861. unrollBufferMaterial( webglObject );
  11862. webglObject.render = true;
  11863. if ( this.sortObjects === true ) {
  11864. if ( object.renderDepth !== null ) {
  11865. webglObject.z = object.renderDepth;
  11866. } else {
  11867. _vector3.copy( object.matrixWorld.getPosition() );
  11868. _projScreenMatrix.multiplyVector3( _vector3 );
  11869. webglObject.z = _vector3.z;
  11870. }
  11871. webglObject.id = object.id;
  11872. }
  11873. }
  11874. }
  11875. }
  11876. if ( this.sortObjects ) {
  11877. renderList.sort( painterSortStable );
  11878. }
  11879. // set matrices for immediate objects
  11880. renderList = scene.__webglObjectsImmediate;
  11881. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11882. webglObject = renderList[ i ];
  11883. object = webglObject.object;
  11884. if ( object.visible ) {
  11885. setupMatrices( object, camera );
  11886. unrollImmediateBufferMaterial( webglObject );
  11887. }
  11888. }
  11889. if ( scene.overrideMaterial ) {
  11890. var material = scene.overrideMaterial;
  11891. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11892. this.setDepthTest( material.depthTest );
  11893. this.setDepthWrite( material.depthWrite );
  11894. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11895. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  11896. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  11897. } else {
  11898. var material = null;
  11899. // opaque pass (front-to-back order)
  11900. this.setBlending( THREE.NoBlending );
  11901. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  11902. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  11903. // transparent pass (back-to-front order)
  11904. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  11905. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  11906. }
  11907. // custom render plugins (post pass)
  11908. renderPlugins( this.renderPluginsPost, scene, camera );
  11909. // Generate mipmap if we're using any kind of mipmap filtering
  11910. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  11911. updateRenderTargetMipmap( renderTarget );
  11912. }
  11913. // Ensure depth buffer writing is enabled so it can be cleared on next render
  11914. this.setDepthTest( true );
  11915. this.setDepthWrite( true );
  11916. // _gl.finish();
  11917. };
  11918. function renderPlugins( plugins, scene, camera ) {
  11919. if ( ! plugins.length ) return;
  11920. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  11921. // reset state for plugin (to start from clean slate)
  11922. _currentProgram = null;
  11923. _currentCamera = null;
  11924. _oldBlending = -1;
  11925. _oldDepthTest = -1;
  11926. _oldDepthWrite = -1;
  11927. _oldDoubleSided = -1;
  11928. _oldFlipSided = -1;
  11929. _currentGeometryGroupHash = -1;
  11930. _currentMaterialId = -1;
  11931. _lightsNeedUpdate = true;
  11932. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  11933. // reset state after plugin (anything could have changed)
  11934. _currentProgram = null;
  11935. _currentCamera = null;
  11936. _oldBlending = -1;
  11937. _oldDepthTest = -1;
  11938. _oldDepthWrite = -1;
  11939. _oldDoubleSided = -1;
  11940. _oldFlipSided = -1;
  11941. _currentGeometryGroupHash = -1;
  11942. _currentMaterialId = -1;
  11943. _lightsNeedUpdate = true;
  11944. }
  11945. };
  11946. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11947. var webglObject, object, buffer, material, start, end, delta;
  11948. if ( reverse ) {
  11949. start = renderList.length - 1;
  11950. end = -1;
  11951. delta = -1;
  11952. } else {
  11953. start = 0;
  11954. end = renderList.length;
  11955. delta = 1;
  11956. }
  11957. for ( var i = start; i !== end; i += delta ) {
  11958. webglObject = renderList[ i ];
  11959. if ( webglObject.render ) {
  11960. object = webglObject.object;
  11961. buffer = webglObject.buffer;
  11962. if ( overrideMaterial ) {
  11963. material = overrideMaterial;
  11964. } else {
  11965. material = webglObject[ materialType ];
  11966. if ( ! material ) continue;
  11967. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11968. _this.setDepthTest( material.depthTest );
  11969. _this.setDepthWrite( material.depthWrite );
  11970. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11971. }
  11972. _this.setMaterialFaces( material );
  11973. if ( buffer instanceof THREE.BufferGeometry ) {
  11974. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  11975. } else {
  11976. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  11977. }
  11978. }
  11979. }
  11980. };
  11981. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11982. var webglObject, object, material, program;
  11983. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  11984. webglObject = renderList[ i ];
  11985. object = webglObject.object;
  11986. if ( object.visible ) {
  11987. if ( overrideMaterial ) {
  11988. material = overrideMaterial;
  11989. } else {
  11990. material = webglObject[ materialType ];
  11991. if ( ! material ) continue;
  11992. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11993. _this.setDepthTest( material.depthTest );
  11994. _this.setDepthWrite( material.depthWrite );
  11995. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11996. }
  11997. _this.renderImmediateObject( camera, lights, fog, material, object );
  11998. }
  11999. }
  12000. };
  12001. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  12002. var program = setProgram( camera, lights, fog, material, object );
  12003. _currentGeometryGroupHash = -1;
  12004. _this.setMaterialFaces( material );
  12005. if ( object.immediateRenderCallback ) {
  12006. object.immediateRenderCallback( program, _gl, _frustum );
  12007. } else {
  12008. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  12009. }
  12010. };
  12011. function unrollImmediateBufferMaterial ( globject ) {
  12012. var object = globject.object,
  12013. material = object.material;
  12014. if ( material.transparent ) {
  12015. globject.transparent = material;
  12016. globject.opaque = null;
  12017. } else {
  12018. globject.opaque = material;
  12019. globject.transparent = null;
  12020. }
  12021. };
  12022. function unrollBufferMaterial ( globject ) {
  12023. var object = globject.object,
  12024. buffer = globject.buffer,
  12025. material, materialIndex, meshMaterial;
  12026. meshMaterial = object.material;
  12027. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  12028. materialIndex = buffer.materialIndex;
  12029. material = meshMaterial.materials[ materialIndex ];
  12030. if ( material.transparent ) {
  12031. globject.transparent = material;
  12032. globject.opaque = null;
  12033. } else {
  12034. globject.opaque = material;
  12035. globject.transparent = null;
  12036. }
  12037. } else {
  12038. material = meshMaterial;
  12039. if ( material ) {
  12040. if ( material.transparent ) {
  12041. globject.transparent = material;
  12042. globject.opaque = null;
  12043. } else {
  12044. globject.opaque = material;
  12045. globject.transparent = null;
  12046. }
  12047. }
  12048. }
  12049. };
  12050. // Geometry splitting
  12051. function sortFacesByMaterial ( geometry, material ) {
  12052. var f, fl, face, materialIndex, vertices,
  12053. groupHash, hash_map = {};
  12054. var numMorphTargets = geometry.morphTargets.length;
  12055. var numMorphNormals = geometry.morphNormals.length;
  12056. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  12057. geometry.geometryGroups = {};
  12058. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  12059. face = geometry.faces[ f ];
  12060. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  12061. if ( hash_map[ materialIndex ] === undefined ) {
  12062. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  12063. }
  12064. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12065. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12066. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12067. }
  12068. vertices = face instanceof THREE.Face3 ? 3 : 4;
  12069. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  12070. hash_map[ materialIndex ].counter += 1;
  12071. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12072. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12073. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12074. }
  12075. }
  12076. if ( face instanceof THREE.Face3 ) {
  12077. geometry.geometryGroups[ groupHash ].faces3.push( f );
  12078. } else {
  12079. geometry.geometryGroups[ groupHash ].faces4.push( f );
  12080. }
  12081. geometry.geometryGroups[ groupHash ].vertices += vertices;
  12082. }
  12083. geometry.geometryGroupsList = [];
  12084. for ( var g in geometry.geometryGroups ) {
  12085. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  12086. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  12087. }
  12088. };
  12089. // Objects refresh
  12090. this.initWebGLObjects = function ( scene ) {
  12091. if ( !scene.__webglObjects ) {
  12092. scene.__webglObjects = [];
  12093. scene.__webglObjectsImmediate = [];
  12094. scene.__webglSprites = [];
  12095. scene.__webglFlares = [];
  12096. }
  12097. while ( scene.__objectsAdded.length ) {
  12098. addObject( scene.__objectsAdded[ 0 ], scene );
  12099. scene.__objectsAdded.splice( 0, 1 );
  12100. }
  12101. while ( scene.__objectsRemoved.length ) {
  12102. removeObject( scene.__objectsRemoved[ 0 ], scene );
  12103. scene.__objectsRemoved.splice( 0, 1 );
  12104. }
  12105. // update must be called after objects adding / removal
  12106. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  12107. updateObject( scene.__webglObjects[ o ].object );
  12108. }
  12109. };
  12110. // Objects adding
  12111. function addObject ( object, scene ) {
  12112. var g, geometry, material, geometryGroup;
  12113. if ( ! object.__webglInit ) {
  12114. object.__webglInit = true;
  12115. object._modelViewMatrix = new THREE.Matrix4();
  12116. object._normalMatrix = new THREE.Matrix3();
  12117. if ( object instanceof THREE.Mesh ) {
  12118. geometry = object.geometry;
  12119. material = object.material;
  12120. if ( geometry instanceof THREE.Geometry ) {
  12121. if ( geometry.geometryGroups === undefined ) {
  12122. sortFacesByMaterial( geometry, material );
  12123. }
  12124. // create separate VBOs per geometry chunk
  12125. for ( g in geometry.geometryGroups ) {
  12126. geometryGroup = geometry.geometryGroups[ g ];
  12127. // initialise VBO on the first access
  12128. if ( ! geometryGroup.__webglVertexBuffer ) {
  12129. createMeshBuffers( geometryGroup );
  12130. initMeshBuffers( geometryGroup, object );
  12131. geometry.verticesNeedUpdate = true;
  12132. geometry.morphTargetsNeedUpdate = true;
  12133. geometry.elementsNeedUpdate = true;
  12134. geometry.uvsNeedUpdate = true;
  12135. geometry.normalsNeedUpdate = true;
  12136. geometry.tangentsNeedUpdate = true;
  12137. geometry.colorsNeedUpdate = true;
  12138. }
  12139. }
  12140. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12141. initDirectBuffers( geometry );
  12142. }
  12143. } else if ( object instanceof THREE.Ribbon ) {
  12144. geometry = object.geometry;
  12145. if ( ! geometry.__webglVertexBuffer ) {
  12146. createRibbonBuffers( geometry );
  12147. initRibbonBuffers( geometry, object );
  12148. geometry.verticesNeedUpdate = true;
  12149. geometry.colorsNeedUpdate = true;
  12150. geometry.normalsNeedUpdate = true;
  12151. }
  12152. } else if ( object instanceof THREE.Line ) {
  12153. geometry = object.geometry;
  12154. if ( ! geometry.__webglVertexBuffer ) {
  12155. createLineBuffers( geometry );
  12156. initLineBuffers( geometry, object );
  12157. geometry.verticesNeedUpdate = true;
  12158. geometry.colorsNeedUpdate = true;
  12159. geometry.lineDistancesNeedUpdate = true;
  12160. }
  12161. } else if ( object instanceof THREE.ParticleSystem ) {
  12162. geometry = object.geometry;
  12163. if ( ! geometry.__webglVertexBuffer ) {
  12164. if ( geometry instanceof THREE.Geometry ) {
  12165. createParticleBuffers( geometry );
  12166. initParticleBuffers( geometry, object );
  12167. geometry.verticesNeedUpdate = true;
  12168. geometry.colorsNeedUpdate = true;
  12169. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12170. initDirectBuffers( geometry );
  12171. }
  12172. }
  12173. }
  12174. }
  12175. if ( ! object.__webglActive ) {
  12176. if ( object instanceof THREE.Mesh ) {
  12177. geometry = object.geometry;
  12178. if ( geometry instanceof THREE.BufferGeometry ) {
  12179. addBuffer( scene.__webglObjects, geometry, object );
  12180. } else {
  12181. for ( g in geometry.geometryGroups ) {
  12182. geometryGroup = geometry.geometryGroups[ g ];
  12183. addBuffer( scene.__webglObjects, geometryGroup, object );
  12184. }
  12185. }
  12186. } else if ( object instanceof THREE.Ribbon ||
  12187. object instanceof THREE.Line ||
  12188. object instanceof THREE.ParticleSystem ) {
  12189. geometry = object.geometry;
  12190. addBuffer( scene.__webglObjects, geometry, object );
  12191. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12192. addBufferImmediate( scene.__webglObjectsImmediate, object );
  12193. } else if ( object instanceof THREE.Sprite ) {
  12194. scene.__webglSprites.push( object );
  12195. } else if ( object instanceof THREE.LensFlare ) {
  12196. scene.__webglFlares.push( object );
  12197. }
  12198. object.__webglActive = true;
  12199. }
  12200. };
  12201. function addBuffer ( objlist, buffer, object ) {
  12202. objlist.push(
  12203. {
  12204. buffer: buffer,
  12205. object: object,
  12206. opaque: null,
  12207. transparent: null
  12208. }
  12209. );
  12210. };
  12211. function addBufferImmediate ( objlist, object ) {
  12212. objlist.push(
  12213. {
  12214. object: object,
  12215. opaque: null,
  12216. transparent: null
  12217. }
  12218. );
  12219. };
  12220. // Objects updates
  12221. function updateObject ( object ) {
  12222. var geometry = object.geometry,
  12223. geometryGroup, customAttributesDirty, material;
  12224. if ( object instanceof THREE.Mesh ) {
  12225. if ( geometry instanceof THREE.BufferGeometry ) {
  12226. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  12227. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12228. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  12229. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12230. }
  12231. geometry.verticesNeedUpdate = false;
  12232. geometry.elementsNeedUpdate = false;
  12233. geometry.uvsNeedUpdate = false;
  12234. geometry.normalsNeedUpdate = false;
  12235. geometry.colorsNeedUpdate = false;
  12236. geometry.tangentsNeedUpdate = false;
  12237. } else {
  12238. // check all geometry groups
  12239. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  12240. geometryGroup = geometry.geometryGroupsList[ i ];
  12241. material = getBufferMaterial( object, geometryGroup );
  12242. if ( geometry.buffersNeedUpdate ) {
  12243. initMeshBuffers( geometryGroup, object );
  12244. }
  12245. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12246. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  12247. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12248. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  12249. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  12250. }
  12251. }
  12252. geometry.verticesNeedUpdate = false;
  12253. geometry.morphTargetsNeedUpdate = false;
  12254. geometry.elementsNeedUpdate = false;
  12255. geometry.uvsNeedUpdate = false;
  12256. geometry.normalsNeedUpdate = false;
  12257. geometry.colorsNeedUpdate = false;
  12258. geometry.tangentsNeedUpdate = false;
  12259. geometry.buffersNeedUpdate = false;
  12260. material.attributes && clearCustomAttributes( material );
  12261. }
  12262. } else if ( object instanceof THREE.Ribbon ) {
  12263. material = getBufferMaterial( object, geometry );
  12264. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12265. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  12266. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  12267. }
  12268. geometry.verticesNeedUpdate = false;
  12269. geometry.colorsNeedUpdate = false;
  12270. geometry.normalsNeedUpdate = false;
  12271. material.attributes && clearCustomAttributes( material );
  12272. } else if ( object instanceof THREE.Line ) {
  12273. material = getBufferMaterial( object, geometry );
  12274. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12275. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  12276. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  12277. }
  12278. geometry.verticesNeedUpdate = false;
  12279. geometry.colorsNeedUpdate = false;
  12280. geometry.lineDistancesNeedUpdate = false;
  12281. material.attributes && clearCustomAttributes( material );
  12282. } else if ( object instanceof THREE.ParticleSystem ) {
  12283. if ( geometry instanceof THREE.BufferGeometry ) {
  12284. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  12285. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12286. }
  12287. geometry.verticesNeedUpdate = false;
  12288. geometry.colorsNeedUpdate = false;
  12289. } else {
  12290. material = getBufferMaterial( object, geometry );
  12291. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12292. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  12293. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  12294. }
  12295. geometry.verticesNeedUpdate = false;
  12296. geometry.colorsNeedUpdate = false;
  12297. material.attributes && clearCustomAttributes( material );
  12298. }
  12299. }
  12300. };
  12301. // Objects updates - custom attributes check
  12302. function areCustomAttributesDirty ( material ) {
  12303. for ( var a in material.attributes ) {
  12304. if ( material.attributes[ a ].needsUpdate ) return true;
  12305. }
  12306. return false;
  12307. };
  12308. function clearCustomAttributes ( material ) {
  12309. for ( var a in material.attributes ) {
  12310. material.attributes[ a ].needsUpdate = false;
  12311. }
  12312. };
  12313. // Objects removal
  12314. function removeObject ( object, scene ) {
  12315. if ( object instanceof THREE.Mesh ||
  12316. object instanceof THREE.ParticleSystem ||
  12317. object instanceof THREE.Ribbon ||
  12318. object instanceof THREE.Line ) {
  12319. removeInstances( scene.__webglObjects, object );
  12320. } else if ( object instanceof THREE.Sprite ) {
  12321. removeInstancesDirect( scene.__webglSprites, object );
  12322. } else if ( object instanceof THREE.LensFlare ) {
  12323. removeInstancesDirect( scene.__webglFlares, object );
  12324. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12325. removeInstances( scene.__webglObjectsImmediate, object );
  12326. }
  12327. object.__webglActive = false;
  12328. };
  12329. function removeInstances ( objlist, object ) {
  12330. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12331. if ( objlist[ o ].object === object ) {
  12332. objlist.splice( o, 1 );
  12333. }
  12334. }
  12335. };
  12336. function removeInstancesDirect ( objlist, object ) {
  12337. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12338. if ( objlist[ o ] === object ) {
  12339. objlist.splice( o, 1 );
  12340. }
  12341. }
  12342. };
  12343. // Materials
  12344. this.initMaterial = function ( material, lights, fog, object ) {
  12345. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  12346. if ( material instanceof THREE.MeshDepthMaterial ) {
  12347. shaderID = 'depth';
  12348. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12349. shaderID = 'normal';
  12350. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  12351. shaderID = 'basic';
  12352. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12353. shaderID = 'lambert';
  12354. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12355. shaderID = 'phong';
  12356. } else if ( material instanceof THREE.LineBasicMaterial ) {
  12357. shaderID = 'basic';
  12358. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12359. shaderID = 'dashed';
  12360. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12361. shaderID = 'particle_basic';
  12362. }
  12363. if ( shaderID ) {
  12364. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  12365. }
  12366. // heuristics to create shader parameters according to lights in the scene
  12367. // (not to blow over maxLights budget)
  12368. maxLightCount = allocateLights( lights );
  12369. maxShadows = allocateShadows( lights );
  12370. maxBones = allocateBones( object );
  12371. parameters = {
  12372. map: !!material.map,
  12373. envMap: !!material.envMap,
  12374. lightMap: !!material.lightMap,
  12375. bumpMap: !!material.bumpMap,
  12376. normalMap: !!material.normalMap,
  12377. specularMap: !!material.specularMap,
  12378. vertexColors: material.vertexColors,
  12379. fog: fog,
  12380. useFog: material.fog,
  12381. fogExp: fog instanceof THREE.FogExp2,
  12382. sizeAttenuation: material.sizeAttenuation,
  12383. skinning: material.skinning,
  12384. maxBones: maxBones,
  12385. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  12386. boneTextureWidth: object && object.boneTextureWidth,
  12387. boneTextureHeight: object && object.boneTextureHeight,
  12388. morphTargets: material.morphTargets,
  12389. morphNormals: material.morphNormals,
  12390. maxMorphTargets: this.maxMorphTargets,
  12391. maxMorphNormals: this.maxMorphNormals,
  12392. maxDirLights: maxLightCount.directional,
  12393. maxPointLights: maxLightCount.point,
  12394. maxSpotLights: maxLightCount.spot,
  12395. maxHemiLights: maxLightCount.hemi,
  12396. maxShadows: maxShadows,
  12397. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  12398. shadowMapSoft: this.shadowMapSoft,
  12399. shadowMapDebug: this.shadowMapDebug,
  12400. shadowMapCascade: this.shadowMapCascade,
  12401. alphaTest: material.alphaTest,
  12402. metal: material.metal,
  12403. perPixel: material.perPixel,
  12404. wrapAround: material.wrapAround,
  12405. doubleSided: material.side === THREE.DoubleSide,
  12406. flipSided: material.side === THREE.BackSide
  12407. };
  12408. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  12409. var attributes = material.program.attributes;
  12410. if ( material.morphTargets ) {
  12411. material.numSupportedMorphTargets = 0;
  12412. var id, base = "morphTarget";
  12413. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  12414. id = base + i;
  12415. if ( attributes[ id ] >= 0 ) {
  12416. material.numSupportedMorphTargets ++;
  12417. }
  12418. }
  12419. }
  12420. if ( material.morphNormals ) {
  12421. material.numSupportedMorphNormals = 0;
  12422. var id, base = "morphNormal";
  12423. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  12424. id = base + i;
  12425. if ( attributes[ id ] >= 0 ) {
  12426. material.numSupportedMorphNormals ++;
  12427. }
  12428. }
  12429. }
  12430. material.uniformsList = [];
  12431. for ( u in material.uniforms ) {
  12432. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  12433. }
  12434. };
  12435. function setMaterialShaders( material, shaders ) {
  12436. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  12437. material.vertexShader = shaders.vertexShader;
  12438. material.fragmentShader = shaders.fragmentShader;
  12439. };
  12440. function setProgram( camera, lights, fog, material, object ) {
  12441. _usedTextureUnits = 0;
  12442. if ( material.needsUpdate ) {
  12443. if ( material.program ) _this.deallocateMaterial( material );
  12444. _this.initMaterial( material, lights, fog, object );
  12445. material.needsUpdate = false;
  12446. }
  12447. if ( material.morphTargets ) {
  12448. if ( ! object.__webglMorphTargetInfluences ) {
  12449. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  12450. }
  12451. }
  12452. var refreshMaterial = false;
  12453. var program = material.program,
  12454. p_uniforms = program.uniforms,
  12455. m_uniforms = material.uniforms;
  12456. if ( program !== _currentProgram ) {
  12457. _gl.useProgram( program );
  12458. _currentProgram = program;
  12459. refreshMaterial = true;
  12460. }
  12461. if ( material.id !== _currentMaterialId ) {
  12462. _currentMaterialId = material.id;
  12463. refreshMaterial = true;
  12464. }
  12465. if ( refreshMaterial || camera !== _currentCamera ) {
  12466. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  12467. if ( camera !== _currentCamera ) _currentCamera = camera;
  12468. }
  12469. // skinning uniforms must be set even if material didn't change
  12470. // auto-setting of texture unit for bone texture must go before other textures
  12471. // not sure why, but otherwise weird things happen
  12472. if ( material.skinning ) {
  12473. if ( _supportsBoneTextures && object.useVertexTexture ) {
  12474. if ( p_uniforms.boneTexture !== null ) {
  12475. var textureUnit = getTextureUnit();
  12476. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  12477. _this.setTexture( object.boneTexture, textureUnit );
  12478. }
  12479. } else {
  12480. if ( p_uniforms.boneGlobalMatrices !== null ) {
  12481. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  12482. }
  12483. }
  12484. }
  12485. if ( refreshMaterial ) {
  12486. // refresh uniforms common to several materials
  12487. if ( fog && material.fog ) {
  12488. refreshUniformsFog( m_uniforms, fog );
  12489. }
  12490. if ( material instanceof THREE.MeshPhongMaterial ||
  12491. material instanceof THREE.MeshLambertMaterial ||
  12492. material.lights ) {
  12493. if ( _lightsNeedUpdate ) {
  12494. setupLights( program, lights );
  12495. _lightsNeedUpdate = false;
  12496. }
  12497. refreshUniformsLights( m_uniforms, _lights );
  12498. }
  12499. if ( material instanceof THREE.MeshBasicMaterial ||
  12500. material instanceof THREE.MeshLambertMaterial ||
  12501. material instanceof THREE.MeshPhongMaterial ) {
  12502. refreshUniformsCommon( m_uniforms, material );
  12503. }
  12504. // refresh single material specific uniforms
  12505. if ( material instanceof THREE.LineBasicMaterial ) {
  12506. refreshUniformsLine( m_uniforms, material );
  12507. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12508. refreshUniformsLine( m_uniforms, material );
  12509. refreshUniformsDash( m_uniforms, material );
  12510. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12511. refreshUniformsParticle( m_uniforms, material );
  12512. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12513. refreshUniformsPhong( m_uniforms, material );
  12514. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12515. refreshUniformsLambert( m_uniforms, material );
  12516. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  12517. m_uniforms.mNear.value = camera.near;
  12518. m_uniforms.mFar.value = camera.far;
  12519. m_uniforms.opacity.value = material.opacity;
  12520. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12521. m_uniforms.opacity.value = material.opacity;
  12522. }
  12523. if ( object.receiveShadow && ! material._shadowPass ) {
  12524. refreshUniformsShadow( m_uniforms, lights );
  12525. }
  12526. // load common uniforms
  12527. loadUniformsGeneric( program, material.uniformsList );
  12528. // load material specific uniforms
  12529. // (shader material also gets them for the sake of genericity)
  12530. if ( material instanceof THREE.ShaderMaterial ||
  12531. material instanceof THREE.MeshPhongMaterial ||
  12532. material.envMap ) {
  12533. if ( p_uniforms.cameraPosition !== null ) {
  12534. var position = camera.matrixWorld.getPosition();
  12535. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  12536. }
  12537. }
  12538. if ( material instanceof THREE.MeshPhongMaterial ||
  12539. material instanceof THREE.MeshLambertMaterial ||
  12540. material instanceof THREE.ShaderMaterial ||
  12541. material.skinning ) {
  12542. if ( p_uniforms.viewMatrix !== null ) {
  12543. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  12544. }
  12545. }
  12546. }
  12547. loadUniformsMatrices( p_uniforms, object );
  12548. if ( p_uniforms.modelMatrix !== null ) {
  12549. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  12550. }
  12551. return program;
  12552. };
  12553. // Uniforms (refresh uniforms objects)
  12554. function refreshUniformsCommon ( uniforms, material ) {
  12555. uniforms.opacity.value = material.opacity;
  12556. if ( _this.gammaInput ) {
  12557. uniforms.diffuse.value.copyGammaToLinear( material.color );
  12558. } else {
  12559. uniforms.diffuse.value = material.color;
  12560. }
  12561. uniforms.map.value = material.map;
  12562. uniforms.lightMap.value = material.lightMap;
  12563. uniforms.specularMap.value = material.specularMap;
  12564. if ( material.bumpMap ) {
  12565. uniforms.bumpMap.value = material.bumpMap;
  12566. uniforms.bumpScale.value = material.bumpScale;
  12567. }
  12568. if ( material.normalMap ) {
  12569. uniforms.normalMap.value = material.normalMap;
  12570. uniforms.normalScale.value.copy( material.normalScale );
  12571. }
  12572. // uv repeat and offset setting priorities
  12573. // 1. color map
  12574. // 2. specular map
  12575. // 3. normal map
  12576. // 4. bump map
  12577. var uvScaleMap;
  12578. if ( material.map ) {
  12579. uvScaleMap = material.map;
  12580. } else if ( material.specularMap ) {
  12581. uvScaleMap = material.specularMap;
  12582. } else if ( material.normalMap ) {
  12583. uvScaleMap = material.normalMap;
  12584. } else if ( material.bumpMap ) {
  12585. uvScaleMap = material.bumpMap;
  12586. }
  12587. if ( uvScaleMap !== undefined ) {
  12588. var offset = uvScaleMap.offset;
  12589. var repeat = uvScaleMap.repeat;
  12590. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12591. }
  12592. uniforms.envMap.value = material.envMap;
  12593. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  12594. if ( _this.gammaInput ) {
  12595. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  12596. uniforms.reflectivity.value = material.reflectivity;
  12597. } else {
  12598. uniforms.reflectivity.value = material.reflectivity;
  12599. }
  12600. uniforms.refractionRatio.value = material.refractionRatio;
  12601. uniforms.combine.value = material.combine;
  12602. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  12603. };
  12604. function refreshUniformsLine ( uniforms, material ) {
  12605. uniforms.diffuse.value = material.color;
  12606. uniforms.opacity.value = material.opacity;
  12607. };
  12608. function refreshUniformsDash ( uniforms, material ) {
  12609. uniforms.dashSize.value = material.dashSize;
  12610. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12611. uniforms.scale.value = material.scale;
  12612. };
  12613. function refreshUniformsParticle ( uniforms, material ) {
  12614. uniforms.psColor.value = material.color;
  12615. uniforms.opacity.value = material.opacity;
  12616. uniforms.size.value = material.size;
  12617. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  12618. uniforms.map.value = material.map;
  12619. };
  12620. function refreshUniformsFog ( uniforms, fog ) {
  12621. uniforms.fogColor.value = fog.color;
  12622. if ( fog instanceof THREE.Fog ) {
  12623. uniforms.fogNear.value = fog.near;
  12624. uniforms.fogFar.value = fog.far;
  12625. } else if ( fog instanceof THREE.FogExp2 ) {
  12626. uniforms.fogDensity.value = fog.density;
  12627. }
  12628. };
  12629. function refreshUniformsPhong ( uniforms, material ) {
  12630. uniforms.shininess.value = material.shininess;
  12631. if ( _this.gammaInput ) {
  12632. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12633. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12634. uniforms.specular.value.copyGammaToLinear( material.specular );
  12635. } else {
  12636. uniforms.ambient.value = material.ambient;
  12637. uniforms.emissive.value = material.emissive;
  12638. uniforms.specular.value = material.specular;
  12639. }
  12640. if ( material.wrapAround ) {
  12641. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12642. }
  12643. };
  12644. function refreshUniformsLambert ( uniforms, material ) {
  12645. if ( _this.gammaInput ) {
  12646. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12647. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12648. } else {
  12649. uniforms.ambient.value = material.ambient;
  12650. uniforms.emissive.value = material.emissive;
  12651. }
  12652. if ( material.wrapAround ) {
  12653. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12654. }
  12655. };
  12656. function refreshUniformsLights ( uniforms, lights ) {
  12657. uniforms.ambientLightColor.value = lights.ambient;
  12658. uniforms.directionalLightColor.value = lights.directional.colors;
  12659. uniforms.directionalLightDirection.value = lights.directional.positions;
  12660. uniforms.pointLightColor.value = lights.point.colors;
  12661. uniforms.pointLightPosition.value = lights.point.positions;
  12662. uniforms.pointLightDistance.value = lights.point.distances;
  12663. uniforms.spotLightColor.value = lights.spot.colors;
  12664. uniforms.spotLightPosition.value = lights.spot.positions;
  12665. uniforms.spotLightDistance.value = lights.spot.distances;
  12666. uniforms.spotLightDirection.value = lights.spot.directions;
  12667. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  12668. uniforms.spotLightExponent.value = lights.spot.exponents;
  12669. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  12670. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  12671. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  12672. };
  12673. function refreshUniformsShadow ( uniforms, lights ) {
  12674. if ( uniforms.shadowMatrix ) {
  12675. var j = 0;
  12676. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  12677. var light = lights[ i ];
  12678. if ( ! light.castShadow ) continue;
  12679. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  12680. uniforms.shadowMap.value[ j ] = light.shadowMap;
  12681. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  12682. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  12683. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  12684. uniforms.shadowBias.value[ j ] = light.shadowBias;
  12685. j ++;
  12686. }
  12687. }
  12688. }
  12689. };
  12690. // Uniforms (load to GPU)
  12691. function loadUniformsMatrices ( uniforms, object ) {
  12692. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  12693. if ( uniforms.normalMatrix ) {
  12694. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  12695. }
  12696. };
  12697. function getTextureUnit() {
  12698. var textureUnit = _usedTextureUnits;
  12699. if ( textureUnit >= _maxTextures ) {
  12700. console.warn( "Trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  12701. }
  12702. _usedTextureUnits += 1;
  12703. return textureUnit;
  12704. };
  12705. function loadUniformsGeneric ( program, uniforms ) {
  12706. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  12707. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  12708. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  12709. if ( !location ) continue;
  12710. uniform = uniforms[ j ][ 0 ];
  12711. type = uniform.type;
  12712. value = uniform.value;
  12713. if ( type === "i" ) { // single integer
  12714. _gl.uniform1i( location, value );
  12715. } else if ( type === "f" ) { // single float
  12716. _gl.uniform1f( location, value );
  12717. } else if ( type === "v2" ) { // single THREE.Vector2
  12718. _gl.uniform2f( location, value.x, value.y );
  12719. } else if ( type === "v3" ) { // single THREE.Vector3
  12720. _gl.uniform3f( location, value.x, value.y, value.z );
  12721. } else if ( type === "v4" ) { // single THREE.Vector4
  12722. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  12723. } else if ( type === "c" ) { // single THREE.Color
  12724. _gl.uniform3f( location, value.r, value.g, value.b );
  12725. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  12726. _gl.uniform1iv( location, value );
  12727. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  12728. _gl.uniform3iv( location, value );
  12729. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  12730. _gl.uniform1fv( location, value );
  12731. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  12732. _gl.uniform3fv( location, value );
  12733. } else if ( type === "v2v" ) { // array of THREE.Vector2
  12734. if ( uniform._array === undefined ) {
  12735. uniform._array = new Float32Array( 2 * value.length );
  12736. }
  12737. for ( i = 0, il = value.length; i < il; i ++ ) {
  12738. offset = i * 2;
  12739. uniform._array[ offset ] = value[ i ].x;
  12740. uniform._array[ offset + 1 ] = value[ i ].y;
  12741. }
  12742. _gl.uniform2fv( location, uniform._array );
  12743. } else if ( type === "v3v" ) { // array of THREE.Vector3
  12744. if ( uniform._array === undefined ) {
  12745. uniform._array = new Float32Array( 3 * value.length );
  12746. }
  12747. for ( i = 0, il = value.length; i < il; i ++ ) {
  12748. offset = i * 3;
  12749. uniform._array[ offset ] = value[ i ].x;
  12750. uniform._array[ offset + 1 ] = value[ i ].y;
  12751. uniform._array[ offset + 2 ] = value[ i ].z;
  12752. }
  12753. _gl.uniform3fv( location, uniform._array );
  12754. } else if ( type === "v4v" ) { // array of THREE.Vector4
  12755. if ( uniform._array === undefined ) {
  12756. uniform._array = new Float32Array( 4 * value.length );
  12757. }
  12758. for ( i = 0, il = value.length; i < il; i ++ ) {
  12759. offset = i * 4;
  12760. uniform._array[ offset ] = value[ i ].x;
  12761. uniform._array[ offset + 1 ] = value[ i ].y;
  12762. uniform._array[ offset + 2 ] = value[ i ].z;
  12763. uniform._array[ offset + 3 ] = value[ i ].w;
  12764. }
  12765. _gl.uniform4fv( location, uniform._array );
  12766. } else if ( type === "m4") { // single THREE.Matrix4
  12767. if ( uniform._array === undefined ) {
  12768. uniform._array = new Float32Array( 16 );
  12769. }
  12770. value.flattenToArray( uniform._array );
  12771. _gl.uniformMatrix4fv( location, false, uniform._array );
  12772. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  12773. if ( uniform._array === undefined ) {
  12774. uniform._array = new Float32Array( 16 * value.length );
  12775. }
  12776. for ( i = 0, il = value.length; i < il; i ++ ) {
  12777. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  12778. }
  12779. _gl.uniformMatrix4fv( location, false, uniform._array );
  12780. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  12781. texture = value;
  12782. textureUnit = getTextureUnit();
  12783. _gl.uniform1i( location, textureUnit );
  12784. if ( !texture ) continue;
  12785. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  12786. setCubeTexture( texture, textureUnit );
  12787. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  12788. setCubeTextureDynamic( texture, textureUnit );
  12789. } else {
  12790. _this.setTexture( texture, textureUnit );
  12791. }
  12792. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  12793. if ( uniform._array === undefined ) {
  12794. uniform._array = [];
  12795. }
  12796. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12797. uniform._array[ i ] = getTextureUnit();
  12798. }
  12799. _gl.uniform1iv( location, uniform._array );
  12800. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12801. texture = uniform.value[ i ];
  12802. textureUnit = uniform._array[ i ];
  12803. if ( !texture ) continue;
  12804. _this.setTexture( texture, textureUnit );
  12805. }
  12806. }
  12807. }
  12808. };
  12809. function setupMatrices ( object, camera ) {
  12810. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  12811. object._normalMatrix.getInverse( object._modelViewMatrix );
  12812. object._normalMatrix.transpose();
  12813. };
  12814. //
  12815. function setColorGamma( array, offset, color, intensitySq ) {
  12816. array[ offset ] = color.r * color.r * intensitySq;
  12817. array[ offset + 1 ] = color.g * color.g * intensitySq;
  12818. array[ offset + 2 ] = color.b * color.b * intensitySq;
  12819. };
  12820. function setColorLinear( array, offset, color, intensity ) {
  12821. array[ offset ] = color.r * intensity;
  12822. array[ offset + 1 ] = color.g * intensity;
  12823. array[ offset + 2 ] = color.b * intensity;
  12824. };
  12825. function setupLights ( program, lights ) {
  12826. var l, ll, light, n,
  12827. r = 0, g = 0, b = 0,
  12828. color, skyColor, groundColor,
  12829. intensity, intensitySq,
  12830. position,
  12831. distance,
  12832. zlights = _lights,
  12833. dirColors = zlights.directional.colors,
  12834. dirPositions = zlights.directional.positions,
  12835. pointColors = zlights.point.colors,
  12836. pointPositions = zlights.point.positions,
  12837. pointDistances = zlights.point.distances,
  12838. spotColors = zlights.spot.colors,
  12839. spotPositions = zlights.spot.positions,
  12840. spotDistances = zlights.spot.distances,
  12841. spotDirections = zlights.spot.directions,
  12842. spotAnglesCos = zlights.spot.anglesCos,
  12843. spotExponents = zlights.spot.exponents,
  12844. hemiSkyColors = zlights.hemi.skyColors,
  12845. hemiGroundColors = zlights.hemi.groundColors,
  12846. hemiPositions = zlights.hemi.positions,
  12847. dirLength = 0,
  12848. pointLength = 0,
  12849. spotLength = 0,
  12850. hemiLength = 0,
  12851. dirCount = 0,
  12852. pointCount = 0,
  12853. spotCount = 0,
  12854. hemiCount = 0,
  12855. dirOffset = 0,
  12856. pointOffset = 0,
  12857. spotOffset = 0,
  12858. hemiOffset = 0;
  12859. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12860. light = lights[ l ];
  12861. if ( light.onlyShadow ) continue;
  12862. color = light.color;
  12863. intensity = light.intensity;
  12864. distance = light.distance;
  12865. if ( light instanceof THREE.AmbientLight ) {
  12866. if ( ! light.visible ) continue;
  12867. if ( _this.gammaInput ) {
  12868. r += color.r * color.r;
  12869. g += color.g * color.g;
  12870. b += color.b * color.b;
  12871. } else {
  12872. r += color.r;
  12873. g += color.g;
  12874. b += color.b;
  12875. }
  12876. } else if ( light instanceof THREE.DirectionalLight ) {
  12877. dirCount += 1;
  12878. if ( ! light.visible ) continue;
  12879. dirOffset = dirLength * 3;
  12880. if ( _this.gammaInput ) {
  12881. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  12882. } else {
  12883. setColorLinear( dirColors, dirOffset, color, intensity );
  12884. }
  12885. _direction.copy( light.matrixWorld.getPosition() );
  12886. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12887. _direction.normalize();
  12888. dirPositions[ dirOffset ] = _direction.x;
  12889. dirPositions[ dirOffset + 1 ] = _direction.y;
  12890. dirPositions[ dirOffset + 2 ] = _direction.z;
  12891. dirLength += 1;
  12892. } else if ( light instanceof THREE.PointLight ) {
  12893. pointCount += 1;
  12894. if ( ! light.visible ) continue;
  12895. pointOffset = pointLength * 3;
  12896. if ( _this.gammaInput ) {
  12897. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  12898. } else {
  12899. setColorLinear( pointColors, pointOffset, color, intensity );
  12900. }
  12901. position = light.matrixWorld.getPosition();
  12902. pointPositions[ pointOffset ] = position.x;
  12903. pointPositions[ pointOffset + 1 ] = position.y;
  12904. pointPositions[ pointOffset + 2 ] = position.z;
  12905. pointDistances[ pointLength ] = distance;
  12906. pointLength += 1;
  12907. } else if ( light instanceof THREE.SpotLight ) {
  12908. spotCount += 1;
  12909. if ( ! light.visible ) continue;
  12910. spotOffset = spotLength * 3;
  12911. if ( _this.gammaInput ) {
  12912. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  12913. } else {
  12914. setColorLinear( spotColors, spotOffset, color, intensity );
  12915. }
  12916. position = light.matrixWorld.getPosition();
  12917. spotPositions[ spotOffset ] = position.x;
  12918. spotPositions[ spotOffset + 1 ] = position.y;
  12919. spotPositions[ spotOffset + 2 ] = position.z;
  12920. spotDistances[ spotLength ] = distance;
  12921. _direction.copy( position );
  12922. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12923. _direction.normalize();
  12924. spotDirections[ spotOffset ] = _direction.x;
  12925. spotDirections[ spotOffset + 1 ] = _direction.y;
  12926. spotDirections[ spotOffset + 2 ] = _direction.z;
  12927. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  12928. spotExponents[ spotLength ] = light.exponent;
  12929. spotLength += 1;
  12930. } else if ( light instanceof THREE.HemisphereLight ) {
  12931. hemiCount += 1;
  12932. if ( ! light.visible ) continue;
  12933. skyColor = light.color;
  12934. groundColor = light.groundColor;
  12935. hemiOffset = hemiLength * 3;
  12936. if ( _this.gammaInput ) {
  12937. intensitySq = intensity * intensity;
  12938. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  12939. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  12940. } else {
  12941. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  12942. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  12943. }
  12944. _direction.copy( light.matrixWorld.getPosition() );
  12945. _direction.normalize();
  12946. hemiPositions[ hemiOffset ] = _direction.x;
  12947. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  12948. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  12949. hemiLength += 1;
  12950. }
  12951. }
  12952. // null eventual remains from removed lights
  12953. // (this is to avoid if in shader)
  12954. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  12955. for ( l = dirLength * 3, ll = Math.max( dirPositions.length, dirCount * 3 ); l < ll; l ++ ) dirPositions[ l ] = 0.0;
  12956. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  12957. for ( l = pointLength * 3, ll = Math.max( pointPositions.length, pointCount * 3 ); l < ll; l ++ ) pointPositions[ l ] = 0.0;
  12958. for ( l = pointLength, ll = Math.max( pointDistances.length, pointCount ); l < ll; l ++ ) pointDistances[ l ] = 0.0;
  12959. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  12960. for ( l = spotLength * 3, ll = Math.max( spotPositions.length, spotCount * 3 ); l < ll; l ++ ) spotPositions[ l ] = 0.0;
  12961. for ( l = spotLength * 3, ll = Math.max( spotDirections.length, spotCount * 3 ); l < ll; l ++ ) spotDirections[ l ] = 0.0;
  12962. for ( l = spotLength, ll = Math.max( spotAnglesCos.length, spotCount ); l < ll; l ++ ) spotAnglesCos[ l ] = 0.0;
  12963. for ( l = spotLength, ll = Math.max( spotExponents.length, spotCount ); l < ll; l ++ ) spotExponents[ l ] = 0.0;
  12964. for ( l = spotLength, ll = Math.max( spotDistances.length, spotCount ); l < ll; l ++ ) spotDistances[ l ] = 0.0;
  12965. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  12966. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  12967. for ( l = hemiLength * 3, ll = Math.max( hemiPositions.length, hemiCount * 3 ); l < ll; l ++ ) hemiPositions[ l ] = 0.0;
  12968. zlights.directional.length = dirLength;
  12969. zlights.point.length = pointLength;
  12970. zlights.spot.length = spotLength;
  12971. zlights.hemi.length = hemiLength;
  12972. zlights.ambient[ 0 ] = r;
  12973. zlights.ambient[ 1 ] = g;
  12974. zlights.ambient[ 2 ] = b;
  12975. };
  12976. // GL state setting
  12977. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  12978. if ( cullFace === THREE.CullFaceNone ) {
  12979. _gl.disable( _gl.CULL_FACE );
  12980. } else {
  12981. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  12982. _gl.frontFace( _gl.CW );
  12983. } else {
  12984. _gl.frontFace( _gl.CCW );
  12985. }
  12986. if ( cullFace === THREE.CullFaceBack ) {
  12987. _gl.cullFace( _gl.BACK );
  12988. } else if ( cullFace === THREE.CullFaceFront ) {
  12989. _gl.cullFace( _gl.FRONT );
  12990. } else {
  12991. _gl.cullFace( _gl.FRONT_AND_BACK );
  12992. }
  12993. _gl.enable( _gl.CULL_FACE );
  12994. }
  12995. };
  12996. this.setMaterialFaces = function ( material ) {
  12997. var doubleSided = material.side === THREE.DoubleSide;
  12998. var flipSided = material.side === THREE.BackSide;
  12999. if ( _oldDoubleSided !== doubleSided ) {
  13000. if ( doubleSided ) {
  13001. _gl.disable( _gl.CULL_FACE );
  13002. } else {
  13003. _gl.enable( _gl.CULL_FACE );
  13004. }
  13005. _oldDoubleSided = doubleSided;
  13006. }
  13007. if ( _oldFlipSided !== flipSided ) {
  13008. if ( flipSided ) {
  13009. _gl.frontFace( _gl.CW );
  13010. } else {
  13011. _gl.frontFace( _gl.CCW );
  13012. }
  13013. _oldFlipSided = flipSided;
  13014. }
  13015. };
  13016. this.setDepthTest = function ( depthTest ) {
  13017. if ( _oldDepthTest !== depthTest ) {
  13018. if ( depthTest ) {
  13019. _gl.enable( _gl.DEPTH_TEST );
  13020. } else {
  13021. _gl.disable( _gl.DEPTH_TEST );
  13022. }
  13023. _oldDepthTest = depthTest;
  13024. }
  13025. };
  13026. this.setDepthWrite = function ( depthWrite ) {
  13027. if ( _oldDepthWrite !== depthWrite ) {
  13028. _gl.depthMask( depthWrite );
  13029. _oldDepthWrite = depthWrite;
  13030. }
  13031. };
  13032. function setLineWidth ( width ) {
  13033. if ( width !== _oldLineWidth ) {
  13034. _gl.lineWidth( width );
  13035. _oldLineWidth = width;
  13036. }
  13037. };
  13038. function setPolygonOffset ( polygonoffset, factor, units ) {
  13039. if ( _oldPolygonOffset !== polygonoffset ) {
  13040. if ( polygonoffset ) {
  13041. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  13042. } else {
  13043. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  13044. }
  13045. _oldPolygonOffset = polygonoffset;
  13046. }
  13047. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  13048. _gl.polygonOffset( factor, units );
  13049. _oldPolygonOffsetFactor = factor;
  13050. _oldPolygonOffsetUnits = units;
  13051. }
  13052. };
  13053. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  13054. if ( blending !== _oldBlending ) {
  13055. if ( blending === THREE.NoBlending ) {
  13056. _gl.disable( _gl.BLEND );
  13057. } else if ( blending === THREE.AdditiveBlending ) {
  13058. _gl.enable( _gl.BLEND );
  13059. _gl.blendEquation( _gl.FUNC_ADD );
  13060. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  13061. } else if ( blending === THREE.SubtractiveBlending ) {
  13062. // TODO: Find blendFuncSeparate() combination
  13063. _gl.enable( _gl.BLEND );
  13064. _gl.blendEquation( _gl.FUNC_ADD );
  13065. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  13066. } else if ( blending === THREE.MultiplyBlending ) {
  13067. // TODO: Find blendFuncSeparate() combination
  13068. _gl.enable( _gl.BLEND );
  13069. _gl.blendEquation( _gl.FUNC_ADD );
  13070. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  13071. } else if ( blending === THREE.CustomBlending ) {
  13072. _gl.enable( _gl.BLEND );
  13073. } else {
  13074. _gl.enable( _gl.BLEND );
  13075. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  13076. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  13077. }
  13078. _oldBlending = blending;
  13079. }
  13080. if ( blending === THREE.CustomBlending ) {
  13081. if ( blendEquation !== _oldBlendEquation ) {
  13082. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  13083. _oldBlendEquation = blendEquation;
  13084. }
  13085. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  13086. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  13087. _oldBlendSrc = blendSrc;
  13088. _oldBlendDst = blendDst;
  13089. }
  13090. } else {
  13091. _oldBlendEquation = null;
  13092. _oldBlendSrc = null;
  13093. _oldBlendDst = null;
  13094. }
  13095. };
  13096. // Defines
  13097. function generateDefines ( defines ) {
  13098. var value, chunk, chunks = [];
  13099. for ( var d in defines ) {
  13100. value = defines[ d ];
  13101. if ( value === false ) continue;
  13102. chunk = "#define " + d + " " + value;
  13103. chunks.push( chunk );
  13104. }
  13105. return chunks.join( "\n" );
  13106. };
  13107. // Shaders
  13108. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  13109. var p, pl, d, program, code;
  13110. var chunks = [];
  13111. // Generate code
  13112. if ( shaderID ) {
  13113. chunks.push( shaderID );
  13114. } else {
  13115. chunks.push( fragmentShader );
  13116. chunks.push( vertexShader );
  13117. }
  13118. for ( d in defines ) {
  13119. chunks.push( d );
  13120. chunks.push( defines[ d ] );
  13121. }
  13122. for ( p in parameters ) {
  13123. chunks.push( p );
  13124. chunks.push( parameters[ p ] );
  13125. }
  13126. code = chunks.join();
  13127. // Check if code has been already compiled
  13128. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  13129. var programInfo = _programs[ p ];
  13130. if ( programInfo.code === code ) {
  13131. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  13132. programInfo.usedTimes ++;
  13133. return programInfo.program;
  13134. }
  13135. }
  13136. //console.log( "building new program " );
  13137. //
  13138. var customDefines = generateDefines( defines );
  13139. //
  13140. program = _gl.createProgram();
  13141. var prefix_vertex = [
  13142. "precision " + _precision + " float;",
  13143. customDefines,
  13144. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  13145. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13146. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13147. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13148. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13149. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13150. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13151. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13152. "#define MAX_SHADOWS " + parameters.maxShadows,
  13153. "#define MAX_BONES " + parameters.maxBones,
  13154. parameters.map ? "#define USE_MAP" : "",
  13155. parameters.envMap ? "#define USE_ENVMAP" : "",
  13156. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13157. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13158. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13159. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13160. parameters.vertexColors ? "#define USE_COLOR" : "",
  13161. parameters.skinning ? "#define USE_SKINNING" : "",
  13162. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  13163. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  13164. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  13165. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  13166. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  13167. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13168. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13169. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13170. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13171. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13172. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  13173. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13174. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13175. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  13176. "uniform mat4 modelMatrix;",
  13177. "uniform mat4 modelViewMatrix;",
  13178. "uniform mat4 projectionMatrix;",
  13179. "uniform mat4 viewMatrix;",
  13180. "uniform mat3 normalMatrix;",
  13181. "uniform vec3 cameraPosition;",
  13182. "attribute vec3 position;",
  13183. "attribute vec3 normal;",
  13184. "attribute vec2 uv;",
  13185. "attribute vec2 uv2;",
  13186. "#ifdef USE_COLOR",
  13187. "attribute vec3 color;",
  13188. "#endif",
  13189. "#ifdef USE_MORPHTARGETS",
  13190. "attribute vec3 morphTarget0;",
  13191. "attribute vec3 morphTarget1;",
  13192. "attribute vec3 morphTarget2;",
  13193. "attribute vec3 morphTarget3;",
  13194. "#ifdef USE_MORPHNORMALS",
  13195. "attribute vec3 morphNormal0;",
  13196. "attribute vec3 morphNormal1;",
  13197. "attribute vec3 morphNormal2;",
  13198. "attribute vec3 morphNormal3;",
  13199. "#else",
  13200. "attribute vec3 morphTarget4;",
  13201. "attribute vec3 morphTarget5;",
  13202. "attribute vec3 morphTarget6;",
  13203. "attribute vec3 morphTarget7;",
  13204. "#endif",
  13205. "#endif",
  13206. "#ifdef USE_SKINNING",
  13207. "attribute vec4 skinIndex;",
  13208. "attribute vec4 skinWeight;",
  13209. "#endif",
  13210. ""
  13211. ].join("\n");
  13212. var prefix_fragment = [
  13213. "precision " + _precision + " float;",
  13214. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  13215. customDefines,
  13216. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13217. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13218. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13219. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13220. "#define MAX_SHADOWS " + parameters.maxShadows,
  13221. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  13222. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13223. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13224. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13225. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  13226. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  13227. parameters.map ? "#define USE_MAP" : "",
  13228. parameters.envMap ? "#define USE_ENVMAP" : "",
  13229. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13230. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13231. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13232. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13233. parameters.vertexColors ? "#define USE_COLOR" : "",
  13234. parameters.metal ? "#define METAL" : "",
  13235. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13236. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13237. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13238. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13239. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13240. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  13241. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13242. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13243. "uniform mat4 viewMatrix;",
  13244. "uniform vec3 cameraPosition;",
  13245. ""
  13246. ].join("\n");
  13247. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  13248. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  13249. _gl.attachShader( program, glVertexShader );
  13250. _gl.attachShader( program, glFragmentShader );
  13251. _gl.linkProgram( program );
  13252. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  13253. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  13254. }
  13255. // clean up
  13256. _gl.deleteShader( glFragmentShader );
  13257. _gl.deleteShader( glVertexShader );
  13258. //console.log( prefix_fragment + fragmentShader );
  13259. //console.log( prefix_vertex + vertexShader );
  13260. program.uniforms = {};
  13261. program.attributes = {};
  13262. var identifiers, u, a, i;
  13263. // cache uniform locations
  13264. identifiers = [
  13265. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  13266. 'morphTargetInfluences'
  13267. ];
  13268. if ( parameters.useVertexTexture ) {
  13269. identifiers.push( 'boneTexture' );
  13270. } else {
  13271. identifiers.push( 'boneGlobalMatrices' );
  13272. }
  13273. for ( u in uniforms ) {
  13274. identifiers.push( u );
  13275. }
  13276. cacheUniformLocations( program, identifiers );
  13277. // cache attributes locations
  13278. identifiers = [
  13279. "position", "normal", "uv", "uv2", "tangent", "color",
  13280. "skinIndex", "skinWeight", "lineDistance"
  13281. ];
  13282. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  13283. identifiers.push( "morphTarget" + i );
  13284. }
  13285. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  13286. identifiers.push( "morphNormal" + i );
  13287. }
  13288. for ( a in attributes ) {
  13289. identifiers.push( a );
  13290. }
  13291. cacheAttributeLocations( program, identifiers );
  13292. program.id = _programs_counter ++;
  13293. _programs.push( { program: program, code: code, usedTimes: 1 } );
  13294. _this.info.memory.programs = _programs.length;
  13295. return program;
  13296. };
  13297. // Shader parameters cache
  13298. function cacheUniformLocations ( program, identifiers ) {
  13299. var i, l, id;
  13300. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13301. id = identifiers[ i ];
  13302. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  13303. }
  13304. };
  13305. function cacheAttributeLocations ( program, identifiers ) {
  13306. var i, l, id;
  13307. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13308. id = identifiers[ i ];
  13309. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  13310. }
  13311. };
  13312. function addLineNumbers ( string ) {
  13313. var chunks = string.split( "\n" );
  13314. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  13315. // Chrome reports shader errors on lines
  13316. // starting counting from 1
  13317. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  13318. }
  13319. return chunks.join( "\n" );
  13320. };
  13321. function getShader ( type, string ) {
  13322. var shader;
  13323. if ( type === "fragment" ) {
  13324. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  13325. } else if ( type === "vertex" ) {
  13326. shader = _gl.createShader( _gl.VERTEX_SHADER );
  13327. }
  13328. _gl.shaderSource( shader, string );
  13329. _gl.compileShader( shader );
  13330. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  13331. console.error( _gl.getShaderInfoLog( shader ) );
  13332. console.error( addLineNumbers( string ) );
  13333. return null;
  13334. }
  13335. return shader;
  13336. };
  13337. // Textures
  13338. function isPowerOfTwo ( value ) {
  13339. return ( value & ( value - 1 ) ) === 0;
  13340. };
  13341. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  13342. if ( isImagePowerOfTwo ) {
  13343. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13344. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13345. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13346. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13347. } else {
  13348. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13349. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13350. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13351. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13352. }
  13353. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  13354. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  13355. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  13356. texture.__oldAnisotropy = texture.anisotropy;
  13357. }
  13358. }
  13359. };
  13360. this.setTexture = function ( texture, slot ) {
  13361. if ( texture.needsUpdate ) {
  13362. if ( ! texture.__webglInit ) {
  13363. texture.__webglInit = true;
  13364. texture.__webglTexture = _gl.createTexture();
  13365. _this.info.memory.textures ++;
  13366. }
  13367. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13368. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13369. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13370. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13371. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  13372. var image = texture.image,
  13373. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13374. glFormat = paramThreeToGL( texture.format ),
  13375. glType = paramThreeToGL( texture.type );
  13376. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  13377. var mipmap, mipmaps = texture.mipmaps;
  13378. if ( texture instanceof THREE.DataTexture ) {
  13379. // use manually created mipmaps if available
  13380. // if there are no manual mipmaps
  13381. // set 0 level mipmap and then use GL to generate other mipmap levels
  13382. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13383. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13384. mipmap = mipmaps[ i ];
  13385. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13386. }
  13387. texture.generateMipmaps = false;
  13388. } else {
  13389. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13390. }
  13391. } else if ( texture instanceof THREE.CompressedTexture ) {
  13392. // compressed textures can only use manually created mipmaps
  13393. // WebGL can't generate mipmaps for DDS textures
  13394. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13395. mipmap = mipmaps[ i ];
  13396. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13397. }
  13398. } else { // regular Texture (image, video, canvas)
  13399. // use manually created mipmaps if available
  13400. // if there are no manual mipmaps
  13401. // set 0 level mipmap and then use GL to generate other mipmap levels
  13402. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13403. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13404. mipmap = mipmaps[ i ];
  13405. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  13406. }
  13407. texture.generateMipmaps = false;
  13408. } else {
  13409. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13410. }
  13411. }
  13412. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13413. texture.needsUpdate = false;
  13414. if ( texture.onUpdate ) texture.onUpdate();
  13415. } else {
  13416. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13417. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13418. }
  13419. };
  13420. function clampToMaxSize ( image, maxSize ) {
  13421. if ( image.width <= maxSize && image.height <= maxSize ) {
  13422. return image;
  13423. }
  13424. // Warning: Scaling through the canvas will only work with images that use
  13425. // premultiplied alpha.
  13426. var maxDimension = Math.max( image.width, image.height );
  13427. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  13428. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  13429. var canvas = document.createElement( 'canvas' );
  13430. canvas.width = newWidth;
  13431. canvas.height = newHeight;
  13432. var ctx = canvas.getContext( "2d" );
  13433. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  13434. return canvas;
  13435. }
  13436. function setCubeTexture ( texture, slot ) {
  13437. if ( texture.image.length === 6 ) {
  13438. if ( texture.needsUpdate ) {
  13439. if ( ! texture.image.__webglTextureCube ) {
  13440. texture.image.__webglTextureCube = _gl.createTexture();
  13441. _this.info.memory.textures ++;
  13442. }
  13443. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13444. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13445. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13446. var isCompressed = texture instanceof THREE.CompressedTexture;
  13447. var cubeImage = [];
  13448. for ( var i = 0; i < 6; i ++ ) {
  13449. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  13450. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  13451. } else {
  13452. cubeImage[ i ] = texture.image[ i ];
  13453. }
  13454. }
  13455. var image = cubeImage[ 0 ],
  13456. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13457. glFormat = paramThreeToGL( texture.format ),
  13458. glType = paramThreeToGL( texture.type );
  13459. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  13460. for ( var i = 0; i < 6; i ++ ) {
  13461. if ( isCompressed ) {
  13462. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13463. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13464. mipmap = mipmaps[ j ];
  13465. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13466. }
  13467. } else {
  13468. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13469. }
  13470. }
  13471. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  13472. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13473. }
  13474. texture.needsUpdate = false;
  13475. if ( texture.onUpdate ) texture.onUpdate();
  13476. } else {
  13477. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13478. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13479. }
  13480. }
  13481. };
  13482. function setCubeTextureDynamic ( texture, slot ) {
  13483. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13484. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  13485. };
  13486. // Render targets
  13487. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  13488. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13489. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  13490. };
  13491. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  13492. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13493. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13494. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13495. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13496. /* For some reason this is not working. Defaulting to RGBA4.
  13497. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13498. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  13499. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13500. */
  13501. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13502. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  13503. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13504. } else {
  13505. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  13506. }
  13507. };
  13508. this.setRenderTarget = function ( renderTarget ) {
  13509. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  13510. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  13511. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  13512. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  13513. renderTarget.__webglTexture = _gl.createTexture();
  13514. _this.info.memory.textures ++;
  13515. // Setup texture, create render and frame buffers
  13516. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  13517. glFormat = paramThreeToGL( renderTarget.format ),
  13518. glType = paramThreeToGL( renderTarget.type );
  13519. if ( isCube ) {
  13520. renderTarget.__webglFramebuffer = [];
  13521. renderTarget.__webglRenderbuffer = [];
  13522. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13523. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  13524. for ( var i = 0; i < 6; i ++ ) {
  13525. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13526. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  13527. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13528. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  13529. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  13530. }
  13531. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13532. } else {
  13533. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  13534. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  13535. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13536. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  13537. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13538. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  13539. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  13540. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13541. }
  13542. // Release everything
  13543. if ( isCube ) {
  13544. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13545. } else {
  13546. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13547. }
  13548. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  13549. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
  13550. }
  13551. var framebuffer, width, height, vx, vy;
  13552. if ( renderTarget ) {
  13553. if ( isCube ) {
  13554. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13555. } else {
  13556. framebuffer = renderTarget.__webglFramebuffer;
  13557. }
  13558. width = renderTarget.width;
  13559. height = renderTarget.height;
  13560. vx = 0;
  13561. vy = 0;
  13562. } else {
  13563. framebuffer = null;
  13564. width = _viewportWidth;
  13565. height = _viewportHeight;
  13566. vx = _viewportX;
  13567. vy = _viewportY;
  13568. }
  13569. if ( framebuffer !== _currentFramebuffer ) {
  13570. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13571. _gl.viewport( vx, vy, width, height );
  13572. _currentFramebuffer = framebuffer;
  13573. }
  13574. _currentWidth = width;
  13575. _currentHeight = height;
  13576. };
  13577. function updateRenderTargetMipmap ( renderTarget ) {
  13578. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  13579. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13580. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13581. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13582. } else {
  13583. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13584. _gl.generateMipmap( _gl.TEXTURE_2D );
  13585. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13586. }
  13587. };
  13588. // Fallback filters for non-power-of-2 textures
  13589. function filterFallback ( f ) {
  13590. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  13591. return _gl.NEAREST;
  13592. }
  13593. return _gl.LINEAR;
  13594. };
  13595. // Map three.js constants to WebGL constants
  13596. function paramThreeToGL ( p ) {
  13597. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  13598. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13599. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13600. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  13601. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13602. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13603. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  13604. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13605. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13606. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13607. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13608. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13609. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13610. if ( p === THREE.ByteType ) return _gl.BYTE;
  13611. if ( p === THREE.ShortType ) return _gl.SHORT;
  13612. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13613. if ( p === THREE.IntType ) return _gl.INT;
  13614. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  13615. if ( p === THREE.FloatType ) return _gl.FLOAT;
  13616. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  13617. if ( p === THREE.RGBFormat ) return _gl.RGB;
  13618. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  13619. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  13620. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13621. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  13622. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13623. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13624. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  13625. if ( p === THREE.OneFactor ) return _gl.ONE;
  13626. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  13627. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13628. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13629. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13630. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  13631. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13632. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  13633. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13634. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13635. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  13636. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13637. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13638. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13639. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13640. }
  13641. return 0;
  13642. };
  13643. // Allocations
  13644. function allocateBones ( object ) {
  13645. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  13646. return 1024;
  13647. } else {
  13648. // default for when object is not specified
  13649. // ( for example when prebuilding shader
  13650. // to be used with multiple objects )
  13651. //
  13652. // - leave some extra space for other uniforms
  13653. // - limit here is ANGLE's 254 max uniform vectors
  13654. // (up to 54 should be safe)
  13655. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  13656. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  13657. var maxBones = nVertexMatrices;
  13658. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  13659. maxBones = Math.min( object.bones.length, maxBones );
  13660. if ( maxBones < object.bones.length ) {
  13661. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  13662. }
  13663. }
  13664. return maxBones;
  13665. }
  13666. };
  13667. function allocateLights ( lights ) {
  13668. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  13669. dirLights = pointLights = spotLights = hemiLights = 0;
  13670. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13671. light = lights[ l ];
  13672. if ( light.onlyShadow ) continue;
  13673. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  13674. if ( light instanceof THREE.PointLight ) pointLights ++;
  13675. if ( light instanceof THREE.SpotLight ) spotLights ++;
  13676. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  13677. }
  13678. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  13679. };
  13680. function allocateShadows ( lights ) {
  13681. var l, ll, light, maxShadows = 0;
  13682. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  13683. light = lights[ l ];
  13684. if ( ! light.castShadow ) continue;
  13685. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  13686. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  13687. }
  13688. return maxShadows;
  13689. };
  13690. // Initialization
  13691. function initGL () {
  13692. try {
  13693. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  13694. throw 'Error creating WebGL context.';
  13695. }
  13696. } catch ( error ) {
  13697. console.error( error );
  13698. }
  13699. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  13700. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  13701. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  13702. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  13703. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  13704. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  13705. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  13706. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  13707. if ( ! _glExtensionTextureFloat ) {
  13708. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  13709. }
  13710. if ( ! _glExtensionStandardDerivatives ) {
  13711. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  13712. }
  13713. if ( ! _glExtensionTextureFilterAnisotropic ) {
  13714. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  13715. }
  13716. if ( ! _glExtensionCompressedTextureS3TC ) {
  13717. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  13718. }
  13719. };
  13720. function setDefaultGLState () {
  13721. _gl.clearColor( 0, 0, 0, 1 );
  13722. _gl.clearDepth( 1 );
  13723. _gl.clearStencil( 0 );
  13724. _gl.enable( _gl.DEPTH_TEST );
  13725. _gl.depthFunc( _gl.LEQUAL );
  13726. _gl.frontFace( _gl.CCW );
  13727. _gl.cullFace( _gl.BACK );
  13728. _gl.enable( _gl.CULL_FACE );
  13729. _gl.enable( _gl.BLEND );
  13730. _gl.blendEquation( _gl.FUNC_ADD );
  13731. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  13732. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  13733. };
  13734. // default plugins (order is important)
  13735. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  13736. this.addPrePlugin( this.shadowMapPlugin );
  13737. this.addPostPlugin( new THREE.SpritePlugin() );
  13738. this.addPostPlugin( new THREE.LensFlarePlugin() );
  13739. };
  13740. /**
  13741. * @author szimek / https://github.com/szimek/
  13742. * @author alteredq / http://alteredqualia.com/
  13743. */
  13744. THREE.WebGLRenderTarget = function ( width, height, options ) {
  13745. this.width = width;
  13746. this.height = height;
  13747. options = options || {};
  13748. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  13749. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  13750. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  13751. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  13752. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  13753. this.offset = new THREE.Vector2( 0, 0 );
  13754. this.repeat = new THREE.Vector2( 1, 1 );
  13755. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  13756. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  13757. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  13758. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  13759. this.generateMipmaps = true;
  13760. };
  13761. THREE.WebGLRenderTarget.prototype.clone = function() {
  13762. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  13763. tmp.wrapS = this.wrapS;
  13764. tmp.wrapT = this.wrapT;
  13765. tmp.magFilter = this.magFilter;
  13766. tmp.anisotropy = this.anisotropy;
  13767. tmp.minFilter = this.minFilter;
  13768. tmp.offset.copy( this.offset );
  13769. tmp.repeat.copy( this.repeat );
  13770. tmp.format = this.format;
  13771. tmp.type = this.type;
  13772. tmp.depthBuffer = this.depthBuffer;
  13773. tmp.stencilBuffer = this.stencilBuffer;
  13774. tmp.generateMipmaps = this.generateMipmaps;
  13775. return tmp;
  13776. };
  13777. /**
  13778. * @author alteredq / http://alteredqualia.com
  13779. */
  13780. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  13781. THREE.WebGLRenderTarget.call( this, width, height, options );
  13782. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  13783. };
  13784. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  13785. /**
  13786. * @author mrdoob / http://mrdoob.com/
  13787. */
  13788. THREE.RenderableVertex = function () {
  13789. this.positionWorld = new THREE.Vector3();
  13790. this.positionScreen = new THREE.Vector4();
  13791. this.visible = true;
  13792. };
  13793. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  13794. this.positionWorld.copy( vertex.positionWorld );
  13795. this.positionScreen.copy( vertex.positionScreen );
  13796. }
  13797. /**
  13798. * @author mrdoob / http://mrdoob.com/
  13799. */
  13800. THREE.RenderableFace3 = function () {
  13801. this.v1 = new THREE.RenderableVertex();
  13802. this.v2 = new THREE.RenderableVertex();
  13803. this.v3 = new THREE.RenderableVertex();
  13804. this.centroidWorld = new THREE.Vector3();
  13805. this.centroidScreen = new THREE.Vector3();
  13806. this.normalWorld = new THREE.Vector3();
  13807. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13808. this.vertexNormalsLength = 0;
  13809. this.color = null;
  13810. this.material = null;
  13811. this.uvs = [[]];
  13812. this.z = null;
  13813. };
  13814. /**
  13815. * @author mrdoob / http://mrdoob.com/
  13816. */
  13817. THREE.RenderableFace4 = function () {
  13818. this.v1 = new THREE.RenderableVertex();
  13819. this.v2 = new THREE.RenderableVertex();
  13820. this.v3 = new THREE.RenderableVertex();
  13821. this.v4 = new THREE.RenderableVertex();
  13822. this.centroidWorld = new THREE.Vector3();
  13823. this.centroidScreen = new THREE.Vector3();
  13824. this.normalWorld = new THREE.Vector3();
  13825. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13826. this.vertexNormalsLength = 0;
  13827. this.color = null;
  13828. this.material = null;
  13829. this.uvs = [[]];
  13830. this.z = null;
  13831. };
  13832. /**
  13833. * @author mrdoob / http://mrdoob.com/
  13834. */
  13835. THREE.RenderableObject = function () {
  13836. this.object = null;
  13837. this.z = null;
  13838. };
  13839. /**
  13840. * @author mrdoob / http://mrdoob.com/
  13841. */
  13842. THREE.RenderableParticle = function () {
  13843. this.object = null;
  13844. this.x = null;
  13845. this.y = null;
  13846. this.z = null;
  13847. this.rotation = null;
  13848. this.scale = new THREE.Vector2();
  13849. this.material = null;
  13850. };
  13851. /**
  13852. * @author mrdoob / http://mrdoob.com/
  13853. */
  13854. THREE.RenderableLine = function () {
  13855. this.z = null;
  13856. this.v1 = new THREE.RenderableVertex();
  13857. this.v2 = new THREE.RenderableVertex();
  13858. this.material = null;
  13859. };
  13860. /**
  13861. * @author alteredq / http://alteredqualia.com/
  13862. */
  13863. THREE.ColorUtils = {
  13864. adjustHSV : function ( color, h, s, v ) {
  13865. var hsv = THREE.ColorUtils.__hsv;
  13866. color.getHSV( hsv );
  13867. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  13868. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  13869. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  13870. color.setHSV( hsv.h, hsv.s, hsv.v );
  13871. }
  13872. };
  13873. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  13874. * @author mrdoob / http://mrdoob.com/
  13875. * @author alteredq / http://alteredqualia.com/
  13876. */
  13877. THREE.GeometryUtils = {
  13878. // Merge two geometries or geometry and geometry from object (using object's transform)
  13879. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  13880. var matrix, matrixRotation,
  13881. vertexOffset = geometry1.vertices.length,
  13882. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  13883. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  13884. vertices1 = geometry1.vertices,
  13885. vertices2 = geometry2.vertices,
  13886. faces1 = geometry1.faces,
  13887. faces2 = geometry2.faces,
  13888. uvs1 = geometry1.faceVertexUvs[ 0 ],
  13889. uvs2 = geometry2.faceVertexUvs[ 0 ];
  13890. if ( object2 instanceof THREE.Mesh ) {
  13891. object2.matrixAutoUpdate && object2.updateMatrix();
  13892. matrix = object2.matrix;
  13893. matrixRotation = new THREE.Matrix4();
  13894. matrixRotation.extractRotation( matrix, object2.scale );
  13895. }
  13896. // vertices
  13897. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  13898. var vertex = vertices2[ i ];
  13899. var vertexCopy = vertex.clone();
  13900. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  13901. vertices1.push( vertexCopy );
  13902. }
  13903. // faces
  13904. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  13905. var face = faces2[ i ], faceCopy, normal, color,
  13906. faceVertexNormals = face.vertexNormals,
  13907. faceVertexColors = face.vertexColors;
  13908. if ( face instanceof THREE.Face3 ) {
  13909. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  13910. } else if ( face instanceof THREE.Face4 ) {
  13911. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  13912. }
  13913. faceCopy.normal.copy( face.normal );
  13914. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  13915. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  13916. normal = faceVertexNormals[ j ].clone();
  13917. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  13918. faceCopy.vertexNormals.push( normal );
  13919. }
  13920. faceCopy.color.copy( face.color );
  13921. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  13922. color = faceVertexColors[ j ];
  13923. faceCopy.vertexColors.push( color.clone() );
  13924. }
  13925. faceCopy.materialIndex = face.materialIndex;
  13926. faceCopy.centroid.copy( face.centroid );
  13927. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  13928. faces1.push( faceCopy );
  13929. }
  13930. // uvs
  13931. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  13932. var uv = uvs2[ i ], uvCopy = [];
  13933. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13934. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13935. }
  13936. uvs1.push( uvCopy );
  13937. }
  13938. },
  13939. removeMaterials: function ( geometry, materialIndexArray ) {
  13940. var materialIndexMap = {};
  13941. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  13942. materialIndexMap[ materialIndexArray[i] ] = true;
  13943. }
  13944. var face, newFaces = [];
  13945. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13946. face = geometry.faces[ i ];
  13947. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  13948. }
  13949. geometry.faces = newFaces;
  13950. },
  13951. // Get random point in triangle (via barycentric coordinates)
  13952. // (uniform distribution)
  13953. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  13954. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  13955. var a, b, c,
  13956. point = new THREE.Vector3(),
  13957. tmp = THREE.GeometryUtils.__v1;
  13958. a = THREE.GeometryUtils.random();
  13959. b = THREE.GeometryUtils.random();
  13960. if ( ( a + b ) > 1 ) {
  13961. a = 1 - a;
  13962. b = 1 - b;
  13963. }
  13964. c = 1 - a - b;
  13965. point.copy( vectorA );
  13966. point.multiplyScalar( a );
  13967. tmp.copy( vectorB );
  13968. tmp.multiplyScalar( b );
  13969. point.addSelf( tmp );
  13970. tmp.copy( vectorC );
  13971. tmp.multiplyScalar( c );
  13972. point.addSelf( tmp );
  13973. return point;
  13974. },
  13975. // Get random point in face (triangle / quad)
  13976. // (uniform distribution)
  13977. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  13978. var vA, vB, vC, vD;
  13979. if ( face instanceof THREE.Face3 ) {
  13980. vA = geometry.vertices[ face.a ];
  13981. vB = geometry.vertices[ face.b ];
  13982. vC = geometry.vertices[ face.c ];
  13983. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  13984. } else if ( face instanceof THREE.Face4 ) {
  13985. vA = geometry.vertices[ face.a ];
  13986. vB = geometry.vertices[ face.b ];
  13987. vC = geometry.vertices[ face.c ];
  13988. vD = geometry.vertices[ face.d ];
  13989. var area1, area2;
  13990. if ( useCachedAreas ) {
  13991. if ( face._area1 && face._area2 ) {
  13992. area1 = face._area1;
  13993. area2 = face._area2;
  13994. } else {
  13995. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13996. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13997. face._area1 = area1;
  13998. face._area2 = area2;
  13999. }
  14000. } else {
  14001. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  14002. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14003. }
  14004. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  14005. if ( r < area1 ) {
  14006. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  14007. } else {
  14008. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  14009. }
  14010. }
  14011. },
  14012. // Get uniformly distributed random points in mesh
  14013. // - create array with cumulative sums of face areas
  14014. // - pick random number from 0 to total area
  14015. // - find corresponding place in area array by binary search
  14016. // - get random point in face
  14017. randomPointsInGeometry: function ( geometry, n ) {
  14018. var face, i,
  14019. faces = geometry.faces,
  14020. vertices = geometry.vertices,
  14021. il = faces.length,
  14022. totalArea = 0,
  14023. cumulativeAreas = [],
  14024. vA, vB, vC, vD;
  14025. // precompute face areas
  14026. for ( i = 0; i < il; i ++ ) {
  14027. face = faces[ i ];
  14028. if ( face instanceof THREE.Face3 ) {
  14029. vA = vertices[ face.a ];
  14030. vB = vertices[ face.b ];
  14031. vC = vertices[ face.c ];
  14032. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  14033. } else if ( face instanceof THREE.Face4 ) {
  14034. vA = vertices[ face.a ];
  14035. vB = vertices[ face.b ];
  14036. vC = vertices[ face.c ];
  14037. vD = vertices[ face.d ];
  14038. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14039. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14040. face._area = face._area1 + face._area2;
  14041. }
  14042. totalArea += face._area;
  14043. cumulativeAreas[ i ] = totalArea;
  14044. }
  14045. // binary search cumulative areas array
  14046. function binarySearchIndices( value ) {
  14047. function binarySearch( start, end ) {
  14048. // return closest larger index
  14049. // if exact number is not found
  14050. if ( end < start )
  14051. return start;
  14052. var mid = start + Math.floor( ( end - start ) / 2 );
  14053. if ( cumulativeAreas[ mid ] > value ) {
  14054. return binarySearch( start, mid - 1 );
  14055. } else if ( cumulativeAreas[ mid ] < value ) {
  14056. return binarySearch( mid + 1, end );
  14057. } else {
  14058. return mid;
  14059. }
  14060. }
  14061. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  14062. return result;
  14063. }
  14064. // pick random face weighted by face area
  14065. var r, index,
  14066. result = [];
  14067. var stats = {};
  14068. for ( i = 0; i < n; i ++ ) {
  14069. r = THREE.GeometryUtils.random() * totalArea;
  14070. index = binarySearchIndices( r );
  14071. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  14072. if ( ! stats[ index ] ) {
  14073. stats[ index ] = 1;
  14074. } else {
  14075. stats[ index ] += 1;
  14076. }
  14077. }
  14078. return result;
  14079. },
  14080. // Get triangle area (by Heron's formula)
  14081. // http://en.wikipedia.org/wiki/Heron%27s_formula
  14082. triangleArea: function ( vectorA, vectorB, vectorC ) {
  14083. var s, a, b, c,
  14084. tmp = THREE.GeometryUtils.__v1;
  14085. tmp.sub( vectorA, vectorB );
  14086. a = tmp.length();
  14087. tmp.sub( vectorA, vectorC );
  14088. b = tmp.length();
  14089. tmp.sub( vectorB, vectorC );
  14090. c = tmp.length();
  14091. s = 0.5 * ( a + b + c );
  14092. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  14093. },
  14094. // Center geometry so that 0,0,0 is in center of bounding box
  14095. center: function ( geometry ) {
  14096. geometry.computeBoundingBox();
  14097. var bb = geometry.boundingBox;
  14098. var offset = new THREE.Vector3();
  14099. offset.add( bb.min, bb.max );
  14100. offset.multiplyScalar( -0.5 );
  14101. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  14102. geometry.computeBoundingBox();
  14103. return offset;
  14104. },
  14105. // Normalize UVs to be from <0,1>
  14106. // (for now just the first set of UVs)
  14107. normalizeUVs: function ( geometry ) {
  14108. var uvSet = geometry.faceVertexUvs[ 0 ];
  14109. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  14110. var uvs = uvSet[ i ];
  14111. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  14112. // texture repeat
  14113. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  14114. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  14115. }
  14116. }
  14117. },
  14118. triangulateQuads: function ( geometry ) {
  14119. var i, il, j, jl;
  14120. var faces = [];
  14121. var faceUvs = [];
  14122. var faceVertexUvs = [];
  14123. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  14124. faceUvs[ i ] = [];
  14125. }
  14126. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14127. faceVertexUvs[ i ] = [];
  14128. }
  14129. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14130. var face = geometry.faces[ i ];
  14131. if ( face instanceof THREE.Face4 ) {
  14132. var a = face.a;
  14133. var b = face.b;
  14134. var c = face.c;
  14135. var d = face.d;
  14136. var triA = new THREE.Face3();
  14137. var triB = new THREE.Face3();
  14138. triA.color.copy( face.color );
  14139. triB.color.copy( face.color );
  14140. triA.materialIndex = face.materialIndex;
  14141. triB.materialIndex = face.materialIndex;
  14142. triA.a = a;
  14143. triA.b = b;
  14144. triA.c = d;
  14145. triB.a = b;
  14146. triB.b = c;
  14147. triB.c = d;
  14148. if ( face.vertexColors.length === 4 ) {
  14149. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  14150. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  14151. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14152. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  14153. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  14154. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14155. }
  14156. faces.push( triA, triB );
  14157. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14158. if ( geometry.faceVertexUvs[ j ].length ) {
  14159. var uvs = geometry.faceVertexUvs[ j ][ i ];
  14160. var uvA = uvs[ 0 ];
  14161. var uvB = uvs[ 1 ];
  14162. var uvC = uvs[ 2 ];
  14163. var uvD = uvs[ 3 ];
  14164. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  14165. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  14166. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14167. }
  14168. }
  14169. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14170. if ( geometry.faceUvs[ j ].length ) {
  14171. var faceUv = geometry.faceUvs[ j ][ i ];
  14172. faceUvs[ j ].push( faceUv, faceUv );
  14173. }
  14174. }
  14175. } else {
  14176. faces.push( face );
  14177. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14178. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  14179. }
  14180. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14181. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14182. }
  14183. }
  14184. }
  14185. geometry.faces = faces;
  14186. geometry.faceUvs = faceUvs;
  14187. geometry.faceVertexUvs = faceVertexUvs;
  14188. geometry.computeCentroids();
  14189. geometry.computeFaceNormals();
  14190. geometry.computeVertexNormals();
  14191. if ( geometry.hasTangents ) geometry.computeTangents();
  14192. },
  14193. // Make all faces use unique vertices
  14194. // so that each face can be separated from others
  14195. explode: function( geometry ) {
  14196. var vertices = [];
  14197. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14198. var n = vertices.length;
  14199. var face = geometry.faces[ i ];
  14200. if ( face instanceof THREE.Face4 ) {
  14201. var a = face.a;
  14202. var b = face.b;
  14203. var c = face.c;
  14204. var d = face.d;
  14205. var va = geometry.vertices[ a ];
  14206. var vb = geometry.vertices[ b ];
  14207. var vc = geometry.vertices[ c ];
  14208. var vd = geometry.vertices[ d ];
  14209. vertices.push( va.clone() );
  14210. vertices.push( vb.clone() );
  14211. vertices.push( vc.clone() );
  14212. vertices.push( vd.clone() );
  14213. face.a = n;
  14214. face.b = n + 1;
  14215. face.c = n + 2;
  14216. face.d = n + 3;
  14217. } else {
  14218. var a = face.a;
  14219. var b = face.b;
  14220. var c = face.c;
  14221. var va = geometry.vertices[ a ];
  14222. var vb = geometry.vertices[ b ];
  14223. var vc = geometry.vertices[ c ];
  14224. vertices.push( va.clone() );
  14225. vertices.push( vb.clone() );
  14226. vertices.push( vc.clone() );
  14227. face.a = n;
  14228. face.b = n + 1;
  14229. face.c = n + 2;
  14230. }
  14231. }
  14232. geometry.vertices = vertices;
  14233. delete geometry.__tmpVertices;
  14234. },
  14235. // Break faces with edges longer than maxEdgeLength
  14236. // - not recursive
  14237. tessellate: function ( geometry, maxEdgeLength ) {
  14238. var i, il, face,
  14239. a, b, c, d,
  14240. va, vb, vc, vd,
  14241. dab, dbc, dac, dcd, dad,
  14242. m, m1, m2,
  14243. vm, vm1, vm2,
  14244. vnm, vnm1, vnm2,
  14245. vcm, vcm1, vcm2,
  14246. triA, triB,
  14247. quadA, quadB,
  14248. edge;
  14249. var faces = [];
  14250. var faceVertexUvs = [];
  14251. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14252. faceVertexUvs[ i ] = [];
  14253. }
  14254. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14255. face = geometry.faces[ i ];
  14256. if ( face instanceof THREE.Face3 ) {
  14257. a = face.a;
  14258. b = face.b;
  14259. c = face.c;
  14260. va = geometry.vertices[ a ];
  14261. vb = geometry.vertices[ b ];
  14262. vc = geometry.vertices[ c ];
  14263. dab = va.distanceTo( vb );
  14264. dbc = vb.distanceTo( vc );
  14265. dac = va.distanceTo( vc );
  14266. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  14267. m = geometry.vertices.length;
  14268. triA = face.clone();
  14269. triB = face.clone();
  14270. if ( dab >= dbc && dab >= dac ) {
  14271. vm = va.clone();
  14272. vm.lerpSelf( vb, 0.5 );
  14273. triA.a = a;
  14274. triA.b = m;
  14275. triA.c = c;
  14276. triB.a = m;
  14277. triB.b = b;
  14278. triB.c = c;
  14279. if ( face.vertexNormals.length === 3 ) {
  14280. vnm = face.vertexNormals[ 0 ].clone();
  14281. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14282. triA.vertexNormals[ 1 ].copy( vnm );
  14283. triB.vertexNormals[ 0 ].copy( vnm );
  14284. }
  14285. if ( face.vertexColors.length === 3 ) {
  14286. vcm = face.vertexColors[ 0 ].clone();
  14287. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14288. triA.vertexColors[ 1 ].copy( vcm );
  14289. triB.vertexColors[ 0 ].copy( vcm );
  14290. }
  14291. edge = 0;
  14292. } else if ( dbc >= dab && dbc >= dac ) {
  14293. vm = vb.clone();
  14294. vm.lerpSelf( vc, 0.5 );
  14295. triA.a = a;
  14296. triA.b = b;
  14297. triA.c = m;
  14298. triB.a = m;
  14299. triB.b = c;
  14300. triB.c = a;
  14301. if ( face.vertexNormals.length === 3 ) {
  14302. vnm = face.vertexNormals[ 1 ].clone();
  14303. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14304. triA.vertexNormals[ 2 ].copy( vnm );
  14305. triB.vertexNormals[ 0 ].copy( vnm );
  14306. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  14307. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  14308. }
  14309. if ( face.vertexColors.length === 3 ) {
  14310. vcm = face.vertexColors[ 1 ].clone();
  14311. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14312. triA.vertexColors[ 2 ].copy( vcm );
  14313. triB.vertexColors[ 0 ].copy( vcm );
  14314. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  14315. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  14316. }
  14317. edge = 1;
  14318. } else {
  14319. vm = va.clone();
  14320. vm.lerpSelf( vc, 0.5 );
  14321. triA.a = a;
  14322. triA.b = b;
  14323. triA.c = m;
  14324. triB.a = m;
  14325. triB.b = b;
  14326. triB.c = c;
  14327. if ( face.vertexNormals.length === 3 ) {
  14328. vnm = face.vertexNormals[ 0 ].clone();
  14329. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14330. triA.vertexNormals[ 2 ].copy( vnm );
  14331. triB.vertexNormals[ 0 ].copy( vnm );
  14332. }
  14333. if ( face.vertexColors.length === 3 ) {
  14334. vcm = face.vertexColors[ 0 ].clone();
  14335. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14336. triA.vertexColors[ 2 ].copy( vcm );
  14337. triB.vertexColors[ 0 ].copy( vcm );
  14338. }
  14339. edge = 2;
  14340. }
  14341. faces.push( triA, triB );
  14342. geometry.vertices.push( vm );
  14343. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  14344. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14345. if ( geometry.faceVertexUvs[ j ].length ) {
  14346. uvs = geometry.faceVertexUvs[ j ][ i ];
  14347. uvA = uvs[ 0 ];
  14348. uvB = uvs[ 1 ];
  14349. uvC = uvs[ 2 ];
  14350. // AB
  14351. if ( edge === 0 ) {
  14352. uvM = uvA.clone();
  14353. uvM.lerpSelf( uvB, 0.5 );
  14354. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  14355. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14356. // BC
  14357. } else if ( edge === 1 ) {
  14358. uvM = uvB.clone();
  14359. uvM.lerpSelf( uvC, 0.5 );
  14360. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14361. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  14362. // AC
  14363. } else {
  14364. uvM = uvA.clone();
  14365. uvM.lerpSelf( uvC, 0.5 );
  14366. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14367. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14368. }
  14369. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14370. }
  14371. }
  14372. } else {
  14373. faces.push( face );
  14374. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14375. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14376. }
  14377. }
  14378. } else {
  14379. a = face.a;
  14380. b = face.b;
  14381. c = face.c;
  14382. d = face.d;
  14383. va = geometry.vertices[ a ];
  14384. vb = geometry.vertices[ b ];
  14385. vc = geometry.vertices[ c ];
  14386. vd = geometry.vertices[ d ];
  14387. dab = va.distanceTo( vb );
  14388. dbc = vb.distanceTo( vc );
  14389. dcd = vc.distanceTo( vd );
  14390. dad = va.distanceTo( vd );
  14391. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  14392. m1 = geometry.vertices.length;
  14393. m2 = geometry.vertices.length + 1;
  14394. quadA = face.clone();
  14395. quadB = face.clone();
  14396. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  14397. vm1 = va.clone();
  14398. vm1.lerpSelf( vb, 0.5 );
  14399. vm2 = vc.clone();
  14400. vm2.lerpSelf( vd, 0.5 );
  14401. quadA.a = a;
  14402. quadA.b = m1;
  14403. quadA.c = m2;
  14404. quadA.d = d;
  14405. quadB.a = m1;
  14406. quadB.b = b;
  14407. quadB.c = c;
  14408. quadB.d = m2;
  14409. if ( face.vertexNormals.length === 4 ) {
  14410. vnm1 = face.vertexNormals[ 0 ].clone();
  14411. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14412. vnm2 = face.vertexNormals[ 2 ].clone();
  14413. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  14414. quadA.vertexNormals[ 1 ].copy( vnm1 );
  14415. quadA.vertexNormals[ 2 ].copy( vnm2 );
  14416. quadB.vertexNormals[ 0 ].copy( vnm1 );
  14417. quadB.vertexNormals[ 3 ].copy( vnm2 );
  14418. }
  14419. if ( face.vertexColors.length === 4 ) {
  14420. vcm1 = face.vertexColors[ 0 ].clone();
  14421. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14422. vcm2 = face.vertexColors[ 2 ].clone();
  14423. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  14424. quadA.vertexColors[ 1 ].copy( vcm1 );
  14425. quadA.vertexColors[ 2 ].copy( vcm2 );
  14426. quadB.vertexColors[ 0 ].copy( vcm1 );
  14427. quadB.vertexColors[ 3 ].copy( vcm2 );
  14428. }
  14429. edge = 0;
  14430. } else {
  14431. vm1 = vb.clone();
  14432. vm1.lerpSelf( vc, 0.5 );
  14433. vm2 = vd.clone();
  14434. vm2.lerpSelf( va, 0.5 );
  14435. quadA.a = a;
  14436. quadA.b = b;
  14437. quadA.c = m1;
  14438. quadA.d = m2;
  14439. quadB.a = m2;
  14440. quadB.b = m1;
  14441. quadB.c = c;
  14442. quadB.d = d;
  14443. if ( face.vertexNormals.length === 4 ) {
  14444. vnm1 = face.vertexNormals[ 1 ].clone();
  14445. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14446. vnm2 = face.vertexNormals[ 3 ].clone();
  14447. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  14448. quadA.vertexNormals[ 2 ].copy( vnm1 );
  14449. quadA.vertexNormals[ 3 ].copy( vnm2 );
  14450. quadB.vertexNormals[ 0 ].copy( vnm2 );
  14451. quadB.vertexNormals[ 1 ].copy( vnm1 );
  14452. }
  14453. if ( face.vertexColors.length === 4 ) {
  14454. vcm1 = face.vertexColors[ 1 ].clone();
  14455. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14456. vcm2 = face.vertexColors[ 3 ].clone();
  14457. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  14458. quadA.vertexColors[ 2 ].copy( vcm1 );
  14459. quadA.vertexColors[ 3 ].copy( vcm2 );
  14460. quadB.vertexColors[ 0 ].copy( vcm2 );
  14461. quadB.vertexColors[ 1 ].copy( vcm1 );
  14462. }
  14463. edge = 1;
  14464. }
  14465. faces.push( quadA, quadB );
  14466. geometry.vertices.push( vm1, vm2 );
  14467. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  14468. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14469. if ( geometry.faceVertexUvs[ j ].length ) {
  14470. uvs = geometry.faceVertexUvs[ j ][ i ];
  14471. uvA = uvs[ 0 ];
  14472. uvB = uvs[ 1 ];
  14473. uvC = uvs[ 2 ];
  14474. uvD = uvs[ 3 ];
  14475. // AB + CD
  14476. if ( edge === 0 ) {
  14477. uvM1 = uvA.clone();
  14478. uvM1.lerpSelf( uvB, 0.5 );
  14479. uvM2 = uvC.clone();
  14480. uvM2.lerpSelf( uvD, 0.5 );
  14481. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  14482. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  14483. // BC + AD
  14484. } else {
  14485. uvM1 = uvB.clone();
  14486. uvM1.lerpSelf( uvC, 0.5 );
  14487. uvM2 = uvD.clone();
  14488. uvM2.lerpSelf( uvA, 0.5 );
  14489. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  14490. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  14491. }
  14492. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  14493. }
  14494. }
  14495. } else {
  14496. faces.push( face );
  14497. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14498. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14499. }
  14500. }
  14501. }
  14502. }
  14503. geometry.faces = faces;
  14504. geometry.faceVertexUvs = faceVertexUvs;
  14505. }
  14506. };
  14507. THREE.GeometryUtils.random = THREE.Math.random16;
  14508. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  14509. /**
  14510. * @author alteredq / http://alteredqualia.com/
  14511. * @author mrdoob / http://mrdoob.com/
  14512. */
  14513. THREE.ImageUtils = {
  14514. crossOrigin: 'anonymous',
  14515. loadTexture: function ( url, mapping, onLoad, onError ) {
  14516. var image = new Image();
  14517. var texture = new THREE.Texture( image, mapping );
  14518. var loader = new THREE.ImageLoader();
  14519. loader.addEventListener( 'load', function ( event ) {
  14520. texture.image = event.content;
  14521. texture.needsUpdate = true;
  14522. if ( onLoad ) onLoad( texture );
  14523. } );
  14524. loader.addEventListener( 'error', function ( event ) {
  14525. if ( onError ) onError( event.message );
  14526. } );
  14527. loader.crossOrigin = this.crossOrigin;
  14528. loader.load( url, image );
  14529. texture.sourceFile = url;
  14530. return texture;
  14531. },
  14532. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  14533. var texture = new THREE.CompressedTexture();
  14534. texture.mapping = mapping;
  14535. var request = new XMLHttpRequest();
  14536. request.onload = function () {
  14537. var buffer = request.response;
  14538. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14539. texture.format = dds.format;
  14540. texture.mipmaps = dds.mipmaps;
  14541. texture.image.width = dds.width;
  14542. texture.image.height = dds.height;
  14543. // gl.generateMipmap fails for compressed textures
  14544. // mipmaps must be embedded in the DDS file
  14545. // or texture filters must not use mipmapping
  14546. texture.generateMipmaps = false;
  14547. texture.needsUpdate = true;
  14548. if ( onLoad ) onLoad( texture );
  14549. }
  14550. request.onerror = onError;
  14551. request.open( 'GET', url, true );
  14552. request.responseType = "arraybuffer";
  14553. request.send( null );
  14554. return texture;
  14555. },
  14556. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  14557. var images = [];
  14558. images.loadCount = 0;
  14559. var texture = new THREE.Texture();
  14560. texture.image = images;
  14561. if ( mapping !== undefined ) texture.mapping = mapping;
  14562. // no flipping needed for cube textures
  14563. texture.flipY = false;
  14564. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14565. var cubeImage = new Image();
  14566. images[ i ] = cubeImage;
  14567. cubeImage.onload = function () {
  14568. images.loadCount += 1;
  14569. if ( images.loadCount === 6 ) {
  14570. texture.needsUpdate = true;
  14571. if ( onLoad ) onLoad( texture );
  14572. }
  14573. };
  14574. cubeImage.onerror = onError;
  14575. cubeImage.crossOrigin = this.crossOrigin;
  14576. cubeImage.src = array[ i ];
  14577. }
  14578. return texture;
  14579. },
  14580. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  14581. var images = [];
  14582. images.loadCount = 0;
  14583. var texture = new THREE.CompressedTexture();
  14584. texture.image = images;
  14585. if ( mapping !== undefined ) texture.mapping = mapping;
  14586. // no flipping for cube textures
  14587. // (also flipping doesn't work for compressed textures )
  14588. texture.flipY = false;
  14589. // can't generate mipmaps for compressed textures
  14590. // mips must be embedded in DDS files
  14591. texture.generateMipmaps = false;
  14592. var generateCubeFaceCallback = function ( rq, img ) {
  14593. return function () {
  14594. var buffer = rq.response;
  14595. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14596. img.format = dds.format;
  14597. img.mipmaps = dds.mipmaps;
  14598. img.width = dds.width;
  14599. img.height = dds.height;
  14600. images.loadCount += 1;
  14601. if ( images.loadCount === 6 ) {
  14602. texture.format = dds.format;
  14603. texture.needsUpdate = true;
  14604. if ( onLoad ) onLoad( texture );
  14605. }
  14606. }
  14607. }
  14608. // compressed cubemap textures as 6 separate DDS files
  14609. if ( array instanceof Array ) {
  14610. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14611. var cubeImage = {};
  14612. images[ i ] = cubeImage;
  14613. var request = new XMLHttpRequest();
  14614. request.onload = generateCubeFaceCallback( request, cubeImage );
  14615. request.onerror = onError;
  14616. var url = array[ i ];
  14617. request.open( 'GET', url, true );
  14618. request.responseType = "arraybuffer";
  14619. request.send( null );
  14620. }
  14621. // compressed cubemap texture stored in a single DDS file
  14622. } else {
  14623. var url = array;
  14624. var request = new XMLHttpRequest();
  14625. request.onload = function( ) {
  14626. var buffer = request.response;
  14627. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14628. if ( dds.isCubemap ) {
  14629. var faces = dds.mipmaps.length / dds.mipmapCount;
  14630. for ( var f = 0; f < faces; f ++ ) {
  14631. images[ f ] = { mipmaps : [] };
  14632. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  14633. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  14634. images[ f ].format = dds.format;
  14635. images[ f ].width = dds.width;
  14636. images[ f ].height = dds.height;
  14637. }
  14638. }
  14639. texture.format = dds.format;
  14640. texture.needsUpdate = true;
  14641. if ( onLoad ) onLoad( texture );
  14642. }
  14643. }
  14644. request.onerror = onError;
  14645. request.open( 'GET', url, true );
  14646. request.responseType = "arraybuffer";
  14647. request.send( null );
  14648. }
  14649. return texture;
  14650. },
  14651. parseDDS: function ( buffer, loadMipmaps ) {
  14652. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  14653. // Adapted from @toji's DDS utils
  14654. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  14655. // All values and structures referenced from:
  14656. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  14657. var DDS_MAGIC = 0x20534444;
  14658. var DDSD_CAPS = 0x1,
  14659. DDSD_HEIGHT = 0x2,
  14660. DDSD_WIDTH = 0x4,
  14661. DDSD_PITCH = 0x8,
  14662. DDSD_PIXELFORMAT = 0x1000,
  14663. DDSD_MIPMAPCOUNT = 0x20000,
  14664. DDSD_LINEARSIZE = 0x80000,
  14665. DDSD_DEPTH = 0x800000;
  14666. var DDSCAPS_COMPLEX = 0x8,
  14667. DDSCAPS_MIPMAP = 0x400000,
  14668. DDSCAPS_TEXTURE = 0x1000;
  14669. var DDSCAPS2_CUBEMAP = 0x200,
  14670. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  14671. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  14672. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  14673. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  14674. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  14675. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  14676. DDSCAPS2_VOLUME = 0x200000;
  14677. var DDPF_ALPHAPIXELS = 0x1,
  14678. DDPF_ALPHA = 0x2,
  14679. DDPF_FOURCC = 0x4,
  14680. DDPF_RGB = 0x40,
  14681. DDPF_YUV = 0x200,
  14682. DDPF_LUMINANCE = 0x20000;
  14683. function fourCCToInt32( value ) {
  14684. return value.charCodeAt(0) +
  14685. (value.charCodeAt(1) << 8) +
  14686. (value.charCodeAt(2) << 16) +
  14687. (value.charCodeAt(3) << 24);
  14688. }
  14689. function int32ToFourCC( value ) {
  14690. return String.fromCharCode(
  14691. value & 0xff,
  14692. (value >> 8) & 0xff,
  14693. (value >> 16) & 0xff,
  14694. (value >> 24) & 0xff
  14695. );
  14696. }
  14697. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  14698. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  14699. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  14700. var headerLengthInt = 31; // The header length in 32 bit ints
  14701. // Offsets into the header array
  14702. var off_magic = 0;
  14703. var off_size = 1;
  14704. var off_flags = 2;
  14705. var off_height = 3;
  14706. var off_width = 4;
  14707. var off_mipmapCount = 7;
  14708. var off_pfFlags = 20;
  14709. var off_pfFourCC = 21;
  14710. var off_caps = 27;
  14711. var off_caps2 = 28;
  14712. var off_caps3 = 29;
  14713. var off_caps4 = 30;
  14714. // Parse header
  14715. var header = new Int32Array( buffer, 0, headerLengthInt );
  14716. if ( header[ off_magic ] !== DDS_MAGIC ) {
  14717. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  14718. return dds;
  14719. }
  14720. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  14721. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  14722. return dds;
  14723. }
  14724. var blockBytes;
  14725. var fourCC = header[ off_pfFourCC ];
  14726. switch ( fourCC ) {
  14727. case FOURCC_DXT1:
  14728. blockBytes = 8;
  14729. dds.format = THREE.RGB_S3TC_DXT1_Format;
  14730. break;
  14731. case FOURCC_DXT3:
  14732. blockBytes = 16;
  14733. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  14734. break;
  14735. case FOURCC_DXT5:
  14736. blockBytes = 16;
  14737. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  14738. break;
  14739. default:
  14740. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  14741. return dds;
  14742. }
  14743. dds.mipmapCount = 1;
  14744. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  14745. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  14746. }
  14747. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  14748. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  14749. dds.width = header[ off_width ];
  14750. dds.height = header[ off_height ];
  14751. var dataOffset = header[ off_size ] + 4;
  14752. // Extract mipmaps buffers
  14753. var width = dds.width;
  14754. var height = dds.height;
  14755. var faces = dds.isCubemap ? 6 : 1;
  14756. for ( var face = 0; face < faces; face ++ ) {
  14757. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  14758. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  14759. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  14760. var mipmap = { "data": byteArray, "width": width, "height": height };
  14761. dds.mipmaps.push( mipmap );
  14762. dataOffset += dataLength;
  14763. width = Math.max( width * 0.5, 1 );
  14764. height = Math.max( height * 0.5, 1 );
  14765. }
  14766. width = dds.width;
  14767. height = dds.height;
  14768. }
  14769. return dds;
  14770. },
  14771. getNormalMap: function ( image, depth ) {
  14772. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  14773. var cross = function ( a, b ) {
  14774. 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 ] ];
  14775. }
  14776. var subtract = function ( a, b ) {
  14777. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  14778. }
  14779. var normalize = function ( a ) {
  14780. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  14781. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  14782. }
  14783. depth = depth | 1;
  14784. var width = image.width;
  14785. var height = image.height;
  14786. var canvas = document.createElement( 'canvas' );
  14787. canvas.width = width;
  14788. canvas.height = height;
  14789. var context = canvas.getContext( '2d' );
  14790. context.drawImage( image, 0, 0 );
  14791. var data = context.getImageData( 0, 0, width, height ).data;
  14792. var imageData = context.createImageData( width, height );
  14793. var output = imageData.data;
  14794. for ( var x = 0; x < width; x ++ ) {
  14795. for ( var y = 0; y < height; y ++ ) {
  14796. var ly = y - 1 < 0 ? 0 : y - 1;
  14797. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  14798. var lx = x - 1 < 0 ? 0 : x - 1;
  14799. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  14800. var points = [];
  14801. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  14802. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  14803. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  14804. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  14805. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  14806. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  14807. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  14808. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  14809. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  14810. var normals = [];
  14811. var num_points = points.length;
  14812. for ( var i = 0; i < num_points; i ++ ) {
  14813. var v1 = points[ i ];
  14814. var v2 = points[ ( i + 1 ) % num_points ];
  14815. v1 = subtract( v1, origin );
  14816. v2 = subtract( v2, origin );
  14817. normals.push( normalize( cross( v1, v2 ) ) );
  14818. }
  14819. var normal = [ 0, 0, 0 ];
  14820. for ( var i = 0; i < normals.length; i ++ ) {
  14821. normal[ 0 ] += normals[ i ][ 0 ];
  14822. normal[ 1 ] += normals[ i ][ 1 ];
  14823. normal[ 2 ] += normals[ i ][ 2 ];
  14824. }
  14825. normal[ 0 ] /= normals.length;
  14826. normal[ 1 ] /= normals.length;
  14827. normal[ 2 ] /= normals.length;
  14828. var idx = ( y * width + x ) * 4;
  14829. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14830. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14831. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  14832. output[ idx + 3 ] = 255;
  14833. }
  14834. }
  14835. context.putImageData( imageData, 0, 0 );
  14836. return canvas;
  14837. },
  14838. generateDataTexture: function ( width, height, color ) {
  14839. var size = width * height;
  14840. var data = new Uint8Array( 3 * size );
  14841. var r = Math.floor( color.r * 255 );
  14842. var g = Math.floor( color.g * 255 );
  14843. var b = Math.floor( color.b * 255 );
  14844. for ( var i = 0; i < size; i ++ ) {
  14845. data[ i * 3 ] = r;
  14846. data[ i * 3 + 1 ] = g;
  14847. data[ i * 3 + 2 ] = b;
  14848. }
  14849. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  14850. texture.needsUpdate = true;
  14851. return texture;
  14852. }
  14853. };
  14854. /**
  14855. * @author alteredq / http://alteredqualia.com/
  14856. */
  14857. THREE.SceneUtils = {
  14858. createMultiMaterialObject: function ( geometry, materials ) {
  14859. var group = new THREE.Object3D();
  14860. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  14861. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  14862. }
  14863. return group;
  14864. },
  14865. detach : function ( child, parent, scene ) {
  14866. child.applyMatrix( parent.matrixWorld );
  14867. parent.remove( child );
  14868. scene.add( child );
  14869. },
  14870. attach: function ( child, scene, parent ) {
  14871. var matrixWorldInverse = new THREE.Matrix4();
  14872. matrixWorldInverse.getInverse( parent.matrixWorld );
  14873. child.applyMatrix( matrixWorldInverse );
  14874. scene.remove( child );
  14875. parent.add( child );
  14876. }
  14877. };
  14878. /**
  14879. * @author alteredq / http://alteredqualia.com/
  14880. * @author mrdoob / http://mrdoob.com/
  14881. *
  14882. * ShaderUtils currently contains:
  14883. *
  14884. * fresnel
  14885. * normal
  14886. * cube
  14887. *
  14888. */
  14889. THREE.ShaderUtils = {
  14890. lib: {
  14891. /* -------------------------------------------------------------------------
  14892. // Fresnel shader
  14893. // - based on Nvidia Cg tutorial
  14894. ------------------------------------------------------------------------- */
  14895. 'fresnel': {
  14896. uniforms: {
  14897. "mRefractionRatio": { type: "f", value: 1.02 },
  14898. "mFresnelBias": { type: "f", value: 0.1 },
  14899. "mFresnelPower": { type: "f", value: 2.0 },
  14900. "mFresnelScale": { type: "f", value: 1.0 },
  14901. "tCube": { type: "t", value: null }
  14902. },
  14903. fragmentShader: [
  14904. "uniform samplerCube tCube;",
  14905. "varying vec3 vReflect;",
  14906. "varying vec3 vRefract[3];",
  14907. "varying float vReflectionFactor;",
  14908. "void main() {",
  14909. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  14910. "vec4 refractedColor = vec4( 1.0 );",
  14911. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  14912. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  14913. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  14914. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  14915. "}"
  14916. ].join("\n"),
  14917. vertexShader: [
  14918. "uniform float mRefractionRatio;",
  14919. "uniform float mFresnelBias;",
  14920. "uniform float mFresnelScale;",
  14921. "uniform float mFresnelPower;",
  14922. "varying vec3 vReflect;",
  14923. "varying vec3 vRefract[3];",
  14924. "varying float vReflectionFactor;",
  14925. "void main() {",
  14926. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14927. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  14928. "vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  14929. "vec3 I = worldPosition.xyz - cameraPosition;",
  14930. "vReflect = reflect( I, worldNormal );",
  14931. "vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );",
  14932. "vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );",
  14933. "vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );",
  14934. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );",
  14935. "gl_Position = projectionMatrix * mvPosition;",
  14936. "}"
  14937. ].join("\n")
  14938. },
  14939. /* -------------------------------------------------------------------------
  14940. // Normal map shader
  14941. // - Blinn-Phong
  14942. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  14943. // - point and directional lights (use with "lights: true" material option)
  14944. ------------------------------------------------------------------------- */
  14945. 'normal' : {
  14946. uniforms: THREE.UniformsUtils.merge( [
  14947. THREE.UniformsLib[ "fog" ],
  14948. THREE.UniformsLib[ "lights" ],
  14949. THREE.UniformsLib[ "shadowmap" ],
  14950. {
  14951. "enableAO" : { type: "i", value: 0 },
  14952. "enableDiffuse" : { type: "i", value: 0 },
  14953. "enableSpecular" : { type: "i", value: 0 },
  14954. "enableReflection": { type: "i", value: 0 },
  14955. "enableDisplacement": { type: "i", value: 0 },
  14956. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  14957. "tDiffuse" : { type: "t", value: null },
  14958. "tCube" : { type: "t", value: null },
  14959. "tNormal" : { type: "t", value: null },
  14960. "tSpecular" : { type: "t", value: null },
  14961. "tAO" : { type: "t", value: null },
  14962. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14963. "uDisplacementBias": { type: "f", value: 0.0 },
  14964. "uDisplacementScale": { type: "f", value: 1.0 },
  14965. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14966. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  14967. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14968. "uShininess": { type: "f", value: 30 },
  14969. "uOpacity": { type: "f", value: 1 },
  14970. "useRefract": { type: "i", value: 0 },
  14971. "uRefractionRatio": { type: "f", value: 0.98 },
  14972. "uReflectivity": { type: "f", value: 0.5 },
  14973. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  14974. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14975. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  14976. }
  14977. ] ),
  14978. fragmentShader: [
  14979. "uniform vec3 uAmbientColor;",
  14980. "uniform vec3 uDiffuseColor;",
  14981. "uniform vec3 uSpecularColor;",
  14982. "uniform float uShininess;",
  14983. "uniform float uOpacity;",
  14984. "uniform bool enableDiffuse;",
  14985. "uniform bool enableSpecular;",
  14986. "uniform bool enableAO;",
  14987. "uniform bool enableReflection;",
  14988. "uniform sampler2D tDiffuse;",
  14989. "uniform sampler2D tNormal;",
  14990. "uniform sampler2D tSpecular;",
  14991. "uniform sampler2D tAO;",
  14992. "uniform samplerCube tCube;",
  14993. "uniform vec2 uNormalScale;",
  14994. "uniform bool useRefract;",
  14995. "uniform float uRefractionRatio;",
  14996. "uniform float uReflectivity;",
  14997. "varying vec3 vTangent;",
  14998. "varying vec3 vBinormal;",
  14999. "varying vec3 vNormal;",
  15000. "varying vec2 vUv;",
  15001. "uniform vec3 ambientLightColor;",
  15002. "#if MAX_DIR_LIGHTS > 0",
  15003. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  15004. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  15005. "#endif",
  15006. "#if MAX_HEMI_LIGHTS > 0",
  15007. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  15008. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  15009. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  15010. "#endif",
  15011. "#if MAX_POINT_LIGHTS > 0",
  15012. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  15013. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  15014. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  15015. "#endif",
  15016. "#if MAX_SPOT_LIGHTS > 0",
  15017. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  15018. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  15019. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  15020. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  15021. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  15022. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  15023. "#endif",
  15024. "#ifdef WRAP_AROUND",
  15025. "uniform vec3 wrapRGB;",
  15026. "#endif",
  15027. "varying vec3 vWorldPosition;",
  15028. "varying vec3 vViewPosition;",
  15029. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  15030. THREE.ShaderChunk[ "fog_pars_fragment" ],
  15031. "void main() {",
  15032. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  15033. "vec3 specularTex = vec3( 1.0 );",
  15034. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  15035. "normalTex.xy *= uNormalScale;",
  15036. "normalTex = normalize( normalTex );",
  15037. "if( enableDiffuse ) {",
  15038. "#ifdef GAMMA_INPUT",
  15039. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  15040. "texelColor.xyz *= texelColor.xyz;",
  15041. "gl_FragColor = gl_FragColor * texelColor;",
  15042. "#else",
  15043. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  15044. "#endif",
  15045. "}",
  15046. "if( enableAO ) {",
  15047. "#ifdef GAMMA_INPUT",
  15048. "vec4 aoColor = texture2D( tAO, vUv );",
  15049. "aoColor.xyz *= aoColor.xyz;",
  15050. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  15051. "#else",
  15052. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  15053. "#endif",
  15054. "}",
  15055. "if( enableSpecular )",
  15056. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  15057. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  15058. "vec3 finalNormal = tsb * normalTex;",
  15059. "#ifdef FLIP_SIDED",
  15060. "finalNormal = -finalNormal;",
  15061. "#endif",
  15062. "vec3 normal = normalize( finalNormal );",
  15063. "vec3 viewPosition = normalize( vViewPosition );",
  15064. // point lights
  15065. "#if MAX_POINT_LIGHTS > 0",
  15066. "vec3 pointDiffuse = vec3( 0.0 );",
  15067. "vec3 pointSpecular = vec3( 0.0 );",
  15068. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  15069. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  15070. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  15071. "float pointDistance = 1.0;",
  15072. "if ( pointLightDistance[ i ] > 0.0 )",
  15073. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  15074. "pointVector = normalize( pointVector );",
  15075. // diffuse
  15076. "#ifdef WRAP_AROUND",
  15077. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  15078. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  15079. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  15080. "#else",
  15081. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  15082. "#endif",
  15083. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  15084. // specular
  15085. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  15086. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  15087. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  15088. "#ifdef PHYSICALLY_BASED_SHADING",
  15089. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15090. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15091. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  15092. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  15093. "#else",
  15094. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  15095. "#endif",
  15096. "}",
  15097. "#endif",
  15098. // spot lights
  15099. "#if MAX_SPOT_LIGHTS > 0",
  15100. "vec3 spotDiffuse = vec3( 0.0 );",
  15101. "vec3 spotSpecular = vec3( 0.0 );",
  15102. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  15103. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  15104. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  15105. "float spotDistance = 1.0;",
  15106. "if ( spotLightDistance[ i ] > 0.0 )",
  15107. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  15108. "spotVector = normalize( spotVector );",
  15109. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  15110. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  15111. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  15112. // diffuse
  15113. "#ifdef WRAP_AROUND",
  15114. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  15115. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  15116. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  15117. "#else",
  15118. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  15119. "#endif",
  15120. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  15121. // specular
  15122. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  15123. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  15124. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  15125. "#ifdef PHYSICALLY_BASED_SHADING",
  15126. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15127. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15128. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  15129. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  15130. "#else",
  15131. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  15132. "#endif",
  15133. "}",
  15134. "}",
  15135. "#endif",
  15136. // directional lights
  15137. "#if MAX_DIR_LIGHTS > 0",
  15138. "vec3 dirDiffuse = vec3( 0.0 );",
  15139. "vec3 dirSpecular = vec3( 0.0 );",
  15140. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  15141. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  15142. "vec3 dirVector = normalize( lDirection.xyz );",
  15143. // diffuse
  15144. "#ifdef WRAP_AROUND",
  15145. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  15146. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  15147. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  15148. "#else",
  15149. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  15150. "#endif",
  15151. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  15152. // specular
  15153. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  15154. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  15155. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  15156. "#ifdef PHYSICALLY_BASED_SHADING",
  15157. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15158. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15159. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  15160. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  15161. "#else",
  15162. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  15163. "#endif",
  15164. "}",
  15165. "#endif",
  15166. // hemisphere lights
  15167. "#if MAX_HEMI_LIGHTS > 0",
  15168. "vec3 hemiDiffuse = vec3( 0.0 );",
  15169. "vec3 hemiSpecular = vec3( 0.0 );" ,
  15170. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  15171. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  15172. "vec3 lVector = normalize( lDirection.xyz );",
  15173. // diffuse
  15174. "float dotProduct = dot( normal, lVector );",
  15175. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  15176. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  15177. "hemiDiffuse += uDiffuseColor * hemiColor;",
  15178. // specular (sky light)
  15179. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  15180. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  15181. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  15182. // specular (ground light)
  15183. "vec3 lVectorGround = -lVector;",
  15184. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  15185. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  15186. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  15187. "#ifdef PHYSICALLY_BASED_SHADING",
  15188. "float dotProductGround = dot( normal, lVectorGround );",
  15189. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15190. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15191. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  15192. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  15193. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  15194. "#else",
  15195. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  15196. "#endif",
  15197. "}",
  15198. "#endif",
  15199. // all lights contribution summation
  15200. "vec3 totalDiffuse = vec3( 0.0 );",
  15201. "vec3 totalSpecular = vec3( 0.0 );",
  15202. "#if MAX_DIR_LIGHTS > 0",
  15203. "totalDiffuse += dirDiffuse;",
  15204. "totalSpecular += dirSpecular;",
  15205. "#endif",
  15206. "#if MAX_HEMI_LIGHTS > 0",
  15207. "totalDiffuse += hemiDiffuse;",
  15208. "totalSpecular += hemiSpecular;",
  15209. "#endif",
  15210. "#if MAX_POINT_LIGHTS > 0",
  15211. "totalDiffuse += pointDiffuse;",
  15212. "totalSpecular += pointSpecular;",
  15213. "#endif",
  15214. "#if MAX_SPOT_LIGHTS > 0",
  15215. "totalDiffuse += spotDiffuse;",
  15216. "totalSpecular += spotSpecular;",
  15217. "#endif",
  15218. "#ifdef METAL",
  15219. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  15220. "#else",
  15221. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  15222. "#endif",
  15223. "if ( enableReflection ) {",
  15224. "vec3 vReflect;",
  15225. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  15226. "if ( useRefract ) {",
  15227. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  15228. "} else {",
  15229. "vReflect = reflect( cameraToVertex, normal );",
  15230. "}",
  15231. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15232. "#ifdef GAMMA_INPUT",
  15233. "cubeColor.xyz *= cubeColor.xyz;",
  15234. "#endif",
  15235. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  15236. "}",
  15237. THREE.ShaderChunk[ "shadowmap_fragment" ],
  15238. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  15239. THREE.ShaderChunk[ "fog_fragment" ],
  15240. "}"
  15241. ].join("\n"),
  15242. vertexShader: [
  15243. "attribute vec4 tangent;",
  15244. "uniform vec2 uOffset;",
  15245. "uniform vec2 uRepeat;",
  15246. "uniform bool enableDisplacement;",
  15247. "#ifdef VERTEX_TEXTURES",
  15248. "uniform sampler2D tDisplacement;",
  15249. "uniform float uDisplacementScale;",
  15250. "uniform float uDisplacementBias;",
  15251. "#endif",
  15252. "varying vec3 vTangent;",
  15253. "varying vec3 vBinormal;",
  15254. "varying vec3 vNormal;",
  15255. "varying vec2 vUv;",
  15256. "varying vec3 vWorldPosition;",
  15257. "varying vec3 vViewPosition;",
  15258. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  15259. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  15260. "void main() {",
  15261. THREE.ShaderChunk[ "skinbase_vertex" ],
  15262. THREE.ShaderChunk[ "skinnormal_vertex" ],
  15263. // normal, tangent and binormal vectors
  15264. "#ifdef USE_SKINNING",
  15265. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  15266. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  15267. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  15268. "#else",
  15269. "vNormal = normalize( normalMatrix * normal );",
  15270. "vTangent = normalize( normalMatrix * tangent.xyz );",
  15271. "#endif",
  15272. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  15273. "vUv = uv * uRepeat + uOffset;",
  15274. // displacement mapping
  15275. "vec3 displacedPosition;",
  15276. "#ifdef VERTEX_TEXTURES",
  15277. "if ( enableDisplacement ) {",
  15278. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  15279. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  15280. "displacedPosition = position + normalize( normal ) * df;",
  15281. "} else {",
  15282. "#ifdef USE_SKINNING",
  15283. "vec4 skinVertex = vec4( position, 1.0 );",
  15284. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15285. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15286. "displacedPosition = skinned.xyz;",
  15287. "#else",
  15288. "displacedPosition = position;",
  15289. "#endif",
  15290. "}",
  15291. "#else",
  15292. "#ifdef USE_SKINNING",
  15293. "vec4 skinVertex = vec4( position, 1.0 );",
  15294. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15295. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15296. "displacedPosition = skinned.xyz;",
  15297. "#else",
  15298. "displacedPosition = position;",
  15299. "#endif",
  15300. "#endif",
  15301. //
  15302. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  15303. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  15304. "gl_Position = projectionMatrix * mvPosition;",
  15305. //
  15306. "vWorldPosition = worldPosition.xyz;",
  15307. "vViewPosition = -mvPosition.xyz;",
  15308. // shadows
  15309. "#ifdef USE_SHADOWMAP",
  15310. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  15311. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  15312. "}",
  15313. "#endif",
  15314. "}"
  15315. ].join("\n")
  15316. },
  15317. /* -------------------------------------------------------------------------
  15318. // Cube map shader
  15319. ------------------------------------------------------------------------- */
  15320. 'cube': {
  15321. uniforms: { "tCube": { type: "t", value: null },
  15322. "tFlip": { type: "f", value: -1 } },
  15323. vertexShader: [
  15324. "varying vec3 vWorldPosition;",
  15325. "void main() {",
  15326. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15327. "vWorldPosition = worldPosition.xyz;",
  15328. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  15329. "}"
  15330. ].join("\n"),
  15331. fragmentShader: [
  15332. "uniform samplerCube tCube;",
  15333. "uniform float tFlip;",
  15334. "varying vec3 vWorldPosition;",
  15335. "void main() {",
  15336. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  15337. "}"
  15338. ].join("\n")
  15339. }
  15340. }
  15341. };
  15342. /**
  15343. * @author zz85 / http://www.lab4games.net/zz85/blog
  15344. * @author alteredq / http://alteredqualia.com/
  15345. *
  15346. * For Text operations in three.js (See TextGeometry)
  15347. *
  15348. * It uses techniques used in:
  15349. *
  15350. * typeface.js and canvastext
  15351. * For converting fonts and rendering with javascript
  15352. * http://typeface.neocracy.org
  15353. *
  15354. * Triangulation ported from AS3
  15355. * Simple Polygon Triangulation
  15356. * http://actionsnippet.com/?p=1462
  15357. *
  15358. * A Method to triangulate shapes with holes
  15359. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15360. *
  15361. */
  15362. THREE.FontUtils = {
  15363. faces : {},
  15364. // Just for now. face[weight][style]
  15365. face : "helvetiker",
  15366. weight: "normal",
  15367. style : "normal",
  15368. size : 150,
  15369. divisions : 10,
  15370. getFace : function() {
  15371. return this.faces[ this.face ][ this.weight ][ this.style ];
  15372. },
  15373. loadFace : function( data ) {
  15374. var family = data.familyName.toLowerCase();
  15375. var ThreeFont = this;
  15376. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15377. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15378. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15379. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15380. return data;
  15381. },
  15382. drawText : function( text ) {
  15383. var characterPts = [], allPts = [];
  15384. // RenderText
  15385. var i, p,
  15386. face = this.getFace(),
  15387. scale = this.size / face.resolution,
  15388. offset = 0,
  15389. chars = String( text ).split( '' ),
  15390. length = chars.length;
  15391. var fontPaths = [];
  15392. for ( i = 0; i < length; i ++ ) {
  15393. var path = new THREE.Path();
  15394. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15395. offset += ret.offset;
  15396. fontPaths.push( ret.path );
  15397. }
  15398. // get the width
  15399. var width = offset / 2;
  15400. //
  15401. // for ( p = 0; p < allPts.length; p++ ) {
  15402. //
  15403. // allPts[ p ].x -= width;
  15404. //
  15405. // }
  15406. //var extract = this.extractPoints( allPts, characterPts );
  15407. //extract.contour = allPts;
  15408. //extract.paths = fontPaths;
  15409. //extract.offset = width;
  15410. return { paths : fontPaths, offset : width };
  15411. },
  15412. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15413. var pts = [];
  15414. var i, i2, divisions,
  15415. outline, action, length,
  15416. scaleX, scaleY,
  15417. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15418. laste,
  15419. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15420. if ( !glyph ) return;
  15421. if ( glyph.o ) {
  15422. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15423. length = outline.length;
  15424. scaleX = scale;
  15425. scaleY = scale;
  15426. for ( i = 0; i < length; ) {
  15427. action = outline[ i ++ ];
  15428. //console.log( action );
  15429. switch( action ) {
  15430. case 'm':
  15431. // Move To
  15432. x = outline[ i++ ] * scaleX + offset;
  15433. y = outline[ i++ ] * scaleY;
  15434. path.moveTo( x, y );
  15435. break;
  15436. case 'l':
  15437. // Line To
  15438. x = outline[ i++ ] * scaleX + offset;
  15439. y = outline[ i++ ] * scaleY;
  15440. path.lineTo(x,y);
  15441. break;
  15442. case 'q':
  15443. // QuadraticCurveTo
  15444. cpx = outline[ i++ ] * scaleX + offset;
  15445. cpy = outline[ i++ ] * scaleY;
  15446. cpx1 = outline[ i++ ] * scaleX + offset;
  15447. cpy1 = outline[ i++ ] * scaleY;
  15448. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15449. laste = pts[ pts.length - 1 ];
  15450. if ( laste ) {
  15451. cpx0 = laste.x;
  15452. cpy0 = laste.y;
  15453. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15454. var t = i2 / divisions;
  15455. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15456. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15457. }
  15458. }
  15459. break;
  15460. case 'b':
  15461. // Cubic Bezier Curve
  15462. cpx = outline[ i++ ] * scaleX + offset;
  15463. cpy = outline[ i++ ] * scaleY;
  15464. cpx1 = outline[ i++ ] * scaleX + offset;
  15465. cpy1 = outline[ i++ ] * -scaleY;
  15466. cpx2 = outline[ i++ ] * scaleX + offset;
  15467. cpy2 = outline[ i++ ] * -scaleY;
  15468. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15469. laste = pts[ pts.length - 1 ];
  15470. if ( laste ) {
  15471. cpx0 = laste.x;
  15472. cpy0 = laste.y;
  15473. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15474. var t = i2 / divisions;
  15475. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15476. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15477. }
  15478. }
  15479. break;
  15480. }
  15481. }
  15482. }
  15483. return { offset: glyph.ha*scale, path:path};
  15484. }
  15485. };
  15486. THREE.FontUtils.generateShapes = function( text, parameters ) {
  15487. // Parameters
  15488. parameters = parameters || {};
  15489. var size = parameters.size !== undefined ? parameters.size : 100;
  15490. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  15491. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  15492. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  15493. var style = parameters.style !== undefined ? parameters.style : "normal";
  15494. THREE.FontUtils.size = size;
  15495. THREE.FontUtils.divisions = curveSegments;
  15496. THREE.FontUtils.face = font;
  15497. THREE.FontUtils.weight = weight;
  15498. THREE.FontUtils.style = style;
  15499. // Get a Font data json object
  15500. var data = THREE.FontUtils.drawText( text );
  15501. var paths = data.paths;
  15502. var shapes = [];
  15503. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  15504. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  15505. }
  15506. return shapes;
  15507. };
  15508. /**
  15509. * This code is a quick port of code written in C++ which was submitted to
  15510. * flipcode.com by John W. Ratcliff // July 22, 2000
  15511. * See original code and more information here:
  15512. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15513. *
  15514. * ported to actionscript by Zevan Rosser
  15515. * www.actionsnippet.com
  15516. *
  15517. * ported to javascript by Joshua Koo
  15518. * http://www.lab4games.net/zz85/blog
  15519. *
  15520. */
  15521. ( function( namespace ) {
  15522. var EPSILON = 0.0000000001;
  15523. // takes in an contour array and returns
  15524. var process = function( contour, indices ) {
  15525. var n = contour.length;
  15526. if ( n < 3 ) return null;
  15527. var result = [],
  15528. verts = [],
  15529. vertIndices = [];
  15530. /* we want a counter-clockwise polygon in verts */
  15531. var u, v, w;
  15532. if ( area( contour ) > 0.0 ) {
  15533. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  15534. } else {
  15535. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  15536. }
  15537. var nv = n;
  15538. /* remove nv - 2 vertices, creating 1 triangle every time */
  15539. var count = 2 * nv; /* error detection */
  15540. for( v = nv - 1; nv > 2; ) {
  15541. /* if we loop, it is probably a non-simple polygon */
  15542. if ( ( count-- ) <= 0 ) {
  15543. //** Triangulate: ERROR - probable bad polygon!
  15544. //throw ( "Warning, unable to triangulate polygon!" );
  15545. //return null;
  15546. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15547. console.log( "Warning, unable to triangulate polygon!" );
  15548. if ( indices ) return vertIndices;
  15549. return result;
  15550. }
  15551. /* three consecutive vertices in current polygon, <u,v,w> */
  15552. u = v; if ( nv <= u ) u = 0; /* previous */
  15553. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15554. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15555. if ( snip( contour, u, v, w, nv, verts ) ) {
  15556. var a, b, c, s, t;
  15557. /* true names of the vertices */
  15558. a = verts[ u ];
  15559. b = verts[ v ];
  15560. c = verts[ w ];
  15561. /* output Triangle */
  15562. /*
  15563. result.push( contour[ a ] );
  15564. result.push( contour[ b ] );
  15565. result.push( contour[ c ] );
  15566. */
  15567. result.push( [ contour[ a ],
  15568. contour[ b ],
  15569. contour[ c ] ] );
  15570. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15571. /* remove v from the remaining polygon */
  15572. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  15573. verts[ s ] = verts[ t ];
  15574. }
  15575. nv--;
  15576. /* reset error detection counter */
  15577. count = 2 * nv;
  15578. }
  15579. }
  15580. if ( indices ) return vertIndices;
  15581. return result;
  15582. };
  15583. // calculate area of the contour polygon
  15584. var area = function ( contour ) {
  15585. var n = contour.length;
  15586. var a = 0.0;
  15587. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  15588. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15589. }
  15590. return a * 0.5;
  15591. };
  15592. // see if p is inside triangle abc
  15593. var insideTriangle = function( ax, ay,
  15594. bx, by,
  15595. cx, cy,
  15596. px, py ) {
  15597. var aX, aY, bX, bY;
  15598. var cX, cY, apx, apy;
  15599. var bpx, bpy, cpx, cpy;
  15600. var cCROSSap, bCROSScp, aCROSSbp;
  15601. aX = cx - bx; aY = cy - by;
  15602. bX = ax - cx; bY = ay - cy;
  15603. cX = bx - ax; cY = by - ay;
  15604. apx= px -ax; apy= py - ay;
  15605. bpx= px - bx; bpy= py - by;
  15606. cpx= px - cx; cpy= py - cy;
  15607. aCROSSbp = aX*bpy - aY*bpx;
  15608. cCROSSap = cX*apy - cY*apx;
  15609. bCROSScp = bX*cpy - bY*cpx;
  15610. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  15611. };
  15612. var snip = function ( contour, u, v, w, n, verts ) {
  15613. var p;
  15614. var ax, ay, bx, by;
  15615. var cx, cy, px, py;
  15616. ax = contour[ verts[ u ] ].x;
  15617. ay = contour[ verts[ u ] ].y;
  15618. bx = contour[ verts[ v ] ].x;
  15619. by = contour[ verts[ v ] ].y;
  15620. cx = contour[ verts[ w ] ].x;
  15621. cy = contour[ verts[ w ] ].y;
  15622. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  15623. for ( p = 0; p < n; p++ ) {
  15624. if( (p == u) || (p == v) || (p == w) ) continue;
  15625. px = contour[ verts[ p ] ].x
  15626. py = contour[ verts[ p ] ].y
  15627. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  15628. }
  15629. return true;
  15630. };
  15631. namespace.Triangulate = process;
  15632. namespace.Triangulate.area = area;
  15633. return namespace;
  15634. })(THREE.FontUtils);
  15635. // To use the typeface.js face files, hook up the API
  15636. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  15637. * @author zz85 / http://www.lab4games.net/zz85/blog
  15638. * Extensible curve object
  15639. *
  15640. * Some common of Curve methods
  15641. * .getPoint(t), getTangent(t)
  15642. * .getPointAt(u), getTagentAt(u)
  15643. * .getPoints(), .getSpacedPoints()
  15644. * .getLength()
  15645. * .updateArcLengths()
  15646. *
  15647. * This file contains following classes:
  15648. *
  15649. * -- 2d classes --
  15650. * THREE.Curve
  15651. * THREE.LineCurve
  15652. * THREE.QuadraticBezierCurve
  15653. * THREE.CubicBezierCurve
  15654. * THREE.SplineCurve
  15655. * THREE.ArcCurve
  15656. * THREE.EllipseCurve
  15657. *
  15658. * -- 3d classes --
  15659. * THREE.LineCurve3
  15660. * THREE.QuadraticBezierCurve3
  15661. * THREE.CubicBezierCurve3
  15662. * THREE.SplineCurve3
  15663. * THREE.ClosedSplineCurve3
  15664. *
  15665. * A series of curves can be represented as a THREE.CurvePath
  15666. *
  15667. **/
  15668. /**************************************************************
  15669. * Abstract Curve base class
  15670. **************************************************************/
  15671. THREE.Curve = function () {
  15672. };
  15673. // Virtual base class method to overwrite and implement in subclasses
  15674. // - t [0 .. 1]
  15675. THREE.Curve.prototype.getPoint = function ( t ) {
  15676. console.log( "Warning, getPoint() not implemented!" );
  15677. return null;
  15678. };
  15679. // Get point at relative position in curve according to arc length
  15680. // - u [0 .. 1]
  15681. THREE.Curve.prototype.getPointAt = function ( u ) {
  15682. var t = this.getUtoTmapping( u );
  15683. return this.getPoint( t );
  15684. };
  15685. // Get sequence of points using getPoint( t )
  15686. THREE.Curve.prototype.getPoints = function ( divisions ) {
  15687. if ( !divisions ) divisions = 5;
  15688. var d, pts = [];
  15689. for ( d = 0; d <= divisions; d ++ ) {
  15690. pts.push( this.getPoint( d / divisions ) );
  15691. }
  15692. return pts;
  15693. };
  15694. // Get sequence of points using getPointAt( u )
  15695. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  15696. if ( !divisions ) divisions = 5;
  15697. var d, pts = [];
  15698. for ( d = 0; d <= divisions; d ++ ) {
  15699. pts.push( this.getPointAt( d / divisions ) );
  15700. }
  15701. return pts;
  15702. };
  15703. // Get total curve arc length
  15704. THREE.Curve.prototype.getLength = function () {
  15705. var lengths = this.getLengths();
  15706. return lengths[ lengths.length - 1 ];
  15707. };
  15708. // Get list of cumulative segment lengths
  15709. THREE.Curve.prototype.getLengths = function ( divisions ) {
  15710. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  15711. if ( this.cacheArcLengths
  15712. && ( this.cacheArcLengths.length == divisions + 1 )
  15713. && !this.needsUpdate) {
  15714. //console.log( "cached", this.cacheArcLengths );
  15715. return this.cacheArcLengths;
  15716. }
  15717. this.needsUpdate = false;
  15718. var cache = [];
  15719. var current, last = this.getPoint( 0 );
  15720. var p, sum = 0;
  15721. cache.push( 0 );
  15722. for ( p = 1; p <= divisions; p ++ ) {
  15723. current = this.getPoint ( p / divisions );
  15724. sum += current.distanceTo( last );
  15725. cache.push( sum );
  15726. last = current;
  15727. }
  15728. this.cacheArcLengths = cache;
  15729. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  15730. };
  15731. THREE.Curve.prototype.updateArcLengths = function() {
  15732. this.needsUpdate = true;
  15733. this.getLengths();
  15734. };
  15735. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  15736. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  15737. var arcLengths = this.getLengths();
  15738. var i = 0, il = arcLengths.length;
  15739. var targetArcLength; // The targeted u distance value to get
  15740. if ( distance ) {
  15741. targetArcLength = distance;
  15742. } else {
  15743. targetArcLength = u * arcLengths[ il - 1 ];
  15744. }
  15745. //var time = Date.now();
  15746. // binary search for the index with largest value smaller than target u distance
  15747. var low = 0, high = il - 1, comparison;
  15748. while ( low <= high ) {
  15749. 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
  15750. comparison = arcLengths[ i ] - targetArcLength;
  15751. if ( comparison < 0 ) {
  15752. low = i + 1;
  15753. continue;
  15754. } else if ( comparison > 0 ) {
  15755. high = i - 1;
  15756. continue;
  15757. } else {
  15758. high = i;
  15759. break;
  15760. // DONE
  15761. }
  15762. }
  15763. i = high;
  15764. //console.log('b' , i, low, high, Date.now()- time);
  15765. if ( arcLengths[ i ] == targetArcLength ) {
  15766. var t = i / ( il - 1 );
  15767. return t;
  15768. }
  15769. // we could get finer grain at lengths, or use simple interpolatation between two points
  15770. var lengthBefore = arcLengths[ i ];
  15771. var lengthAfter = arcLengths[ i + 1 ];
  15772. var segmentLength = lengthAfter - lengthBefore;
  15773. // determine where we are between the 'before' and 'after' points
  15774. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  15775. // add that fractional amount to t
  15776. var t = ( i + segmentFraction ) / ( il -1 );
  15777. return t;
  15778. };
  15779. // In 2D space, there are actually 2 normal vectors,
  15780. // and in 3D space, infinte
  15781. // TODO this should be depreciated.
  15782. THREE.Curve.prototype.getNormalVector = function( t ) {
  15783. var vec = this.getTangent( t );
  15784. return new THREE.Vector2( -vec.y , vec.x );
  15785. };
  15786. // Returns a unit vector tangent at t
  15787. // In case any sub curve does not implement its tangent / normal finding,
  15788. // we get 2 points with a small delta and find a gradient of the 2 points
  15789. // which seems to make a reasonable approximation
  15790. THREE.Curve.prototype.getTangent = function( t ) {
  15791. var delta = 0.0001;
  15792. var t1 = t - delta;
  15793. var t2 = t + delta;
  15794. // Capping in case of danger
  15795. if ( t1 < 0 ) t1 = 0;
  15796. if ( t2 > 1 ) t2 = 1;
  15797. var pt1 = this.getPoint( t1 );
  15798. var pt2 = this.getPoint( t2 );
  15799. var vec = pt2.clone().subSelf(pt1);
  15800. return vec.normalize();
  15801. };
  15802. THREE.Curve.prototype.getTangentAt = function ( u ) {
  15803. var t = this.getUtoTmapping( u );
  15804. return this.getTangent( t );
  15805. };
  15806. /**************************************************************
  15807. * Line
  15808. **************************************************************/
  15809. THREE.LineCurve = function ( v1, v2 ) {
  15810. this.v1 = v1;
  15811. this.v2 = v2;
  15812. };
  15813. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  15814. THREE.LineCurve.prototype.getPoint = function ( t ) {
  15815. var point = this.v2.clone().subSelf(this.v1);
  15816. point.multiplyScalar( t ).addSelf( this.v1 );
  15817. return point;
  15818. };
  15819. // Line curve is linear, so we can overwrite default getPointAt
  15820. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  15821. return this.getPoint( u );
  15822. };
  15823. THREE.LineCurve.prototype.getTangent = function( t ) {
  15824. var tangent = this.v2.clone().subSelf(this.v1);
  15825. return tangent.normalize();
  15826. };
  15827. /**************************************************************
  15828. * Quadratic Bezier curve
  15829. **************************************************************/
  15830. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  15831. this.v0 = v0;
  15832. this.v1 = v1;
  15833. this.v2 = v2;
  15834. };
  15835. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15836. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  15837. var tx, ty;
  15838. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15839. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15840. return new THREE.Vector2( tx, ty );
  15841. };
  15842. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  15843. var tx, ty;
  15844. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  15845. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  15846. // returns unit vector
  15847. var tangent = new THREE.Vector2( tx, ty );
  15848. tangent.normalize();
  15849. return tangent;
  15850. };
  15851. /**************************************************************
  15852. * Cubic Bezier curve
  15853. **************************************************************/
  15854. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  15855. this.v0 = v0;
  15856. this.v1 = v1;
  15857. this.v2 = v2;
  15858. this.v3 = v3;
  15859. };
  15860. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15861. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  15862. var tx, ty;
  15863. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15864. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15865. return new THREE.Vector2( tx, ty );
  15866. };
  15867. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  15868. var tx, ty;
  15869. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15870. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15871. var tangent = new THREE.Vector2( tx, ty );
  15872. tangent.normalize();
  15873. return tangent;
  15874. };
  15875. /**************************************************************
  15876. * Spline curve
  15877. **************************************************************/
  15878. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  15879. this.points = (points == undefined) ? [] : points;
  15880. };
  15881. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  15882. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  15883. var v = new THREE.Vector2();
  15884. var c = [];
  15885. var points = this.points, point, intPoint, weight;
  15886. point = ( points.length - 1 ) * t;
  15887. intPoint = Math.floor( point );
  15888. weight = point - intPoint;
  15889. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15890. c[ 1 ] = intPoint;
  15891. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  15892. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  15893. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15894. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15895. return v;
  15896. };
  15897. /**************************************************************
  15898. * Ellipse curve
  15899. **************************************************************/
  15900. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  15901. aStartAngle, aEndAngle,
  15902. aClockwise ) {
  15903. this.aX = aX;
  15904. this.aY = aY;
  15905. this.xRadius = xRadius;
  15906. this.yRadius = yRadius;
  15907. this.aStartAngle = aStartAngle;
  15908. this.aEndAngle = aEndAngle;
  15909. this.aClockwise = aClockwise;
  15910. };
  15911. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  15912. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  15913. var deltaAngle = this.aEndAngle - this.aStartAngle;
  15914. if ( !this.aClockwise ) {
  15915. t = 1 - t;
  15916. }
  15917. var angle = this.aStartAngle + t * deltaAngle;
  15918. var tx = this.aX + this.xRadius * Math.cos( angle );
  15919. var ty = this.aY + this.yRadius * Math.sin( angle );
  15920. return new THREE.Vector2( tx, ty );
  15921. };
  15922. /**************************************************************
  15923. * Arc curve
  15924. **************************************************************/
  15925. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  15926. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  15927. };
  15928. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  15929. /**************************************************************
  15930. * Utils
  15931. **************************************************************/
  15932. THREE.Curve.Utils = {
  15933. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  15934. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  15935. },
  15936. // Puay Bing, thanks for helping with this derivative!
  15937. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  15938. return -3 * p0 * (1 - t) * (1 - t) +
  15939. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  15940. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  15941. 3 * t * t * p3;
  15942. },
  15943. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  15944. // To check if my formulas are correct
  15945. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  15946. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  15947. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  15948. var h11 = 3 * t * t - 2 * t; // t3 − t2
  15949. return h00 + h10 + h01 + h11;
  15950. },
  15951. // Catmull-Rom
  15952. interpolate: function( p0, p1, p2, p3, t ) {
  15953. var v0 = ( p2 - p0 ) * 0.5;
  15954. var v1 = ( p3 - p1 ) * 0.5;
  15955. var t2 = t * t;
  15956. var t3 = t * t2;
  15957. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  15958. }
  15959. };
  15960. // TODO: Transformation for Curves?
  15961. /**************************************************************
  15962. * 3D Curves
  15963. **************************************************************/
  15964. // A Factory method for creating new curve subclasses
  15965. THREE.Curve.create = function ( constructor, getPointFunc ) {
  15966. constructor.prototype = Object.create( THREE.Curve.prototype );
  15967. constructor.prototype.getPoint = getPointFunc;
  15968. return constructor;
  15969. };
  15970. /**************************************************************
  15971. * Line3D
  15972. **************************************************************/
  15973. THREE.LineCurve3 = THREE.Curve.create(
  15974. function ( v1, v2 ) {
  15975. this.v1 = v1;
  15976. this.v2 = v2;
  15977. },
  15978. function ( t ) {
  15979. var r = new THREE.Vector3();
  15980. r.sub( this.v2, this.v1 ); // diff
  15981. r.multiplyScalar( t );
  15982. r.addSelf( this.v1 );
  15983. return r;
  15984. }
  15985. );
  15986. /**************************************************************
  15987. * Quadratic Bezier 3D curve
  15988. **************************************************************/
  15989. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  15990. function ( v0, v1, v2 ) {
  15991. this.v0 = v0;
  15992. this.v1 = v1;
  15993. this.v2 = v2;
  15994. },
  15995. function ( t ) {
  15996. var tx, ty, tz;
  15997. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15998. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15999. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16000. return new THREE.Vector3( tx, ty, tz );
  16001. }
  16002. );
  16003. /**************************************************************
  16004. * Cubic Bezier 3D curve
  16005. **************************************************************/
  16006. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16007. function ( v0, v1, v2, v3 ) {
  16008. this.v0 = v0;
  16009. this.v1 = v1;
  16010. this.v2 = v2;
  16011. this.v3 = v3;
  16012. },
  16013. function ( t ) {
  16014. var tx, ty, tz;
  16015. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16016. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16017. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16018. return new THREE.Vector3( tx, ty, tz );
  16019. }
  16020. );
  16021. /**************************************************************
  16022. * Spline 3D curve
  16023. **************************************************************/
  16024. THREE.SplineCurve3 = THREE.Curve.create(
  16025. function ( points /* array of Vector3 */) {
  16026. this.points = (points == undefined) ? [] : points;
  16027. },
  16028. function ( t ) {
  16029. var v = new THREE.Vector3();
  16030. var c = [];
  16031. var points = this.points, point, intPoint, weight;
  16032. point = ( points.length - 1 ) * t;
  16033. intPoint = Math.floor( point );
  16034. weight = point - intPoint;
  16035. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16036. c[ 1 ] = intPoint;
  16037. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16038. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16039. var pt0 = points[ c[0] ],
  16040. pt1 = points[ c[1] ],
  16041. pt2 = points[ c[2] ],
  16042. pt3 = points[ c[3] ];
  16043. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16044. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16045. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16046. return v;
  16047. }
  16048. );
  16049. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16050. // var v = new THREE.Vector3();
  16051. // var c = [];
  16052. // var points = this.points, point, intPoint, weight;
  16053. // point = ( points.length - 1 ) * t;
  16054. // intPoint = Math.floor( point );
  16055. // weight = point - intPoint;
  16056. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16057. // c[ 1 ] = intPoint;
  16058. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16059. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16060. // var pt0 = points[ c[0] ],
  16061. // pt1 = points[ c[1] ],
  16062. // pt2 = points[ c[2] ],
  16063. // pt3 = points[ c[3] ];
  16064. // // t = weight;
  16065. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16066. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16067. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16068. // return v;
  16069. // }
  16070. /**************************************************************
  16071. * Closed Spline 3D curve
  16072. **************************************************************/
  16073. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16074. function ( points /* array of Vector3 */) {
  16075. this.points = (points == undefined) ? [] : points;
  16076. },
  16077. function ( t ) {
  16078. var v = new THREE.Vector3();
  16079. var c = [];
  16080. var points = this.points, point, intPoint, weight;
  16081. point = ( points.length - 0 ) * t;
  16082. // This needs to be from 0-length +1
  16083. intPoint = Math.floor( point );
  16084. weight = point - intPoint;
  16085. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16086. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16087. c[ 1 ] = ( intPoint ) % points.length;
  16088. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16089. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16090. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16091. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16092. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16093. return v;
  16094. }
  16095. );
  16096. /**
  16097. * @author zz85 / http://www.lab4games.net/zz85/blog
  16098. *
  16099. **/
  16100. /**************************************************************
  16101. * Curved Path - a curve path is simply a array of connected
  16102. * curves, but retains the api of a curve
  16103. **************************************************************/
  16104. THREE.CurvePath = function () {
  16105. this.curves = [];
  16106. this.bends = [];
  16107. this.autoClose = false; // Automatically closes the path
  16108. };
  16109. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16110. THREE.CurvePath.prototype.add = function ( curve ) {
  16111. this.curves.push( curve );
  16112. };
  16113. THREE.CurvePath.prototype.checkConnection = function() {
  16114. // TODO
  16115. // If the ending of curve is not connected to the starting
  16116. // or the next curve, then, this is not a real path
  16117. };
  16118. THREE.CurvePath.prototype.closePath = function() {
  16119. // TODO Test
  16120. // and verify for vector3 (needs to implement equals)
  16121. // Add a line curve if start and end of lines are not connected
  16122. var startPoint = this.curves[0].getPoint(0);
  16123. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16124. if (!startPoint.equals(endPoint)) {
  16125. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16126. }
  16127. };
  16128. // To get accurate point with reference to
  16129. // entire path distance at time t,
  16130. // following has to be done:
  16131. // 1. Length of each sub path have to be known
  16132. // 2. Locate and identify type of curve
  16133. // 3. Get t for the curve
  16134. // 4. Return curve.getPointAt(t')
  16135. THREE.CurvePath.prototype.getPoint = function( t ) {
  16136. var d = t * this.getLength();
  16137. var curveLengths = this.getCurveLengths();
  16138. var i = 0, diff, curve;
  16139. // To think about boundaries points.
  16140. while ( i < curveLengths.length ) {
  16141. if ( curveLengths[ i ] >= d ) {
  16142. diff = curveLengths[ i ] - d;
  16143. curve = this.curves[ i ];
  16144. var u = 1 - diff / curve.getLength();
  16145. return curve.getPointAt( u );
  16146. break;
  16147. }
  16148. i ++;
  16149. }
  16150. return null;
  16151. // loop where sum != 0, sum > d , sum+1 <d
  16152. };
  16153. /*
  16154. THREE.CurvePath.prototype.getTangent = function( t ) {
  16155. };*/
  16156. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16157. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16158. // getPoint() depends on getLength
  16159. THREE.CurvePath.prototype.getLength = function() {
  16160. var lens = this.getCurveLengths();
  16161. return lens[ lens.length - 1 ];
  16162. };
  16163. // Compute lengths and cache them
  16164. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16165. THREE.CurvePath.prototype.getCurveLengths = function() {
  16166. // We use cache values if curves and cache array are same length
  16167. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16168. return this.cacheLengths;
  16169. };
  16170. // Get length of subsurve
  16171. // Push sums into cached array
  16172. var lengths = [], sums = 0;
  16173. var i, il = this.curves.length;
  16174. for ( i = 0; i < il; i ++ ) {
  16175. sums += this.curves[ i ].getLength();
  16176. lengths.push( sums );
  16177. }
  16178. this.cacheLengths = lengths;
  16179. return lengths;
  16180. };
  16181. // Returns min and max coordinates, as well as centroid
  16182. THREE.CurvePath.prototype.getBoundingBox = function () {
  16183. var points = this.getPoints();
  16184. var maxX, maxY, maxZ;
  16185. var minX, minY, minZ;
  16186. maxX = maxY = Number.NEGATIVE_INFINITY;
  16187. minX = minY = Number.POSITIVE_INFINITY;
  16188. var p, i, il, sum;
  16189. var v3 = points[0] instanceof THREE.Vector3;
  16190. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16191. for ( i = 0, il = points.length; i < il; i ++ ) {
  16192. p = points[ i ];
  16193. if ( p.x > maxX ) maxX = p.x;
  16194. else if ( p.x < minX ) minX = p.x;
  16195. if ( p.y > maxY ) maxY = p.y;
  16196. else if ( p.y < minY ) minY = p.y;
  16197. if (v3) {
  16198. if ( p.z > maxZ ) maxZ = p.z;
  16199. else if ( p.z < minZ ) minZ = p.z;
  16200. }
  16201. sum.addSelf( p );
  16202. }
  16203. var ret = {
  16204. minX: minX,
  16205. minY: minY,
  16206. maxX: maxX,
  16207. maxY: maxY,
  16208. centroid: sum.divideScalar( il )
  16209. };
  16210. if (v3) {
  16211. ret.maxZ = maxZ;
  16212. ret.minZ = minZ;
  16213. }
  16214. return ret;
  16215. };
  16216. /**************************************************************
  16217. * Create Geometries Helpers
  16218. **************************************************************/
  16219. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16220. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16221. var pts = this.getPoints( divisions, true );
  16222. return this.createGeometry( pts );
  16223. };
  16224. // Generate geometry from equidistance sampling along the path
  16225. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16226. var pts = this.getSpacedPoints( divisions, true );
  16227. return this.createGeometry( pts );
  16228. };
  16229. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16230. var geometry = new THREE.Geometry();
  16231. for ( var i = 0; i < points.length; i ++ ) {
  16232. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16233. }
  16234. return geometry;
  16235. };
  16236. /**************************************************************
  16237. * Bend / Wrap Helper Methods
  16238. **************************************************************/
  16239. // Wrap path / Bend modifiers?
  16240. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16241. this.bends.push( bendpath );
  16242. };
  16243. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16244. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16245. var i, il;
  16246. if ( !bends ) {
  16247. bends = this.bends;
  16248. }
  16249. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16250. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16251. }
  16252. return oldPts;
  16253. };
  16254. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16255. var oldPts = this.getSpacedPoints( segments );
  16256. var i, il;
  16257. if ( !bends ) {
  16258. bends = this.bends;
  16259. }
  16260. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16261. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16262. }
  16263. return oldPts;
  16264. };
  16265. // This returns getPoints() bend/wrapped around the contour of a path.
  16266. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16267. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16268. var bounds = this.getBoundingBox();
  16269. var i, il, p, oldX, oldY, xNorm;
  16270. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16271. p = oldPts[ i ];
  16272. oldX = p.x;
  16273. oldY = p.y;
  16274. xNorm = oldX / bounds.maxX;
  16275. // If using actual distance, for length > path, requires line extrusions
  16276. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16277. xNorm = path.getUtoTmapping( xNorm, oldX );
  16278. // check for out of bounds?
  16279. var pathPt = path.getPoint( xNorm );
  16280. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16281. p.x = pathPt.x + normal.x;
  16282. p.y = pathPt.y + normal.y;
  16283. }
  16284. return oldPts;
  16285. };
  16286. /**
  16287. * @author alteredq / http://alteredqualia.com/
  16288. */
  16289. THREE.Gyroscope = function () {
  16290. THREE.Object3D.call( this );
  16291. };
  16292. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16293. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16294. this.matrixAutoUpdate && this.updateMatrix();
  16295. // update matrixWorld
  16296. if ( this.matrixWorldNeedsUpdate || force ) {
  16297. if ( this.parent ) {
  16298. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  16299. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16300. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16301. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16302. } else {
  16303. this.matrixWorld.copy( this.matrix );
  16304. }
  16305. this.matrixWorldNeedsUpdate = false;
  16306. force = true;
  16307. }
  16308. // update children
  16309. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16310. this.children[ i ].updateMatrixWorld( force );
  16311. }
  16312. };
  16313. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16314. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16315. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16316. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16317. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16318. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16319. /**
  16320. * @author zz85 / http://www.lab4games.net/zz85/blog
  16321. * Creates free form 2d path using series of points, lines or curves.
  16322. *
  16323. **/
  16324. THREE.Path = function ( points ) {
  16325. THREE.CurvePath.call(this);
  16326. this.actions = [];
  16327. if ( points ) {
  16328. this.fromPoints( points );
  16329. }
  16330. };
  16331. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16332. THREE.PathActions = {
  16333. MOVE_TO: 'moveTo',
  16334. LINE_TO: 'lineTo',
  16335. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16336. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16337. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16338. ARC: 'arc', // Circle
  16339. ELLIPSE: 'ellipse'
  16340. };
  16341. // TODO Clean up PATH API
  16342. // Create path using straight lines to connect all points
  16343. // - vectors: array of Vector2
  16344. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16345. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16346. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16347. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16348. };
  16349. };
  16350. // startPath() endPath()?
  16351. THREE.Path.prototype.moveTo = function ( x, y ) {
  16352. var args = Array.prototype.slice.call( arguments );
  16353. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16354. };
  16355. THREE.Path.prototype.lineTo = function ( x, y ) {
  16356. var args = Array.prototype.slice.call( arguments );
  16357. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16358. var x0 = lastargs[ lastargs.length - 2 ];
  16359. var y0 = lastargs[ lastargs.length - 1 ];
  16360. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16361. this.curves.push( curve );
  16362. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16363. };
  16364. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16365. var args = Array.prototype.slice.call( arguments );
  16366. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16367. var x0 = lastargs[ lastargs.length - 2 ];
  16368. var y0 = lastargs[ lastargs.length - 1 ];
  16369. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16370. new THREE.Vector2( aCPx, aCPy ),
  16371. new THREE.Vector2( aX, aY ) );
  16372. this.curves.push( curve );
  16373. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16374. };
  16375. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16376. aCP2x, aCP2y,
  16377. aX, aY ) {
  16378. var args = Array.prototype.slice.call( arguments );
  16379. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16380. var x0 = lastargs[ lastargs.length - 2 ];
  16381. var y0 = lastargs[ lastargs.length - 1 ];
  16382. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16383. new THREE.Vector2( aCP1x, aCP1y ),
  16384. new THREE.Vector2( aCP2x, aCP2y ),
  16385. new THREE.Vector2( aX, aY ) );
  16386. this.curves.push( curve );
  16387. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16388. };
  16389. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16390. var args = Array.prototype.slice.call( arguments );
  16391. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16392. var x0 = lastargs[ lastargs.length - 2 ];
  16393. var y0 = lastargs[ lastargs.length - 1 ];
  16394. //---
  16395. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16396. Array.prototype.push.apply( npts, pts );
  16397. var curve = new THREE.SplineCurve( npts );
  16398. this.curves.push( curve );
  16399. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16400. };
  16401. // FUTURE: Change the API or follow canvas API?
  16402. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16403. aStartAngle, aEndAngle, aClockwise ) {
  16404. var lastargs = this.actions[ this.actions.length - 1].args;
  16405. var x0 = lastargs[ lastargs.length - 2 ];
  16406. var y0 = lastargs[ lastargs.length - 1 ];
  16407. this.absarc(aX + x0, aY + y0, aRadius,
  16408. aStartAngle, aEndAngle, aClockwise );
  16409. };
  16410. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16411. aStartAngle, aEndAngle, aClockwise ) {
  16412. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16413. };
  16414. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16415. aStartAngle, aEndAngle, aClockwise ) {
  16416. var lastargs = this.actions[ this.actions.length - 1].args;
  16417. var x0 = lastargs[ lastargs.length - 2 ];
  16418. var y0 = lastargs[ lastargs.length - 1 ];
  16419. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16420. aStartAngle, aEndAngle, aClockwise );
  16421. };
  16422. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16423. aStartAngle, aEndAngle, aClockwise ) {
  16424. var args = Array.prototype.slice.call( arguments );
  16425. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16426. aStartAngle, aEndAngle, aClockwise );
  16427. this.curves.push( curve );
  16428. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  16429. args.push(lastPoint.x);
  16430. args.push(lastPoint.y);
  16431. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16432. };
  16433. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16434. if ( ! divisions ) divisions = 40;
  16435. var points = [];
  16436. for ( var i = 0; i < divisions; i ++ ) {
  16437. points.push( this.getPoint( i / divisions ) );
  16438. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16439. }
  16440. // if ( closedPath ) {
  16441. //
  16442. // points.push( points[ 0 ] );
  16443. //
  16444. // }
  16445. return points;
  16446. };
  16447. /* Return an array of vectors based on contour of the path */
  16448. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16449. if (this.useSpacedPoints) {
  16450. console.log('tata');
  16451. return this.getSpacedPoints( divisions, closedPath );
  16452. }
  16453. divisions = divisions || 12;
  16454. var points = [];
  16455. var i, il, item, action, args;
  16456. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16457. laste, j,
  16458. t, tx, ty;
  16459. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16460. item = this.actions[ i ];
  16461. action = item.action;
  16462. args = item.args;
  16463. switch( action ) {
  16464. case THREE.PathActions.MOVE_TO:
  16465. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16466. break;
  16467. case THREE.PathActions.LINE_TO:
  16468. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16469. break;
  16470. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16471. cpx = args[ 2 ];
  16472. cpy = args[ 3 ];
  16473. cpx1 = args[ 0 ];
  16474. cpy1 = args[ 1 ];
  16475. if ( points.length > 0 ) {
  16476. laste = points[ points.length - 1 ];
  16477. cpx0 = laste.x;
  16478. cpy0 = laste.y;
  16479. } else {
  16480. laste = this.actions[ i - 1 ].args;
  16481. cpx0 = laste[ laste.length - 2 ];
  16482. cpy0 = laste[ laste.length - 1 ];
  16483. }
  16484. for ( j = 1; j <= divisions; j ++ ) {
  16485. t = j / divisions;
  16486. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16487. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16488. points.push( new THREE.Vector2( tx, ty ) );
  16489. }
  16490. break;
  16491. case THREE.PathActions.BEZIER_CURVE_TO:
  16492. cpx = args[ 4 ];
  16493. cpy = args[ 5 ];
  16494. cpx1 = args[ 0 ];
  16495. cpy1 = args[ 1 ];
  16496. cpx2 = args[ 2 ];
  16497. cpy2 = args[ 3 ];
  16498. if ( points.length > 0 ) {
  16499. laste = points[ points.length - 1 ];
  16500. cpx0 = laste.x;
  16501. cpy0 = laste.y;
  16502. } else {
  16503. laste = this.actions[ i - 1 ].args;
  16504. cpx0 = laste[ laste.length - 2 ];
  16505. cpy0 = laste[ laste.length - 1 ];
  16506. }
  16507. for ( j = 1; j <= divisions; j ++ ) {
  16508. t = j / divisions;
  16509. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16510. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16511. points.push( new THREE.Vector2( tx, ty ) );
  16512. }
  16513. break;
  16514. case THREE.PathActions.CSPLINE_THRU:
  16515. laste = this.actions[ i - 1 ].args;
  16516. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16517. var spts = [ last ];
  16518. var n = divisions * args[ 0 ].length;
  16519. spts = spts.concat( args[ 0 ] );
  16520. var spline = new THREE.SplineCurve( spts );
  16521. for ( j = 1; j <= n; j ++ ) {
  16522. points.push( spline.getPointAt( j / n ) ) ;
  16523. }
  16524. break;
  16525. case THREE.PathActions.ARC:
  16526. var aX = args[ 0 ], aY = args[ 1 ],
  16527. aRadius = args[ 2 ],
  16528. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16529. aClockwise = !!args[ 5 ];
  16530. var deltaAngle = aEndAngle - aStartAngle;
  16531. var angle;
  16532. var tdivisions = divisions * 2;
  16533. for ( j = 1; j <= tdivisions; j ++ ) {
  16534. t = j / tdivisions;
  16535. if ( ! aClockwise ) {
  16536. t = 1 - t;
  16537. }
  16538. angle = aStartAngle + t * deltaAngle;
  16539. tx = aX + aRadius * Math.cos( angle );
  16540. ty = aY + aRadius * Math.sin( angle );
  16541. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16542. points.push( new THREE.Vector2( tx, ty ) );
  16543. }
  16544. //console.log(points);
  16545. break;
  16546. case THREE.PathActions.ELLIPSE:
  16547. var aX = args[ 0 ], aY = args[ 1 ],
  16548. xRadius = args[ 2 ],
  16549. yRadius = args[ 3 ],
  16550. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16551. aClockwise = !!args[ 6 ];
  16552. var deltaAngle = aEndAngle - aStartAngle;
  16553. var angle;
  16554. var tdivisions = divisions * 2;
  16555. for ( j = 1; j <= tdivisions; j ++ ) {
  16556. t = j / tdivisions;
  16557. if ( ! aClockwise ) {
  16558. t = 1 - t;
  16559. }
  16560. angle = aStartAngle + t * deltaAngle;
  16561. tx = aX + xRadius * Math.cos( angle );
  16562. ty = aY + yRadius * Math.sin( angle );
  16563. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16564. points.push( new THREE.Vector2( tx, ty ) );
  16565. }
  16566. //console.log(points);
  16567. break;
  16568. } // end switch
  16569. }
  16570. // Normalize to remove the closing point by default.
  16571. var lastPoint = points[ points.length - 1];
  16572. var EPSILON = 0.0000000001;
  16573. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  16574. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  16575. points.splice( points.length - 1, 1);
  16576. if ( closedPath ) {
  16577. points.push( points[ 0 ] );
  16578. }
  16579. return points;
  16580. };
  16581. // Breaks path into shapes
  16582. THREE.Path.prototype.toShapes = function() {
  16583. var i, il, item, action, args;
  16584. var subPaths = [], lastPath = new THREE.Path();
  16585. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16586. item = this.actions[ i ];
  16587. args = item.args;
  16588. action = item.action;
  16589. if ( action == THREE.PathActions.MOVE_TO ) {
  16590. if ( lastPath.actions.length != 0 ) {
  16591. subPaths.push( lastPath );
  16592. lastPath = new THREE.Path();
  16593. }
  16594. }
  16595. lastPath[ action ].apply( lastPath, args );
  16596. }
  16597. if ( lastPath.actions.length != 0 ) {
  16598. subPaths.push( lastPath );
  16599. }
  16600. // console.log(subPaths);
  16601. if ( subPaths.length == 0 ) return [];
  16602. var tmpPath, tmpShape, shapes = [];
  16603. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  16604. // console.log("Holes first", holesFirst);
  16605. if ( subPaths.length == 1) {
  16606. tmpPath = subPaths[0];
  16607. tmpShape = new THREE.Shape();
  16608. tmpShape.actions = tmpPath.actions;
  16609. tmpShape.curves = tmpPath.curves;
  16610. shapes.push( tmpShape );
  16611. return shapes;
  16612. };
  16613. if ( holesFirst ) {
  16614. tmpShape = new THREE.Shape();
  16615. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16616. tmpPath = subPaths[ i ];
  16617. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16618. tmpShape.actions = tmpPath.actions;
  16619. tmpShape.curves = tmpPath.curves;
  16620. shapes.push( tmpShape );
  16621. tmpShape = new THREE.Shape();
  16622. //console.log('cw', i);
  16623. } else {
  16624. tmpShape.holes.push( tmpPath );
  16625. //console.log('ccw', i);
  16626. }
  16627. }
  16628. } else {
  16629. // Shapes first
  16630. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16631. tmpPath = subPaths[ i ];
  16632. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16633. if ( tmpShape ) shapes.push( tmpShape );
  16634. tmpShape = new THREE.Shape();
  16635. tmpShape.actions = tmpPath.actions;
  16636. tmpShape.curves = tmpPath.curves;
  16637. } else {
  16638. tmpShape.holes.push( tmpPath );
  16639. }
  16640. }
  16641. shapes.push( tmpShape );
  16642. }
  16643. //console.log("shape", shapes);
  16644. return shapes;
  16645. };
  16646. /**
  16647. * @author zz85 / http://www.lab4games.net/zz85/blog
  16648. * Defines a 2d shape plane using paths.
  16649. **/
  16650. // STEP 1 Create a path.
  16651. // STEP 2 Turn path into shape.
  16652. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  16653. // STEP 3a - Extract points from each shape, turn to vertices
  16654. // STEP 3b - Triangulate each shape, add faces.
  16655. THREE.Shape = function ( ) {
  16656. THREE.Path.apply( this, arguments );
  16657. this.holes = [];
  16658. };
  16659. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  16660. // Convenience method to return ExtrudeGeometry
  16661. THREE.Shape.prototype.extrude = function ( options ) {
  16662. var extruded = new THREE.ExtrudeGeometry( this, options );
  16663. return extruded;
  16664. };
  16665. // Convenience method to return ShapeGeometry
  16666. THREE.Shape.prototype.makeGeometry = function ( options ) {
  16667. var geometry = new THREE.ShapeGeometry( this, options );
  16668. return geometry;
  16669. };
  16670. // Get points of holes
  16671. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  16672. var i, il = this.holes.length, holesPts = [];
  16673. for ( i = 0; i < il; i ++ ) {
  16674. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  16675. }
  16676. return holesPts;
  16677. };
  16678. // Get points of holes (spaced by regular distance)
  16679. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  16680. var i, il = this.holes.length, holesPts = [];
  16681. for ( i = 0; i < il; i ++ ) {
  16682. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  16683. }
  16684. return holesPts;
  16685. };
  16686. // Get points of shape and holes (keypoints based on segments parameter)
  16687. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  16688. return {
  16689. shape: this.getTransformedPoints( divisions ),
  16690. holes: this.getPointsHoles( divisions )
  16691. };
  16692. };
  16693. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  16694. if (this.useSpacedPoints) {
  16695. return this.extractAllSpacedPoints(divisions);
  16696. }
  16697. return this.extractAllPoints(divisions);
  16698. };
  16699. //
  16700. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  16701. //
  16702. // return {
  16703. //
  16704. // shape: this.transform( bend, divisions ),
  16705. // holes: this.getPointsHoles( divisions, bend )
  16706. //
  16707. // };
  16708. //
  16709. // };
  16710. // Get points of shape and holes (spaced by regular distance)
  16711. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  16712. return {
  16713. shape: this.getTransformedSpacedPoints( divisions ),
  16714. holes: this.getSpacedPointsHoles( divisions )
  16715. };
  16716. };
  16717. /**************************************************************
  16718. * Utils
  16719. **************************************************************/
  16720. THREE.Shape.Utils = {
  16721. /*
  16722. contour - array of vector2 for contour
  16723. holes - array of array of vector2
  16724. */
  16725. removeHoles: function ( contour, holes ) {
  16726. var shape = contour.concat(); // work on this shape
  16727. var allpoints = shape.concat();
  16728. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  16729. var prevShapeVert, nextShapeVert,
  16730. prevHoleVert, nextHoleVert,
  16731. holeIndex, shapeIndex,
  16732. shapeId, shapeGroup,
  16733. h, h2,
  16734. hole, shortest, d,
  16735. p, pts1, pts2,
  16736. tmpShape1, tmpShape2,
  16737. tmpHole1, tmpHole2,
  16738. verts = [];
  16739. for ( h = 0; h < holes.length; h ++ ) {
  16740. hole = holes[ h ];
  16741. /*
  16742. shapeholes[ h ].concat(); // preserves original
  16743. holes.push( hole );
  16744. */
  16745. Array.prototype.push.apply( allpoints, hole );
  16746. shortest = Number.POSITIVE_INFINITY;
  16747. // Find the shortest pair of pts between shape and hole
  16748. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  16749. // Using distanceToSquared() intead of distanceTo() should speed a little
  16750. // since running square roots operations are reduced.
  16751. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  16752. pts1 = hole[ h2 ];
  16753. var dist = [];
  16754. for ( p = 0; p < shape.length; p++ ) {
  16755. pts2 = shape[ p ];
  16756. d = pts1.distanceToSquared( pts2 );
  16757. dist.push( d );
  16758. if ( d < shortest ) {
  16759. shortest = d;
  16760. holeIndex = h2;
  16761. shapeIndex = p;
  16762. }
  16763. }
  16764. }
  16765. //console.log("shortest", shortest, dist);
  16766. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16767. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16768. var areaapts = [
  16769. hole[ holeIndex ],
  16770. shape[ shapeIndex ],
  16771. shape[ prevShapeVert ]
  16772. ];
  16773. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  16774. var areabpts = [
  16775. hole[ holeIndex ],
  16776. hole[ prevHoleVert ],
  16777. shape[ shapeIndex ]
  16778. ];
  16779. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  16780. var shapeOffset = 1;
  16781. var holeOffset = -1;
  16782. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  16783. shapeIndex += shapeOffset;
  16784. holeIndex += holeOffset;
  16785. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16786. shapeIndex %= shape.length;
  16787. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16788. holeIndex %= hole.length;
  16789. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16790. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16791. areaapts = [
  16792. hole[ holeIndex ],
  16793. shape[ shapeIndex ],
  16794. shape[ prevShapeVert ]
  16795. ];
  16796. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  16797. areabpts = [
  16798. hole[ holeIndex ],
  16799. hole[ prevHoleVert ],
  16800. shape[ shapeIndex ]
  16801. ];
  16802. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  16803. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  16804. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  16805. // In case areas are not correct.
  16806. //console.log("USE THIS");
  16807. shapeIndex = oldShapeIndex;
  16808. holeIndex = oldHoleIndex ;
  16809. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16810. shapeIndex %= shape.length;
  16811. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16812. holeIndex %= hole.length;
  16813. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16814. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16815. } else {
  16816. //console.log("USE THAT ")
  16817. }
  16818. tmpShape1 = shape.slice( 0, shapeIndex );
  16819. tmpShape2 = shape.slice( shapeIndex );
  16820. tmpHole1 = hole.slice( holeIndex );
  16821. tmpHole2 = hole.slice( 0, holeIndex );
  16822. // Should check orders here again?
  16823. var trianglea = [
  16824. hole[ holeIndex ],
  16825. shape[ shapeIndex ],
  16826. shape[ prevShapeVert ]
  16827. ];
  16828. var triangleb = [
  16829. hole[ holeIndex ] ,
  16830. hole[ prevHoleVert ],
  16831. shape[ shapeIndex ]
  16832. ];
  16833. verts.push( trianglea );
  16834. verts.push( triangleb );
  16835. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  16836. }
  16837. return {
  16838. shape:shape, /* shape with no holes */
  16839. isolatedPts: verts, /* isolated faces */
  16840. allpoints: allpoints
  16841. }
  16842. },
  16843. triangulateShape: function ( contour, holes ) {
  16844. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  16845. var shape = shapeWithoutHoles.shape,
  16846. allpoints = shapeWithoutHoles.allpoints,
  16847. isolatedPts = shapeWithoutHoles.isolatedPts;
  16848. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  16849. // 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.
  16850. //console.log( "triangles",triangles, triangles.length );
  16851. //console.log( "allpoints",allpoints, allpoints.length );
  16852. var i, il, f, face,
  16853. key, index,
  16854. allPointsMap = {},
  16855. isolatedPointsMap = {};
  16856. // prepare all points map
  16857. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  16858. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  16859. if ( allPointsMap[ key ] !== undefined ) {
  16860. console.log( "Duplicate point", key );
  16861. }
  16862. allPointsMap[ key ] = i;
  16863. }
  16864. // check all face vertices against all points map
  16865. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  16866. face = triangles[ i ];
  16867. for ( f = 0; f < 3; f ++ ) {
  16868. key = face[ f ].x + ":" + face[ f ].y;
  16869. index = allPointsMap[ key ];
  16870. if ( index !== undefined ) {
  16871. face[ f ] = index;
  16872. }
  16873. }
  16874. }
  16875. // check isolated points vertices against all points map
  16876. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  16877. face = isolatedPts[ i ];
  16878. for ( f = 0; f < 3; f ++ ) {
  16879. key = face[ f ].x + ":" + face[ f ].y;
  16880. index = allPointsMap[ key ];
  16881. if ( index !== undefined ) {
  16882. face[ f ] = index;
  16883. }
  16884. }
  16885. }
  16886. return triangles.concat( isolatedPts );
  16887. }, // end triangulate shapes
  16888. /*
  16889. triangulate2 : function( pts, holes ) {
  16890. // For use with Poly2Tri.js
  16891. var allpts = pts.concat();
  16892. var shape = [];
  16893. for (var p in pts) {
  16894. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  16895. }
  16896. var swctx = new js.poly2tri.SweepContext(shape);
  16897. for (var h in holes) {
  16898. var aHole = holes[h];
  16899. var newHole = []
  16900. for (i in aHole) {
  16901. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  16902. allpts.push(aHole[i]);
  16903. }
  16904. swctx.AddHole(newHole);
  16905. }
  16906. var find;
  16907. var findIndexForPt = function (pt) {
  16908. find = new THREE.Vector2(pt.x, pt.y);
  16909. var p;
  16910. for (p=0, pl = allpts.length; p<pl; p++) {
  16911. if (allpts[p].equals(find)) return p;
  16912. }
  16913. return -1;
  16914. };
  16915. // triangulate
  16916. js.poly2tri.sweep.Triangulate(swctx);
  16917. var triangles = swctx.GetTriangles();
  16918. var tr ;
  16919. var facesPts = [];
  16920. for (var t in triangles) {
  16921. tr = triangles[t];
  16922. facesPts.push([
  16923. findIndexForPt(tr.GetPoint(0)),
  16924. findIndexForPt(tr.GetPoint(1)),
  16925. findIndexForPt(tr.GetPoint(2))
  16926. ]);
  16927. }
  16928. // console.log(facesPts);
  16929. // console.log("triangles", triangles.length, triangles);
  16930. // Returns array of faces with 3 element each
  16931. return facesPts;
  16932. },
  16933. */
  16934. isClockWise: function ( pts ) {
  16935. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  16936. },
  16937. // Bezier Curves formulas obtained from
  16938. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  16939. // Quad Bezier Functions
  16940. b2p0: function ( t, p ) {
  16941. var k = 1 - t;
  16942. return k * k * p;
  16943. },
  16944. b2p1: function ( t, p ) {
  16945. return 2 * ( 1 - t ) * t * p;
  16946. },
  16947. b2p2: function ( t, p ) {
  16948. return t * t * p;
  16949. },
  16950. b2: function ( t, p0, p1, p2 ) {
  16951. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  16952. },
  16953. // Cubic Bezier Functions
  16954. b3p0: function ( t, p ) {
  16955. var k = 1 - t;
  16956. return k * k * k * p;
  16957. },
  16958. b3p1: function ( t, p ) {
  16959. var k = 1 - t;
  16960. return 3 * k * k * t * p;
  16961. },
  16962. b3p2: function ( t, p ) {
  16963. var k = 1 - t;
  16964. return 3 * k * t * t * p;
  16965. },
  16966. b3p3: function ( t, p ) {
  16967. return t * t * t * p;
  16968. },
  16969. b3: function ( t, p0, p1, p2, p3 ) {
  16970. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  16971. }
  16972. };
  16973. /**
  16974. * @author mikael emtinger / http://gomo.se/
  16975. */
  16976. THREE.AnimationHandler = (function() {
  16977. var playing = [];
  16978. var library = {};
  16979. var that = {};
  16980. //--- update ---
  16981. that.update = function( deltaTimeMS ) {
  16982. for( var i = 0; i < playing.length; i ++ )
  16983. playing[ i ].update( deltaTimeMS );
  16984. };
  16985. //--- add ---
  16986. that.addToUpdate = function( animation ) {
  16987. if ( playing.indexOf( animation ) === -1 )
  16988. playing.push( animation );
  16989. };
  16990. //--- remove ---
  16991. that.removeFromUpdate = function( animation ) {
  16992. var index = playing.indexOf( animation );
  16993. if( index !== -1 )
  16994. playing.splice( index, 1 );
  16995. };
  16996. //--- add ---
  16997. that.add = function( data ) {
  16998. if ( library[ data.name ] !== undefined )
  16999. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17000. library[ data.name ] = data;
  17001. initData( data );
  17002. };
  17003. //--- get ---
  17004. that.get = function( name ) {
  17005. if ( typeof name === "string" ) {
  17006. if ( library[ name ] ) {
  17007. return library[ name ];
  17008. } else {
  17009. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17010. return null;
  17011. }
  17012. } else {
  17013. // todo: add simple tween library
  17014. }
  17015. };
  17016. //--- parse ---
  17017. that.parse = function( root ) {
  17018. // setup hierarchy
  17019. var hierarchy = [];
  17020. if ( root instanceof THREE.SkinnedMesh ) {
  17021. for( var b = 0; b < root.bones.length; b++ ) {
  17022. hierarchy.push( root.bones[ b ] );
  17023. }
  17024. } else {
  17025. parseRecurseHierarchy( root, hierarchy );
  17026. }
  17027. return hierarchy;
  17028. };
  17029. var parseRecurseHierarchy = function( root, hierarchy ) {
  17030. hierarchy.push( root );
  17031. for( var c = 0; c < root.children.length; c++ )
  17032. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17033. }
  17034. //--- init data ---
  17035. var initData = function( data ) {
  17036. if( data.initialized === true )
  17037. return;
  17038. // loop through all keys
  17039. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17040. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17041. // remove minus times
  17042. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17043. data.hierarchy[ h ].keys[ k ].time = 0;
  17044. // create quaternions
  17045. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17046. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17047. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17048. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17049. }
  17050. }
  17051. // prepare morph target keys
  17052. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17053. // get all used
  17054. var usedMorphTargets = {};
  17055. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17056. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17057. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17058. usedMorphTargets[ morphTargetName ] = -1;
  17059. }
  17060. }
  17061. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17062. // set all used on all frames
  17063. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17064. var influences = {};
  17065. for ( var morphTargetName in usedMorphTargets ) {
  17066. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17067. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17068. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17069. break;
  17070. }
  17071. }
  17072. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17073. influences[ morphTargetName ] = 0;
  17074. }
  17075. }
  17076. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17077. }
  17078. }
  17079. // remove all keys that are on the same time
  17080. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17081. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17082. data.hierarchy[ h ].keys.splice( k, 1 );
  17083. k --;
  17084. }
  17085. }
  17086. // set index
  17087. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17088. data.hierarchy[ h ].keys[ k ].index = k;
  17089. }
  17090. }
  17091. // JIT
  17092. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17093. data.JIT = {};
  17094. data.JIT.hierarchy = [];
  17095. for( var h = 0; h < data.hierarchy.length; h ++ )
  17096. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17097. // done
  17098. data.initialized = true;
  17099. };
  17100. // interpolation types
  17101. that.LINEAR = 0;
  17102. that.CATMULLROM = 1;
  17103. that.CATMULLROM_FORWARD = 2;
  17104. return that;
  17105. }());
  17106. /**
  17107. * @author mikael emtinger / http://gomo.se/
  17108. * @author mrdoob / http://mrdoob.com/
  17109. * @author alteredq / http://alteredqualia.com/
  17110. */
  17111. THREE.Animation = function ( root, name, interpolationType ) {
  17112. this.root = root;
  17113. this.data = THREE.AnimationHandler.get( name );
  17114. this.hierarchy = THREE.AnimationHandler.parse( root );
  17115. this.currentTime = 0;
  17116. this.timeScale = 1;
  17117. this.isPlaying = false;
  17118. this.isPaused = true;
  17119. this.loop = true;
  17120. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17121. this.points = [];
  17122. this.target = new THREE.Vector3();
  17123. };
  17124. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17125. if ( this.isPlaying === false ) {
  17126. this.isPlaying = true;
  17127. this.loop = loop !== undefined ? loop : true;
  17128. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17129. // reset key cache
  17130. var h, hl = this.hierarchy.length,
  17131. object;
  17132. for ( h = 0; h < hl; h ++ ) {
  17133. object = this.hierarchy[ h ];
  17134. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17135. object.useQuaternion = true;
  17136. }
  17137. object.matrixAutoUpdate = true;
  17138. if ( object.animationCache === undefined ) {
  17139. object.animationCache = {};
  17140. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17141. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17142. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17143. }
  17144. var prevKey = object.animationCache.prevKey;
  17145. var nextKey = object.animationCache.nextKey;
  17146. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17147. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17148. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17149. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17150. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17151. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17152. }
  17153. this.update( 0 );
  17154. }
  17155. this.isPaused = false;
  17156. THREE.AnimationHandler.addToUpdate( this );
  17157. };
  17158. THREE.Animation.prototype.pause = function() {
  17159. if ( this.isPaused === true ) {
  17160. THREE.AnimationHandler.addToUpdate( this );
  17161. } else {
  17162. THREE.AnimationHandler.removeFromUpdate( this );
  17163. }
  17164. this.isPaused = !this.isPaused;
  17165. };
  17166. THREE.Animation.prototype.stop = function() {
  17167. this.isPlaying = false;
  17168. this.isPaused = false;
  17169. THREE.AnimationHandler.removeFromUpdate( this );
  17170. };
  17171. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17172. // early out
  17173. if ( this.isPlaying === false ) return;
  17174. // vars
  17175. var types = [ "pos", "rot", "scl" ];
  17176. var type;
  17177. var scale;
  17178. var vector;
  17179. var prevXYZ, nextXYZ;
  17180. var prevKey, nextKey;
  17181. var object;
  17182. var animationCache;
  17183. var frame;
  17184. var JIThierarchy = this.data.JIT.hierarchy;
  17185. var currentTime, unloopedCurrentTime;
  17186. var currentPoint, forwardPoint, angle;
  17187. this.currentTime += deltaTimeMS * this.timeScale;
  17188. unloopedCurrentTime = this.currentTime;
  17189. currentTime = this.currentTime = this.currentTime % this.data.length;
  17190. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17191. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17192. object = this.hierarchy[ h ];
  17193. animationCache = object.animationCache;
  17194. // loop through pos/rot/scl
  17195. for ( var t = 0; t < 3; t ++ ) {
  17196. // get keys
  17197. type = types[ t ];
  17198. prevKey = animationCache.prevKey[ type ];
  17199. nextKey = animationCache.nextKey[ type ];
  17200. // switch keys?
  17201. if ( nextKey.time <= unloopedCurrentTime ) {
  17202. // did we loop?
  17203. if ( currentTime < unloopedCurrentTime ) {
  17204. if ( this.loop ) {
  17205. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17206. nextKey = this.getNextKeyWith( type, h, 1 );
  17207. while( nextKey.time < currentTime ) {
  17208. prevKey = nextKey;
  17209. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17210. }
  17211. } else {
  17212. this.stop();
  17213. return;
  17214. }
  17215. } else {
  17216. do {
  17217. prevKey = nextKey;
  17218. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17219. } while( nextKey.time < currentTime )
  17220. }
  17221. animationCache.prevKey[ type ] = prevKey;
  17222. animationCache.nextKey[ type ] = nextKey;
  17223. }
  17224. object.matrixAutoUpdate = true;
  17225. object.matrixWorldNeedsUpdate = true;
  17226. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17227. prevXYZ = prevKey[ type ];
  17228. nextXYZ = nextKey[ type ];
  17229. // check scale error
  17230. if ( scale < 0 || scale > 1 ) {
  17231. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17232. scale = scale < 0 ? 0 : 1;
  17233. }
  17234. // interpolate
  17235. if ( type === "pos" ) {
  17236. vector = object.position;
  17237. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17238. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17239. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17240. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17241. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17242. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17243. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17244. this.points[ 1 ] = prevXYZ;
  17245. this.points[ 2 ] = nextXYZ;
  17246. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17247. scale = scale * 0.33 + 0.33;
  17248. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17249. vector.x = currentPoint[ 0 ];
  17250. vector.y = currentPoint[ 1 ];
  17251. vector.z = currentPoint[ 2 ];
  17252. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17253. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17254. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17255. this.target.subSelf( vector );
  17256. this.target.y = 0;
  17257. this.target.normalize();
  17258. angle = Math.atan2( this.target.x, this.target.z );
  17259. object.rotation.set( 0, angle, 0 );
  17260. }
  17261. }
  17262. } else if ( type === "rot" ) {
  17263. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17264. } else if ( type === "scl" ) {
  17265. vector = object.scale;
  17266. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17267. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17268. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17269. }
  17270. }
  17271. }
  17272. };
  17273. // Catmull-Rom spline
  17274. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17275. var c = [], v3 = [],
  17276. point, intPoint, weight, w2, w3,
  17277. pa, pb, pc, pd;
  17278. point = ( points.length - 1 ) * scale;
  17279. intPoint = Math.floor( point );
  17280. weight = point - intPoint;
  17281. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17282. c[ 1 ] = intPoint;
  17283. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17284. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17285. pa = points[ c[ 0 ] ];
  17286. pb = points[ c[ 1 ] ];
  17287. pc = points[ c[ 2 ] ];
  17288. pd = points[ c[ 3 ] ];
  17289. w2 = weight * weight;
  17290. w3 = weight * w2;
  17291. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17292. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17293. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17294. return v3;
  17295. };
  17296. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17297. var v0 = ( p2 - p0 ) * 0.5,
  17298. v1 = ( p3 - p1 ) * 0.5;
  17299. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17300. };
  17301. // Get next key with
  17302. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17303. var keys = this.data.hierarchy[ h ].keys;
  17304. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17305. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17306. key = key < keys.length - 1 ? key : keys.length - 1;
  17307. } else {
  17308. key = key % keys.length;
  17309. }
  17310. for ( ; key < keys.length; key++ ) {
  17311. if ( keys[ key ][ type ] !== undefined ) {
  17312. return keys[ key ];
  17313. }
  17314. }
  17315. return this.data.hierarchy[ h ].keys[ 0 ];
  17316. };
  17317. // Get previous key with
  17318. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17319. var keys = this.data.hierarchy[ h ].keys;
  17320. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17321. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17322. key = key > 0 ? key : 0;
  17323. } else {
  17324. key = key >= 0 ? key : key + keys.length;
  17325. }
  17326. for ( ; key >= 0; key -- ) {
  17327. if ( keys[ key ][ type ] !== undefined ) {
  17328. return keys[ key ];
  17329. }
  17330. }
  17331. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17332. };
  17333. /**
  17334. * @author mikael emtinger / http://gomo.se/
  17335. * @author mrdoob / http://mrdoob.com/
  17336. * @author alteredq / http://alteredqualia.com/
  17337. * @author khang duong
  17338. * @author erik kitson
  17339. */
  17340. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17341. this.root = root;
  17342. this.data = THREE.AnimationHandler.get( data );
  17343. this.hierarchy = THREE.AnimationHandler.parse( root );
  17344. this.currentTime = 0;
  17345. this.timeScale = 0.001;
  17346. this.isPlaying = false;
  17347. this.isPaused = true;
  17348. this.loop = true;
  17349. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17350. // initialize to first keyframes
  17351. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17352. var keys = this.data.hierarchy[h].keys,
  17353. sids = this.data.hierarchy[h].sids,
  17354. obj = this.hierarchy[h];
  17355. if ( keys.length && sids ) {
  17356. for ( var s = 0; s < sids.length; s++ ) {
  17357. var sid = sids[ s ],
  17358. next = this.getNextKeyWith( sid, h, 0 );
  17359. if ( next ) {
  17360. next.apply( sid );
  17361. }
  17362. }
  17363. obj.matrixAutoUpdate = false;
  17364. this.data.hierarchy[h].node.updateMatrix();
  17365. obj.matrixWorldNeedsUpdate = true;
  17366. }
  17367. }
  17368. };
  17369. // Play
  17370. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  17371. if( !this.isPlaying ) {
  17372. this.isPlaying = true;
  17373. this.loop = loop !== undefined ? loop : true;
  17374. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17375. this.startTimeMs = startTimeMS;
  17376. this.startTime = 10000000;
  17377. this.endTime = -this.startTime;
  17378. // reset key cache
  17379. var h, hl = this.hierarchy.length,
  17380. object,
  17381. node;
  17382. for ( h = 0; h < hl; h++ ) {
  17383. object = this.hierarchy[ h ];
  17384. node = this.data.hierarchy[ h ];
  17385. object.useQuaternion = true;
  17386. if ( node.animationCache === undefined ) {
  17387. node.animationCache = {};
  17388. node.animationCache.prevKey = null;
  17389. node.animationCache.nextKey = null;
  17390. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17391. }
  17392. var keys = this.data.hierarchy[h].keys;
  17393. if (keys.length) {
  17394. node.animationCache.prevKey = keys[ 0 ];
  17395. node.animationCache.nextKey = keys[ 1 ];
  17396. this.startTime = Math.min( keys[0].time, this.startTime );
  17397. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17398. }
  17399. }
  17400. this.update( 0 );
  17401. }
  17402. this.isPaused = false;
  17403. THREE.AnimationHandler.addToUpdate( this );
  17404. };
  17405. // Pause
  17406. THREE.KeyFrameAnimation.prototype.pause = function() {
  17407. if( this.isPaused ) {
  17408. THREE.AnimationHandler.addToUpdate( this );
  17409. } else {
  17410. THREE.AnimationHandler.removeFromUpdate( this );
  17411. }
  17412. this.isPaused = !this.isPaused;
  17413. };
  17414. // Stop
  17415. THREE.KeyFrameAnimation.prototype.stop = function() {
  17416. this.isPlaying = false;
  17417. this.isPaused = false;
  17418. THREE.AnimationHandler.removeFromUpdate( this );
  17419. // reset JIT matrix and remove cache
  17420. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  17421. var obj = this.hierarchy[ h ];
  17422. var node = this.data.hierarchy[ h ];
  17423. if ( node.animationCache !== undefined ) {
  17424. var original = node.animationCache.originalMatrix;
  17425. if( obj instanceof THREE.Bone ) {
  17426. original.copy( obj.skinMatrix );
  17427. obj.skinMatrix = original;
  17428. } else {
  17429. original.copy( obj.matrix );
  17430. obj.matrix = original;
  17431. }
  17432. delete node.animationCache;
  17433. }
  17434. }
  17435. };
  17436. // Update
  17437. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  17438. // early out
  17439. if( !this.isPlaying ) return;
  17440. // vars
  17441. var prevKey, nextKey;
  17442. var object;
  17443. var node;
  17444. var frame;
  17445. var JIThierarchy = this.data.JIT.hierarchy;
  17446. var currentTime, unloopedCurrentTime;
  17447. var looped;
  17448. // update
  17449. this.currentTime += deltaTimeMS * this.timeScale;
  17450. unloopedCurrentTime = this.currentTime;
  17451. currentTime = this.currentTime = this.currentTime % this.data.length;
  17452. // if looped around, the current time should be based on the startTime
  17453. if ( currentTime < this.startTimeMs ) {
  17454. currentTime = this.currentTime = this.startTimeMs + currentTime;
  17455. }
  17456. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17457. looped = currentTime < unloopedCurrentTime;
  17458. if ( looped && !this.loop ) {
  17459. // Set the animation to the last keyframes and stop
  17460. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17461. var keys = this.data.hierarchy[h].keys,
  17462. sids = this.data.hierarchy[h].sids,
  17463. end = keys.length-1,
  17464. obj = this.hierarchy[h];
  17465. if ( keys.length ) {
  17466. for ( var s = 0; s < sids.length; s++ ) {
  17467. var sid = sids[ s ],
  17468. prev = this.getPrevKeyWith( sid, h, end );
  17469. if ( prev ) {
  17470. prev.apply( sid );
  17471. }
  17472. }
  17473. this.data.hierarchy[h].node.updateMatrix();
  17474. obj.matrixWorldNeedsUpdate = true;
  17475. }
  17476. }
  17477. this.stop();
  17478. return;
  17479. }
  17480. // check pre-infinity
  17481. if ( currentTime < this.startTime ) {
  17482. return;
  17483. }
  17484. // update
  17485. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17486. object = this.hierarchy[ h ];
  17487. node = this.data.hierarchy[ h ];
  17488. var keys = node.keys,
  17489. animationCache = node.animationCache;
  17490. // use JIT?
  17491. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  17492. if( object instanceof THREE.Bone ) {
  17493. object.skinMatrix = JIThierarchy[ h ][ frame ];
  17494. object.matrixWorldNeedsUpdate = false;
  17495. } else {
  17496. object.matrix = JIThierarchy[ h ][ frame ];
  17497. object.matrixWorldNeedsUpdate = true;
  17498. }
  17499. // use interpolation
  17500. } else if ( keys.length ) {
  17501. // make sure so original matrix and not JIT matrix is set
  17502. if ( this.JITCompile && animationCache ) {
  17503. if( object instanceof THREE.Bone ) {
  17504. object.skinMatrix = animationCache.originalMatrix;
  17505. } else {
  17506. object.matrix = animationCache.originalMatrix;
  17507. }
  17508. }
  17509. prevKey = animationCache.prevKey;
  17510. nextKey = animationCache.nextKey;
  17511. if ( prevKey && nextKey ) {
  17512. // switch keys?
  17513. if ( nextKey.time <= unloopedCurrentTime ) {
  17514. // did we loop?
  17515. if ( looped && this.loop ) {
  17516. prevKey = keys[ 0 ];
  17517. nextKey = keys[ 1 ];
  17518. while ( nextKey.time < currentTime ) {
  17519. prevKey = nextKey;
  17520. nextKey = keys[ prevKey.index + 1 ];
  17521. }
  17522. } else if ( !looped ) {
  17523. var lastIndex = keys.length - 1;
  17524. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  17525. prevKey = nextKey;
  17526. nextKey = keys[ prevKey.index + 1 ];
  17527. }
  17528. }
  17529. animationCache.prevKey = prevKey;
  17530. animationCache.nextKey = nextKey;
  17531. }
  17532. if(nextKey.time >= currentTime)
  17533. prevKey.interpolate( nextKey, currentTime );
  17534. else
  17535. prevKey.interpolate( nextKey, nextKey.time);
  17536. }
  17537. this.data.hierarchy[h].node.updateMatrix();
  17538. object.matrixWorldNeedsUpdate = true;
  17539. }
  17540. }
  17541. // update JIT?
  17542. if ( this.JITCompile ) {
  17543. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  17544. this.hierarchy[ 0 ].updateMatrixWorld( true );
  17545. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  17546. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  17547. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  17548. } else {
  17549. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  17550. }
  17551. }
  17552. }
  17553. }
  17554. };
  17555. // Get next key with
  17556. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  17557. var keys = this.data.hierarchy[ h ].keys;
  17558. key = key % keys.length;
  17559. for ( ; key < keys.length; key++ ) {
  17560. if ( keys[ key ].hasTarget( sid ) ) {
  17561. return keys[ key ];
  17562. }
  17563. }
  17564. return keys[ 0 ];
  17565. };
  17566. // Get previous key with
  17567. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  17568. var keys = this.data.hierarchy[ h ].keys;
  17569. key = key >= 0 ? key : key + keys.length;
  17570. for ( ; key >= 0; key-- ) {
  17571. if ( keys[ key ].hasTarget( sid ) ) {
  17572. return keys[ key ];
  17573. }
  17574. }
  17575. return keys[ keys.length - 1 ];
  17576. };
  17577. /**
  17578. * Camera for rendering cube maps
  17579. * - renders scene into axis-aligned cube
  17580. *
  17581. * @author alteredq / http://alteredqualia.com/
  17582. */
  17583. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  17584. THREE.Object3D.call( this );
  17585. var fov = 90, aspect = 1;
  17586. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17587. cameraPX.up.set( 0, -1, 0 );
  17588. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  17589. this.add( cameraPX );
  17590. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17591. cameraNX.up.set( 0, -1, 0 );
  17592. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  17593. this.add( cameraNX );
  17594. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17595. cameraPY.up.set( 0, 0, 1 );
  17596. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  17597. this.add( cameraPY );
  17598. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17599. cameraNY.up.set( 0, 0, -1 );
  17600. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  17601. this.add( cameraNY );
  17602. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17603. cameraPZ.up.set( 0, -1, 0 );
  17604. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  17605. this.add( cameraPZ );
  17606. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17607. cameraNZ.up.set( 0, -1, 0 );
  17608. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  17609. this.add( cameraNZ );
  17610. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  17611. this.updateCubeMap = function ( renderer, scene ) {
  17612. var renderTarget = this.renderTarget;
  17613. var generateMipmaps = renderTarget.generateMipmaps;
  17614. renderTarget.generateMipmaps = false;
  17615. renderTarget.activeCubeFace = 0;
  17616. renderer.render( scene, cameraPX, renderTarget );
  17617. renderTarget.activeCubeFace = 1;
  17618. renderer.render( scene, cameraNX, renderTarget );
  17619. renderTarget.activeCubeFace = 2;
  17620. renderer.render( scene, cameraPY, renderTarget );
  17621. renderTarget.activeCubeFace = 3;
  17622. renderer.render( scene, cameraNY, renderTarget );
  17623. renderTarget.activeCubeFace = 4;
  17624. renderer.render( scene, cameraPZ, renderTarget );
  17625. renderTarget.generateMipmaps = generateMipmaps;
  17626. renderTarget.activeCubeFace = 5;
  17627. renderer.render( scene, cameraNZ, renderTarget );
  17628. };
  17629. };
  17630. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  17631. /*
  17632. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  17633. *
  17634. * A general perpose camera, for setting FOV, Lens Focal Length,
  17635. * and switching between perspective and orthographic views easily.
  17636. * Use this only if you do not wish to manage
  17637. * both a Orthographic and Perspective Camera
  17638. *
  17639. */
  17640. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  17641. THREE.Camera.call( this );
  17642. this.fov = fov;
  17643. this.left = -width / 2;
  17644. this.right = width / 2
  17645. this.top = height / 2;
  17646. this.bottom = -height / 2;
  17647. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  17648. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  17649. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  17650. this.zoom = 1;
  17651. this.toPerspective();
  17652. var aspect = width/height;
  17653. };
  17654. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  17655. THREE.CombinedCamera.prototype.toPerspective = function () {
  17656. // Switches to the Perspective Camera
  17657. this.near = this.cameraP.near;
  17658. this.far = this.cameraP.far;
  17659. this.cameraP.fov = this.fov / this.zoom ;
  17660. this.cameraP.updateProjectionMatrix();
  17661. this.projectionMatrix = this.cameraP.projectionMatrix;
  17662. this.inPerspectiveMode = true;
  17663. this.inOrthographicMode = false;
  17664. };
  17665. THREE.CombinedCamera.prototype.toOrthographic = function () {
  17666. // Switches to the Orthographic camera estimating viewport from Perspective
  17667. var fov = this.fov;
  17668. var aspect = this.cameraP.aspect;
  17669. var near = this.cameraP.near;
  17670. var far = this.cameraP.far;
  17671. // The size that we set is the mid plane of the viewing frustum
  17672. var hyperfocus = ( near + far ) / 2;
  17673. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  17674. var planeHeight = 2 * halfHeight;
  17675. var planeWidth = planeHeight * aspect;
  17676. var halfWidth = planeWidth / 2;
  17677. halfHeight /= this.zoom;
  17678. halfWidth /= this.zoom;
  17679. this.cameraO.left = -halfWidth;
  17680. this.cameraO.right = halfWidth;
  17681. this.cameraO.top = halfHeight;
  17682. this.cameraO.bottom = -halfHeight;
  17683. // this.cameraO.left = -farHalfWidth;
  17684. // this.cameraO.right = farHalfWidth;
  17685. // this.cameraO.top = farHalfHeight;
  17686. // this.cameraO.bottom = -farHalfHeight;
  17687. // this.cameraO.left = this.left / this.zoom;
  17688. // this.cameraO.right = this.right / this.zoom;
  17689. // this.cameraO.top = this.top / this.zoom;
  17690. // this.cameraO.bottom = this.bottom / this.zoom;
  17691. this.cameraO.updateProjectionMatrix();
  17692. this.near = this.cameraO.near;
  17693. this.far = this.cameraO.far;
  17694. this.projectionMatrix = this.cameraO.projectionMatrix;
  17695. this.inPerspectiveMode = false;
  17696. this.inOrthographicMode = true;
  17697. };
  17698. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  17699. this.cameraP.aspect = width / height;
  17700. this.left = -width / 2;
  17701. this.right = width / 2
  17702. this.top = height / 2;
  17703. this.bottom = -height / 2;
  17704. };
  17705. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  17706. this.fov = fov;
  17707. if ( this.inPerspectiveMode ) {
  17708. this.toPerspective();
  17709. } else {
  17710. this.toOrthographic();
  17711. }
  17712. };
  17713. // For mantaining similar API with PerspectiveCamera
  17714. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  17715. if ( this.inPerspectiveMode ) {
  17716. this.toPerspective();
  17717. } else {
  17718. this.toPerspective();
  17719. this.toOrthographic();
  17720. }
  17721. };
  17722. /*
  17723. * Uses Focal Length (in mm) to estimate and set FOV
  17724. * 35mm (fullframe) camera is used if frame size is not specified;
  17725. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  17726. */
  17727. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  17728. if ( frameHeight === undefined ) frameHeight = 24;
  17729. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  17730. this.setFov( fov );
  17731. return fov;
  17732. };
  17733. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  17734. this.zoom = zoom;
  17735. if ( this.inPerspectiveMode ) {
  17736. this.toPerspective();
  17737. } else {
  17738. this.toOrthographic();
  17739. }
  17740. };
  17741. THREE.CombinedCamera.prototype.toFrontView = function() {
  17742. this.rotation.x = 0;
  17743. this.rotation.y = 0;
  17744. this.rotation.z = 0;
  17745. // should we be modifing the matrix instead?
  17746. this.rotationAutoUpdate = false;
  17747. };
  17748. THREE.CombinedCamera.prototype.toBackView = function() {
  17749. this.rotation.x = 0;
  17750. this.rotation.y = Math.PI;
  17751. this.rotation.z = 0;
  17752. this.rotationAutoUpdate = false;
  17753. };
  17754. THREE.CombinedCamera.prototype.toLeftView = function() {
  17755. this.rotation.x = 0;
  17756. this.rotation.y = - Math.PI / 2;
  17757. this.rotation.z = 0;
  17758. this.rotationAutoUpdate = false;
  17759. };
  17760. THREE.CombinedCamera.prototype.toRightView = function() {
  17761. this.rotation.x = 0;
  17762. this.rotation.y = Math.PI / 2;
  17763. this.rotation.z = 0;
  17764. this.rotationAutoUpdate = false;
  17765. };
  17766. THREE.CombinedCamera.prototype.toTopView = function() {
  17767. this.rotation.x = - Math.PI / 2;
  17768. this.rotation.y = 0;
  17769. this.rotation.z = 0;
  17770. this.rotationAutoUpdate = false;
  17771. };
  17772. THREE.CombinedCamera.prototype.toBottomView = function() {
  17773. this.rotation.x = Math.PI / 2;
  17774. this.rotation.y = 0;
  17775. this.rotation.z = 0;
  17776. this.rotationAutoUpdate = false;
  17777. };
  17778. /**
  17779. * @author alteredq / http://alteredqualia.com/
  17780. *
  17781. * - 3d asterisk shape (for line pieces THREE.Line)
  17782. */
  17783. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  17784. THREE.Geometry.call( this );
  17785. var sd = innerRadius;
  17786. var ed = outerRadius;
  17787. var sd2 = 0.707 * sd;
  17788. var ed2 = 0.707 * ed;
  17789. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  17790. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  17791. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  17792. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  17793. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  17794. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  17795. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  17796. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  17797. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  17798. ];
  17799. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  17800. var x = rays[ i ][ 0 ];
  17801. var y = rays[ i ][ 1 ];
  17802. var z = rays[ i ][ 2 ];
  17803. this.vertices.push( new THREE.Vector3( x, y, z ) );
  17804. }
  17805. };
  17806. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  17807. * @author hughes
  17808. */
  17809. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  17810. THREE.Geometry.call( this );
  17811. radius = radius || 50;
  17812. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17813. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17814. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17815. var i, uvs = [],
  17816. center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );
  17817. this.vertices.push(center);
  17818. uvs.push( centerUV );
  17819. for ( i = 0; i <= segments; i ++ ) {
  17820. var vertex = new THREE.Vector3();
  17821. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  17822. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  17823. this.vertices.push( vertex );
  17824. uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  17825. }
  17826. var n = new THREE.Vector3( 0, 0, -1 );
  17827. for ( i = 1; i <= segments; i ++ ) {
  17828. var v1 = i;
  17829. var v2 = i + 1 ;
  17830. var v3 = 0;
  17831. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  17832. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  17833. }
  17834. this.computeCentroids();
  17835. this.computeFaceNormals();
  17836. this.boundingSphere = { radius: radius };
  17837. };
  17838. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17839. /**
  17840. * @author mrdoob / http://mrdoob.com/
  17841. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  17842. */
  17843. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  17844. THREE.Geometry.call( this );
  17845. var scope = this;
  17846. this.width = width;
  17847. this.height = height;
  17848. this.depth = depth;
  17849. this.widthSegments = widthSegments || 1;
  17850. this.heightSegments = heightSegments || 1;
  17851. this.depthSegments = depthSegments || 1;
  17852. var width_half = this.width / 2;
  17853. var height_half = this.height / 2;
  17854. var depth_half = this.depth / 2;
  17855. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  17856. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  17857. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  17858. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  17859. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  17860. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  17861. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  17862. var w, ix, iy,
  17863. gridX = scope.widthSegments,
  17864. gridY = scope.heightSegments,
  17865. width_half = width / 2,
  17866. height_half = height / 2,
  17867. offset = scope.vertices.length;
  17868. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  17869. w = 'z';
  17870. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  17871. w = 'y';
  17872. gridY = scope.depthSegments;
  17873. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  17874. w = 'x';
  17875. gridX = scope.depthSegments;
  17876. }
  17877. var gridX1 = gridX + 1,
  17878. gridY1 = gridY + 1,
  17879. segment_width = width / gridX,
  17880. segment_height = height / gridY,
  17881. normal = new THREE.Vector3();
  17882. normal[ w ] = depth > 0 ? 1 : - 1;
  17883. for ( iy = 0; iy < gridY1; iy ++ ) {
  17884. for ( ix = 0; ix < gridX1; ix ++ ) {
  17885. var vector = new THREE.Vector3();
  17886. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  17887. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  17888. vector[ w ] = depth;
  17889. scope.vertices.push( vector );
  17890. }
  17891. }
  17892. for ( iy = 0; iy < gridY; iy++ ) {
  17893. for ( ix = 0; ix < gridX; ix++ ) {
  17894. var a = ix + gridX1 * iy;
  17895. var b = ix + gridX1 * ( iy + 1 );
  17896. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  17897. var d = ( ix + 1 ) + gridX1 * iy;
  17898. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  17899. face.normal.copy( normal );
  17900. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  17901. face.materialIndex = materialIndex;
  17902. scope.faces.push( face );
  17903. scope.faceVertexUvs[ 0 ].push( [
  17904. new THREE.UV( ix / gridX, 1 - iy / gridY ),
  17905. new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  17906. new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  17907. new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
  17908. ] );
  17909. }
  17910. }
  17911. }
  17912. this.computeCentroids();
  17913. this.mergeVertices();
  17914. };
  17915. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17916. /**
  17917. * @author mrdoob / http://mrdoob.com/
  17918. */
  17919. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  17920. THREE.Geometry.call( this );
  17921. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  17922. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  17923. height = height !== undefined ? height : 100;
  17924. var heightHalf = height / 2;
  17925. var segmentsX = radiusSegments || 8;
  17926. var segmentsY = heightSegments || 1;
  17927. var x, y, vertices = [], uvs = [];
  17928. for ( y = 0; y <= segmentsY; y ++ ) {
  17929. var verticesRow = [];
  17930. var uvsRow = [];
  17931. var v = y / segmentsY;
  17932. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17933. for ( x = 0; x <= segmentsX; x ++ ) {
  17934. var u = x / segmentsX;
  17935. var vertex = new THREE.Vector3();
  17936. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  17937. vertex.y = - v * height + heightHalf;
  17938. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  17939. this.vertices.push( vertex );
  17940. verticesRow.push( this.vertices.length - 1 );
  17941. uvsRow.push( new THREE.UV( u, 1 - v ) );
  17942. }
  17943. vertices.push( verticesRow );
  17944. uvs.push( uvsRow );
  17945. }
  17946. var tanTheta = ( radiusBottom - radiusTop ) / height;
  17947. var na, nb;
  17948. for ( x = 0; x < segmentsX; x ++ ) {
  17949. if ( radiusTop !== 0 ) {
  17950. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  17951. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  17952. } else {
  17953. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  17954. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  17955. }
  17956. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  17957. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  17958. for ( y = 0; y < segmentsY; y ++ ) {
  17959. var v1 = vertices[ y ][ x ];
  17960. var v2 = vertices[ y + 1 ][ x ];
  17961. var v3 = vertices[ y + 1 ][ x + 1 ];
  17962. var v4 = vertices[ y ][ x + 1 ];
  17963. var n1 = na.clone();
  17964. var n2 = na.clone();
  17965. var n3 = nb.clone();
  17966. var n4 = nb.clone();
  17967. var uv1 = uvs[ y ][ x ].clone();
  17968. var uv2 = uvs[ y + 1 ][ x ].clone();
  17969. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  17970. var uv4 = uvs[ y ][ x + 1 ].clone();
  17971. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  17972. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  17973. }
  17974. }
  17975. // top cap
  17976. if ( !openEnded && radiusTop > 0 ) {
  17977. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  17978. for ( x = 0; x < segmentsX; x ++ ) {
  17979. var v1 = vertices[ 0 ][ x ];
  17980. var v2 = vertices[ 0 ][ x + 1 ];
  17981. var v3 = this.vertices.length - 1;
  17982. var n1 = new THREE.Vector3( 0, 1, 0 );
  17983. var n2 = new THREE.Vector3( 0, 1, 0 );
  17984. var n3 = new THREE.Vector3( 0, 1, 0 );
  17985. var uv1 = uvs[ 0 ][ x ].clone();
  17986. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  17987. var uv3 = new THREE.UV( uv2.u, 0 );
  17988. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  17989. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  17990. }
  17991. }
  17992. // bottom cap
  17993. if ( !openEnded && radiusBottom > 0 ) {
  17994. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  17995. for ( x = 0; x < segmentsX; x ++ ) {
  17996. var v1 = vertices[ y ][ x + 1 ];
  17997. var v2 = vertices[ y ][ x ];
  17998. var v3 = this.vertices.length - 1;
  17999. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18000. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18001. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18002. var uv1 = uvs[ y ][ x + 1 ].clone();
  18003. var uv2 = uvs[ y ][ x ].clone();
  18004. var uv3 = new THREE.UV( uv2.u, 1 );
  18005. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18006. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18007. }
  18008. }
  18009. this.computeCentroids();
  18010. this.computeFaceNormals();
  18011. }
  18012. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18013. /**
  18014. * @author zz85 / http://www.lab4games.net/zz85/blog
  18015. *
  18016. * Creates extruded geometry from a path shape.
  18017. *
  18018. * parameters = {
  18019. *
  18020. * size: <float>, // size of the text
  18021. * height: <float>, // thickness to extrude text
  18022. * curveSegments: <int>, // number of points on the curves
  18023. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18024. * amount: <int>, // Amount
  18025. *
  18026. * bevelEnabled: <bool>, // turn on bevel
  18027. * bevelThickness: <float>, // how deep into text bevel goes
  18028. * bevelSize: <float>, // how far from text outline is bevel
  18029. * bevelSegments: <int>, // number of bevel layers
  18030. *
  18031. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18032. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18033. *
  18034. * material: <int> // material index for front and back faces
  18035. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18036. * uvGenerator: <Object> // object that provides UV generator functions
  18037. *
  18038. * }
  18039. **/
  18040. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18041. if ( typeof( shapes ) === "undefined" ) {
  18042. shapes = [];
  18043. return;
  18044. }
  18045. THREE.Geometry.call( this );
  18046. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18047. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18048. this.addShapeList( shapes, options );
  18049. this.computeCentroids();
  18050. this.computeFaceNormals();
  18051. // can't really use automatic vertex normals
  18052. // as then front and back sides get smoothed too
  18053. // should do separate smoothing just for sides
  18054. //this.computeVertexNormals();
  18055. //console.log( "took", ( Date.now() - startTime ) );
  18056. };
  18057. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18058. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18059. var sl = shapes.length;
  18060. for ( var s = 0; s < sl; s ++ ) {
  18061. var shape = shapes[ s ];
  18062. this.addShape( shape, options );
  18063. }
  18064. };
  18065. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18066. var amount = options.amount !== undefined ? options.amount : 100;
  18067. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18068. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18069. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18070. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18071. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18072. var steps = options.steps !== undefined ? options.steps : 1;
  18073. var extrudePath = options.extrudePath;
  18074. var extrudePts, extrudeByPath = false;
  18075. var material = options.material;
  18076. var extrudeMaterial = options.extrudeMaterial;
  18077. // Use default WorldUVGenerator if no UV generators are specified.
  18078. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18079. var shapebb = this.shapebb;
  18080. //shapebb = shape.getBoundingBox();
  18081. var splineTube, binormal, normal, position2;
  18082. if ( extrudePath ) {
  18083. extrudePts = extrudePath.getSpacedPoints( steps );
  18084. extrudeByPath = true;
  18085. bevelEnabled = false; // bevels not supported for path extrusion
  18086. // SETUP TNB variables
  18087. // Reuse TNB from TubeGeomtry for now.
  18088. // TODO1 - have a .isClosed in spline?
  18089. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18090. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18091. binormal = new THREE.Vector3();
  18092. normal = new THREE.Vector3();
  18093. position2 = new THREE.Vector3();
  18094. }
  18095. // Safeguards if bevels are not enabled
  18096. if ( ! bevelEnabled ) {
  18097. bevelSegments = 0;
  18098. bevelThickness = 0;
  18099. bevelSize = 0;
  18100. }
  18101. // Variables initalization
  18102. var ahole, h, hl; // looping of holes
  18103. var scope = this;
  18104. var bevelPoints = [];
  18105. var shapesOffset = this.vertices.length;
  18106. var shapePoints = shape.extractPoints( curveSegments );
  18107. var vertices = shapePoints.shape;
  18108. var holes = shapePoints.holes;
  18109. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18110. if ( reverse ) {
  18111. vertices = vertices.reverse();
  18112. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18113. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18114. ahole = holes[ h ];
  18115. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18116. holes[ h ] = ahole.reverse();
  18117. }
  18118. }
  18119. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18120. }
  18121. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18122. /* Vertices */
  18123. var contour = vertices; // vertices has all points but contour has only points of circumference
  18124. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18125. ahole = holes[ h ];
  18126. vertices = vertices.concat( ahole );
  18127. }
  18128. function scalePt2 ( pt, vec, size ) {
  18129. if ( !vec ) console.log( "die" );
  18130. return vec.clone().multiplyScalar( size ).addSelf( pt );
  18131. }
  18132. var b, bs, t, z,
  18133. vert, vlen = vertices.length,
  18134. face, flen = faces.length,
  18135. cont, clen = contour.length;
  18136. // Find directions for point movement
  18137. var RAD_TO_DEGREES = 180 / Math.PI;
  18138. function getBevelVec( pt_i, pt_j, pt_k ) {
  18139. // Algorithm 2
  18140. return getBevelVec2( pt_i, pt_j, pt_k );
  18141. }
  18142. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18143. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18144. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18145. if ( anglea > angleb ) {
  18146. angleb += Math.PI * 2;
  18147. }
  18148. var anglec = ( anglea + angleb ) / 2;
  18149. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18150. var x = - Math.cos( anglec );
  18151. var y = - Math.sin( anglec );
  18152. var vec = new THREE.Vector2( x, y ); //.normalize();
  18153. return vec;
  18154. }
  18155. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18156. var a = THREE.ExtrudeGeometry.__v1,
  18157. b = THREE.ExtrudeGeometry.__v2,
  18158. v_hat = THREE.ExtrudeGeometry.__v3,
  18159. w_hat = THREE.ExtrudeGeometry.__v4,
  18160. p = THREE.ExtrudeGeometry.__v5,
  18161. q = THREE.ExtrudeGeometry.__v6,
  18162. v, w,
  18163. v_dot_w_hat, q_sub_p_dot_w_hat,
  18164. s, intersection;
  18165. // good reading for line-line intersection
  18166. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18167. // define a as vector j->i
  18168. // define b as vectot k->i
  18169. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18170. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18171. // get unit vectors
  18172. v = a.normalize();
  18173. w = b.normalize();
  18174. // normals from pt i
  18175. v_hat.set( -v.y, v.x );
  18176. w_hat.set( w.y, -w.x );
  18177. // pts from i
  18178. p.copy( pt_i ).addSelf( v_hat );
  18179. q.copy( pt_i ).addSelf( w_hat );
  18180. if ( p.equals( q ) ) {
  18181. //console.log("Warning: lines are straight");
  18182. return w_hat.clone();
  18183. }
  18184. // Points from j, k. helps prevents points cross overover most of the time
  18185. p.copy( pt_j ).addSelf( v_hat );
  18186. q.copy( pt_k ).addSelf( w_hat );
  18187. v_dot_w_hat = v.dot( w_hat );
  18188. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  18189. // We should not reach these conditions
  18190. if ( v_dot_w_hat === 0 ) {
  18191. console.log( "Either infinite or no solutions!" );
  18192. if ( q_sub_p_dot_w_hat === 0 ) {
  18193. console.log( "Its finite solutions." );
  18194. } else {
  18195. console.log( "Too bad, no solutions." );
  18196. }
  18197. }
  18198. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18199. if ( s < 0 ) {
  18200. // in case of emergecy, revert to algorithm 1.
  18201. return getBevelVec1( pt_i, pt_j, pt_k );
  18202. }
  18203. intersection = v.multiplyScalar( s ).addSelf( p );
  18204. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18205. }
  18206. var contourMovements = [];
  18207. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18208. if ( j === il ) j = 0;
  18209. if ( k === il ) k = 0;
  18210. // (j)---(i)---(k)
  18211. // console.log('i,j,k', i, j , k)
  18212. var pt_i = contour[ i ];
  18213. var pt_j = contour[ j ];
  18214. var pt_k = contour[ k ];
  18215. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18216. }
  18217. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18218. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18219. ahole = holes[ h ];
  18220. oneHoleMovements = [];
  18221. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18222. if ( j === il ) j = 0;
  18223. if ( k === il ) k = 0;
  18224. // (j)---(i)---(k)
  18225. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18226. }
  18227. holesMovements.push( oneHoleMovements );
  18228. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18229. }
  18230. // Loop bevelSegments, 1 for the front, 1 for the back
  18231. for ( b = 0; b < bevelSegments; b ++ ) {
  18232. //for ( b = bevelSegments; b > 0; b -- ) {
  18233. t = b / bevelSegments;
  18234. z = bevelThickness * ( 1 - t );
  18235. //z = bevelThickness * t;
  18236. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18237. //bs = bevelSize * t ; // linear
  18238. // contract shape
  18239. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18240. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18241. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18242. v( vert.x, vert.y, - z );
  18243. }
  18244. // expand holes
  18245. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18246. ahole = holes[ h ];
  18247. oneHoleMovements = holesMovements[ h ];
  18248. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18249. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18250. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18251. v( vert.x, vert.y, -z );
  18252. }
  18253. }
  18254. }
  18255. bs = bevelSize;
  18256. // Back facing vertices
  18257. for ( i = 0; i < vlen; i ++ ) {
  18258. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18259. if ( !extrudeByPath ) {
  18260. v( vert.x, vert.y, 0 );
  18261. } else {
  18262. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18263. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18264. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18265. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  18266. v( position2.x, position2.y, position2.z );
  18267. }
  18268. }
  18269. // Add stepped vertices...
  18270. // Including front facing vertices
  18271. var s;
  18272. for ( s = 1; s <= steps; s ++ ) {
  18273. for ( i = 0; i < vlen; i ++ ) {
  18274. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18275. if ( !extrudeByPath ) {
  18276. v( vert.x, vert.y, amount / steps * s );
  18277. } else {
  18278. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18279. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18280. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18281. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  18282. v( position2.x, position2.y, position2.z );
  18283. }
  18284. }
  18285. }
  18286. // Add bevel segments planes
  18287. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18288. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18289. t = b / bevelSegments;
  18290. z = bevelThickness * ( 1 - t );
  18291. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18292. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18293. // contract shape
  18294. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18295. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18296. v( vert.x, vert.y, amount + z );
  18297. }
  18298. // expand holes
  18299. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18300. ahole = holes[ h ];
  18301. oneHoleMovements = holesMovements[ h ];
  18302. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18303. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18304. if ( !extrudeByPath ) {
  18305. v( vert.x, vert.y, amount + z );
  18306. } else {
  18307. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18308. }
  18309. }
  18310. }
  18311. }
  18312. /* Faces */
  18313. // Top and bottom faces
  18314. buildLidFaces();
  18315. // Sides faces
  18316. buildSideFaces();
  18317. ///// Internal functions
  18318. function buildLidFaces() {
  18319. if ( bevelEnabled ) {
  18320. var layer = 0 ; // steps + 1
  18321. var offset = vlen * layer;
  18322. // Bottom faces
  18323. for ( i = 0; i < flen; i ++ ) {
  18324. face = faces[ i ];
  18325. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18326. }
  18327. layer = steps + bevelSegments * 2;
  18328. offset = vlen * layer;
  18329. // Top faces
  18330. for ( i = 0; i < flen; i ++ ) {
  18331. face = faces[ i ];
  18332. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18333. }
  18334. } else {
  18335. // Bottom faces
  18336. for ( i = 0; i < flen; i++ ) {
  18337. face = faces[ i ];
  18338. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18339. }
  18340. // Top faces
  18341. for ( i = 0; i < flen; i ++ ) {
  18342. face = faces[ i ];
  18343. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18344. }
  18345. }
  18346. }
  18347. // Create faces for the z-sides of the shape
  18348. function buildSideFaces() {
  18349. var layeroffset = 0;
  18350. sidewalls( contour, layeroffset );
  18351. layeroffset += contour.length;
  18352. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18353. ahole = holes[ h ];
  18354. sidewalls( ahole, layeroffset );
  18355. //, true
  18356. layeroffset += ahole.length;
  18357. }
  18358. }
  18359. function sidewalls( contour, layeroffset ) {
  18360. var j, k;
  18361. i = contour.length;
  18362. while ( --i >= 0 ) {
  18363. j = i;
  18364. k = i - 1;
  18365. if ( k < 0 ) k = contour.length - 1;
  18366. //console.log('b', i,j, i-1, k,vertices.length);
  18367. var s = 0, sl = steps + bevelSegments * 2;
  18368. for ( s = 0; s < sl; s ++ ) {
  18369. var slen1 = vlen * s;
  18370. var slen2 = vlen * ( s + 1 );
  18371. var a = layeroffset + j + slen1,
  18372. b = layeroffset + k + slen1,
  18373. c = layeroffset + k + slen2,
  18374. d = layeroffset + j + slen2;
  18375. f4( a, b, c, d, contour, s, sl, j, k );
  18376. }
  18377. }
  18378. }
  18379. function v( x, y, z ) {
  18380. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18381. }
  18382. function f3( a, b, c, isBottom ) {
  18383. a += shapesOffset;
  18384. b += shapesOffset;
  18385. c += shapesOffset;
  18386. // normal, color, material
  18387. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18388. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18389. scope.faceVertexUvs[ 0 ].push( uvs );
  18390. }
  18391. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18392. a += shapesOffset;
  18393. b += shapesOffset;
  18394. c += shapesOffset;
  18395. d += shapesOffset;
  18396. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18397. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18398. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18399. scope.faceVertexUvs[ 0 ].push( uvs );
  18400. }
  18401. };
  18402. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18403. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18404. var ax = geometry.vertices[ indexA ].x,
  18405. ay = geometry.vertices[ indexA ].y,
  18406. bx = geometry.vertices[ indexB ].x,
  18407. by = geometry.vertices[ indexB ].y,
  18408. cx = geometry.vertices[ indexC ].x,
  18409. cy = geometry.vertices[ indexC ].y;
  18410. return [
  18411. new THREE.UV( ax, ay ),
  18412. new THREE.UV( bx, by ),
  18413. new THREE.UV( cx, cy )
  18414. ];
  18415. },
  18416. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18417. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18418. },
  18419. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18420. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18421. contourIndex1, contourIndex2 ) {
  18422. var ax = geometry.vertices[ indexA ].x,
  18423. ay = geometry.vertices[ indexA ].y,
  18424. az = geometry.vertices[ indexA ].z,
  18425. bx = geometry.vertices[ indexB ].x,
  18426. by = geometry.vertices[ indexB ].y,
  18427. bz = geometry.vertices[ indexB ].z,
  18428. cx = geometry.vertices[ indexC ].x,
  18429. cy = geometry.vertices[ indexC ].y,
  18430. cz = geometry.vertices[ indexC ].z,
  18431. dx = geometry.vertices[ indexD ].x,
  18432. dy = geometry.vertices[ indexD ].y,
  18433. dz = geometry.vertices[ indexD ].z;
  18434. if ( Math.abs( ay - by ) < 0.01 ) {
  18435. return [
  18436. new THREE.UV( ax, 1 - az ),
  18437. new THREE.UV( bx, 1 - bz ),
  18438. new THREE.UV( cx, 1 - cz ),
  18439. new THREE.UV( dx, 1 - dz )
  18440. ];
  18441. } else {
  18442. return [
  18443. new THREE.UV( ay, 1 - az ),
  18444. new THREE.UV( by, 1 - bz ),
  18445. new THREE.UV( cy, 1 - cz ),
  18446. new THREE.UV( dy, 1 - dz )
  18447. ];
  18448. }
  18449. }
  18450. };
  18451. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18452. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18453. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18454. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18455. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18456. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18457. /**
  18458. * @author jonobr1 / http://jonobr1.com
  18459. *
  18460. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18461. * ExtrudeGeometry.
  18462. *
  18463. * parameters = {
  18464. *
  18465. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18466. *
  18467. * material: <int> // material index for front and back faces
  18468. * uvGenerator: <Object> // object that provides UV generator functions
  18469. *
  18470. * }
  18471. **/
  18472. THREE.ShapeGeometry = function ( shapes, options ) {
  18473. THREE.Geometry.call( this );
  18474. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  18475. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18476. this.addShapeList( shapes, options );
  18477. this.computeCentroids();
  18478. this.computeFaceNormals();
  18479. };
  18480. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18481. /**
  18482. * Add an array of shapes to THREE.ShapeGeometry.
  18483. */
  18484. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18485. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  18486. this.addShape( shapes[ i ], options );
  18487. }
  18488. return this;
  18489. };
  18490. /**
  18491. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18492. */
  18493. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18494. if ( options === undefined ) options = {};
  18495. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18496. var material = options.material;
  18497. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18498. var shapebb = this.shapebb;
  18499. //
  18500. var i, l, hole, s;
  18501. var shapesOffset = this.vertices.length;
  18502. var shapePoints = shape.extractPoints( curveSegments );
  18503. var vertices = shapePoints.shape;
  18504. var holes = shapePoints.holes;
  18505. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  18506. if ( reverse ) {
  18507. vertices = vertices.reverse();
  18508. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18509. for ( i = 0, l = holes.length; i < l; i++ ) {
  18510. hole = holes[ i ];
  18511. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  18512. holes[ i ] = hole.reverse();
  18513. }
  18514. }
  18515. reverse = false;
  18516. }
  18517. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  18518. // Vertices
  18519. var contour = vertices;
  18520. for ( i = 0, l = holes.length; i < l; i++ ) {
  18521. hole = holes[ i ];
  18522. vertices = vertices.concat( hole );
  18523. }
  18524. //
  18525. var vert, vlen = vertices.length;
  18526. var face, flen = faces.length;
  18527. var cont, clen = contour.length;
  18528. for ( i = 0; i < vlen; i++ ) {
  18529. vert = vertices[ i ];
  18530. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  18531. }
  18532. for ( i = 0; i < flen; i++ ) {
  18533. face = faces[ i ];
  18534. var a = face[ 0 ] + shapesOffset;
  18535. var b = face[ 1 ] + shapesOffset;
  18536. var c = face[ 2 ] + shapesOffset;
  18537. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18538. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  18539. }
  18540. };
  18541. /**
  18542. * @author astrodud / http://astrodud.isgreat.org/
  18543. * @author zz85 / https://github.com/zz85
  18544. */
  18545. THREE.LatheGeometry = function ( points, steps, angle ) {
  18546. THREE.Geometry.call( this );
  18547. var _steps = steps || 12;
  18548. var _angle = angle || 2 * Math.PI;
  18549. var _newV = [];
  18550. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  18551. for ( var j = 0; j < points.length; j ++ ) {
  18552. _newV[ j ] = points[ j ].clone();
  18553. this.vertices.push( _newV[ j ] );
  18554. }
  18555. var i, il = _steps + 1;
  18556. for ( i = 0; i < il; i ++ ) {
  18557. for ( var j = 0; j < _newV.length; j ++ ) {
  18558. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  18559. this.vertices.push( _newV[ j ] );
  18560. }
  18561. }
  18562. for ( i = 0; i < _steps; i ++ ) {
  18563. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  18564. var a = i * kl + k;
  18565. var b = ( ( i + 1 ) % il ) * kl + k;
  18566. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  18567. var d = i * kl + ( k + 1 ) % kl;
  18568. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18569. this.faceVertexUvs[ 0 ].push( [
  18570. new THREE.UV( 1 - i / _steps, k / kl ),
  18571. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  18572. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  18573. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  18574. ] );
  18575. }
  18576. }
  18577. this.computeCentroids();
  18578. this.computeFaceNormals();
  18579. this.computeVertexNormals();
  18580. };
  18581. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18582. /**
  18583. * @author mrdoob / http://mrdoob.com/
  18584. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18585. */
  18586. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  18587. THREE.Geometry.call( this );
  18588. this.width = width;
  18589. this.height = height;
  18590. this.widthSegments = widthSegments || 1;
  18591. this.heightSegments = heightSegments || 1;
  18592. var ix, iz;
  18593. var width_half = width / 2;
  18594. var height_half = height / 2;
  18595. var gridX = this.widthSegments;
  18596. var gridZ = this.heightSegments;
  18597. var gridX1 = gridX + 1;
  18598. var gridZ1 = gridZ + 1;
  18599. var segment_width = this.width / gridX;
  18600. var segment_height = this.height / gridZ;
  18601. var normal = new THREE.Vector3( 0, 0, 1 );
  18602. for ( iz = 0; iz < gridZ1; iz ++ ) {
  18603. for ( ix = 0; ix < gridX1; ix ++ ) {
  18604. var x = ix * segment_width - width_half;
  18605. var y = iz * segment_height - height_half;
  18606. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  18607. }
  18608. }
  18609. for ( iz = 0; iz < gridZ; iz ++ ) {
  18610. for ( ix = 0; ix < gridX; ix ++ ) {
  18611. var a = ix + gridX1 * iz;
  18612. var b = ix + gridX1 * ( iz + 1 );
  18613. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  18614. var d = ( ix + 1 ) + gridX1 * iz;
  18615. var face = new THREE.Face4( a, b, c, d );
  18616. face.normal.copy( normal );
  18617. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18618. this.faces.push( face );
  18619. this.faceVertexUvs[ 0 ].push( [
  18620. new THREE.UV( ix / gridX, 1 - iz / gridZ ),
  18621. new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  18622. new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  18623. new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  18624. ] );
  18625. }
  18626. }
  18627. this.computeCentroids();
  18628. };
  18629. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18630. /**
  18631. * @author mrdoob / http://mrdoob.com/
  18632. */
  18633. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  18634. THREE.Geometry.call( this );
  18635. this.radius = radius || 50;
  18636. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  18637. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  18638. phiStart = phiStart !== undefined ? phiStart : 0;
  18639. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18640. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18641. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18642. var x, y, vertices = [], uvs = [];
  18643. for ( y = 0; y <= this.heightSegments; y ++ ) {
  18644. var verticesRow = [];
  18645. var uvsRow = [];
  18646. for ( x = 0; x <= this.widthSegments; x ++ ) {
  18647. var u = x / this.widthSegments;
  18648. var v = y / this.heightSegments;
  18649. var vertex = new THREE.Vector3();
  18650. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18651. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  18652. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18653. this.vertices.push( vertex );
  18654. verticesRow.push( this.vertices.length - 1 );
  18655. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18656. }
  18657. vertices.push( verticesRow );
  18658. uvs.push( uvsRow );
  18659. }
  18660. for ( y = 0; y < this.heightSegments; y ++ ) {
  18661. for ( x = 0; x < this.widthSegments; x ++ ) {
  18662. var v1 = vertices[ y ][ x + 1 ];
  18663. var v2 = vertices[ y ][ x ];
  18664. var v3 = vertices[ y + 1 ][ x ];
  18665. var v4 = vertices[ y + 1 ][ x + 1 ];
  18666. var n1 = this.vertices[ v1 ].clone().normalize();
  18667. var n2 = this.vertices[ v2 ].clone().normalize();
  18668. var n3 = this.vertices[ v3 ].clone().normalize();
  18669. var n4 = this.vertices[ v4 ].clone().normalize();
  18670. var uv1 = uvs[ y ][ x + 1 ].clone();
  18671. var uv2 = uvs[ y ][ x ].clone();
  18672. var uv3 = uvs[ y + 1 ][ x ].clone();
  18673. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  18674. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  18675. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  18676. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  18677. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  18678. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18679. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18680. } else {
  18681. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18682. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18683. }
  18684. }
  18685. }
  18686. this.computeCentroids();
  18687. this.computeFaceNormals();
  18688. this.boundingSphere = { radius: this.radius };
  18689. };
  18690. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18691. /**
  18692. * @author zz85 / http://www.lab4games.net/zz85/blog
  18693. * @author alteredq / http://alteredqualia.com/
  18694. *
  18695. * For creating 3D text geometry in three.js
  18696. *
  18697. * Text = 3D Text
  18698. *
  18699. * parameters = {
  18700. * size: <float>, // size of the text
  18701. * height: <float>, // thickness to extrude text
  18702. * curveSegments: <int>, // number of points on the curves
  18703. *
  18704. * font: <string>, // font name
  18705. * weight: <string>, // font weight (normal, bold)
  18706. * style: <string>, // font style (normal, italics)
  18707. *
  18708. * bevelEnabled: <bool>, // turn on bevel
  18709. * bevelThickness: <float>, // how deep into text bevel goes
  18710. * bevelSize: <float>, // how far from text outline is bevel
  18711. * }
  18712. *
  18713. */
  18714. /* Usage Examples
  18715. // TextGeometry wrapper
  18716. var text3d = new TextGeometry( text, options );
  18717. // Complete manner
  18718. var textShapes = THREE.FontUtils.generateShapes( text, options );
  18719. var text3d = new ExtrudeGeometry( textShapes, options );
  18720. */
  18721. THREE.TextGeometry = function ( text, parameters ) {
  18722. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  18723. // translate parameters to ExtrudeGeometry API
  18724. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  18725. // defaults
  18726. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  18727. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  18728. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  18729. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  18730. };
  18731. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  18732. /**
  18733. * @author oosmoxiecode
  18734. * @author mrdoob / http://mrdoob.com/
  18735. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  18736. */
  18737. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  18738. THREE.Geometry.call( this );
  18739. var scope = this;
  18740. this.radius = radius || 100;
  18741. this.tube = tube || 40;
  18742. this.radialSegments = radialSegments || 8;
  18743. this.tubularSegments = tubularSegments || 6;
  18744. this.arc = arc || Math.PI * 2;
  18745. var center = new THREE.Vector3(), uvs = [], normals = [];
  18746. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  18747. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  18748. var u = i / this.tubularSegments * this.arc;
  18749. var v = j / this.radialSegments * Math.PI * 2;
  18750. center.x = this.radius * Math.cos( u );
  18751. center.y = this.radius * Math.sin( u );
  18752. var vertex = new THREE.Vector3();
  18753. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  18754. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  18755. vertex.z = this.tube * Math.sin( v );
  18756. this.vertices.push( vertex );
  18757. uvs.push( new THREE.UV( i / this.tubularSegments, j / this.radialSegments ) );
  18758. normals.push( vertex.clone().subSelf( center ).normalize() );
  18759. }
  18760. }
  18761. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  18762. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  18763. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  18764. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  18765. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  18766. var d = ( this.tubularSegments + 1 ) * j + i;
  18767. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  18768. face.normal.addSelf( normals[ a ] );
  18769. face.normal.addSelf( normals[ b ] );
  18770. face.normal.addSelf( normals[ c ] );
  18771. face.normal.addSelf( normals[ d ] );
  18772. face.normal.normalize();
  18773. this.faces.push( face );
  18774. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  18775. }
  18776. }
  18777. this.computeCentroids();
  18778. };
  18779. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18780. /**
  18781. * @author oosmoxiecode
  18782. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  18783. */
  18784. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  18785. THREE.Geometry.call( this );
  18786. var scope = this;
  18787. this.radius = radius || 200;
  18788. this.tube = tube || 40;
  18789. this.radialSegments = radialSegments || 64;
  18790. this.tubularSegments = tubularSegments || 8;
  18791. this.p = p || 2;
  18792. this.q = q || 3;
  18793. this.heightScale = heightScale || 1;
  18794. this.grid = new Array(this.radialSegments);
  18795. var tang = new THREE.Vector3();
  18796. var n = new THREE.Vector3();
  18797. var bitan = new THREE.Vector3();
  18798. for ( var i = 0; i < this.radialSegments; ++ i ) {
  18799. this.grid[ i ] = new Array( this.tubularSegments );
  18800. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  18801. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  18802. var v = j / this.tubularSegments * 2 * Math.PI;
  18803. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  18804. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  18805. var cx, cy;
  18806. tang.sub( p2, p1 );
  18807. n.add( p2, p1 );
  18808. bitan.cross( tang, n );
  18809. n.cross( bitan, tang );
  18810. bitan.normalize();
  18811. n.normalize();
  18812. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18813. cy = this.tube * Math.sin( v );
  18814. p1.x += cx * n.x + cy * bitan.x;
  18815. p1.y += cx * n.y + cy * bitan.y;
  18816. p1.z += cx * n.z + cy * bitan.z;
  18817. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  18818. }
  18819. }
  18820. for ( var i = 0; i < this.radialSegments; ++ i ) {
  18821. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  18822. var ip = ( i + 1 ) % this.radialSegments;
  18823. var jp = ( j + 1 ) % this.tubularSegments;
  18824. var a = this.grid[ i ][ j ];
  18825. var b = this.grid[ ip ][ j ];
  18826. var c = this.grid[ ip ][ jp ];
  18827. var d = this.grid[ i ][ jp ];
  18828. var uva = new THREE.UV( i / this.radialSegments, j / this.tubularSegments );
  18829. var uvb = new THREE.UV( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  18830. var uvc = new THREE.UV( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  18831. var uvd = new THREE.UV( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  18832. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18833. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  18834. }
  18835. }
  18836. this.computeCentroids();
  18837. this.computeFaceNormals();
  18838. this.computeVertexNormals();
  18839. function vert( x, y, z ) {
  18840. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18841. }
  18842. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  18843. var cu = Math.cos( u );
  18844. var cv = Math.cos( v );
  18845. var su = Math.sin( u );
  18846. var quOverP = in_q / in_p * u;
  18847. var cs = Math.cos( quOverP );
  18848. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  18849. var ty = radius * ( 2 + cs ) * su * 0.5;
  18850. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  18851. return new THREE.Vector3( tx, ty, tz );
  18852. }
  18853. };
  18854. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18855. /**
  18856. * @author WestLangley / https://github.com/WestLangley
  18857. * @author zz85 / https://github.com/zz85
  18858. * @author miningold / https://github.com/miningold
  18859. *
  18860. * Modified from the TorusKnotGeometry by @oosmoxiecode
  18861. *
  18862. * Creates a tube which extrudes along a 3d spline
  18863. *
  18864. * Uses parallel transport frames as described in
  18865. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18866. */
  18867. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  18868. THREE.Geometry.call( this );
  18869. this.path = path;
  18870. this.segments = segments || 64;
  18871. this.radius = radius || 1;
  18872. this.radiusSegments = radiusSegments || 8;
  18873. this.closed = closed || false;
  18874. if ( debug ) this.debug = new THREE.Object3D();
  18875. this.grid = [];
  18876. var scope = this,
  18877. tangent,
  18878. normal,
  18879. binormal,
  18880. numpoints = this.segments + 1,
  18881. x, y, z,
  18882. tx, ty, tz,
  18883. u, v,
  18884. cx, cy,
  18885. pos, pos2 = new THREE.Vector3(),
  18886. i, j,
  18887. ip, jp,
  18888. a, b, c, d,
  18889. uva, uvb, uvc, uvd;
  18890. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  18891. tangents = frames.tangents,
  18892. normals = frames.normals,
  18893. binormals = frames.binormals;
  18894. // proxy internals
  18895. this.tangents = tangents;
  18896. this.normals = normals;
  18897. this.binormals = binormals;
  18898. function vert( x, y, z ) {
  18899. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18900. }
  18901. // consruct the grid
  18902. for ( i = 0; i < numpoints; i++ ) {
  18903. this.grid[ i ] = [];
  18904. u = i / ( numpoints - 1 );
  18905. pos = path.getPointAt( u );
  18906. tangent = tangents[ i ];
  18907. normal = normals[ i ];
  18908. binormal = binormals[ i ];
  18909. if ( this.debug ) {
  18910. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  18911. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  18912. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  18913. }
  18914. for ( j = 0; j < this.radiusSegments; j++ ) {
  18915. v = j / this.radiusSegments * 2 * Math.PI;
  18916. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18917. cy = this.radius * Math.sin( v );
  18918. pos2.copy( pos );
  18919. pos2.x += cx * normal.x + cy * binormal.x;
  18920. pos2.y += cx * normal.y + cy * binormal.y;
  18921. pos2.z += cx * normal.z + cy * binormal.z;
  18922. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  18923. }
  18924. }
  18925. // construct the mesh
  18926. for ( i = 0; i < this.segments; i++ ) {
  18927. for ( j = 0; j < this.radiusSegments; j++ ) {
  18928. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  18929. jp = (j + 1) % this.radiusSegments;
  18930. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  18931. b = this.grid[ ip ][ j ];
  18932. c = this.grid[ ip ][ jp ];
  18933. d = this.grid[ i ][ jp ];
  18934. uva = new THREE.UV( i / this.segments, j / this.radiusSegments );
  18935. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.radiusSegments );
  18936. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  18937. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.radiusSegments );
  18938. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18939. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  18940. }
  18941. }
  18942. this.computeCentroids();
  18943. this.computeFaceNormals();
  18944. this.computeVertexNormals();
  18945. };
  18946. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18947. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  18948. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  18949. var tangent = new THREE.Vector3(),
  18950. normal = new THREE.Vector3(),
  18951. binormal = new THREE.Vector3(),
  18952. tangents = [],
  18953. normals = [],
  18954. binormals = [],
  18955. vec = new THREE.Vector3(),
  18956. mat = new THREE.Matrix4(),
  18957. numpoints = segments + 1,
  18958. theta,
  18959. epsilon = 0.0001,
  18960. smallest,
  18961. tx, ty, tz,
  18962. i, u, v;
  18963. // expose internals
  18964. this.tangents = tangents;
  18965. this.normals = normals;
  18966. this.binormals = binormals;
  18967. // compute the tangent vectors for each segment on the path
  18968. for ( i = 0; i < numpoints; i++ ) {
  18969. u = i / ( numpoints - 1 );
  18970. tangents[ i ] = path.getTangentAt( u );
  18971. tangents[ i ].normalize();
  18972. }
  18973. initialNormal3();
  18974. function initialNormal1(lastBinormal) {
  18975. // fixed start binormal. Has dangers of 0 vectors
  18976. normals[ 0 ] = new THREE.Vector3();
  18977. binormals[ 0 ] = new THREE.Vector3();
  18978. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  18979. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  18980. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18981. }
  18982. function initialNormal2() {
  18983. // This uses the Frenet-Serret formula for deriving binormal
  18984. var t2 = path.getTangentAt( epsilon );
  18985. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  18986. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  18987. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  18988. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18989. }
  18990. function initialNormal3() {
  18991. // select an initial normal vector perpenicular to the first tangent vector,
  18992. // and in the direction of the smallest tangent xyz component
  18993. normals[ 0 ] = new THREE.Vector3();
  18994. binormals[ 0 ] = new THREE.Vector3();
  18995. smallest = Number.MAX_VALUE;
  18996. tx = Math.abs( tangents[ 0 ].x );
  18997. ty = Math.abs( tangents[ 0 ].y );
  18998. tz = Math.abs( tangents[ 0 ].z );
  18999. if ( tx <= smallest ) {
  19000. smallest = tx;
  19001. normal.set( 1, 0, 0 );
  19002. }
  19003. if ( ty <= smallest ) {
  19004. smallest = ty;
  19005. normal.set( 0, 1, 0 );
  19006. }
  19007. if ( tz <= smallest ) {
  19008. normal.set( 0, 0, 1 );
  19009. }
  19010. vec.cross( tangents[ 0 ], normal ).normalize();
  19011. normals[ 0 ].cross( tangents[ 0 ], vec );
  19012. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  19013. }
  19014. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19015. for ( i = 1; i < numpoints; i++ ) {
  19016. normals[ i ] = normals[ i-1 ].clone();
  19017. binormals[ i ] = binormals[ i-1 ].clone();
  19018. vec.cross( tangents[ i-1 ], tangents[ i ] );
  19019. if ( vec.length() > epsilon ) {
  19020. vec.normalize();
  19021. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19022. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  19023. }
  19024. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19025. }
  19026. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19027. if ( closed ) {
  19028. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19029. theta /= ( numpoints - 1 );
  19030. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19031. theta = -theta;
  19032. }
  19033. for ( i = 1; i < numpoints; i++ ) {
  19034. // twist a little...
  19035. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  19036. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19037. }
  19038. }
  19039. };
  19040. /**
  19041. * @author clockworkgeek / https://github.com/clockworkgeek
  19042. * @author timothypratley / https://github.com/timothypratley
  19043. */
  19044. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19045. THREE.Geometry.call( this );
  19046. radius = radius || 1;
  19047. detail = detail || 0;
  19048. var that = this;
  19049. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19050. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19051. }
  19052. var midpoints = [], p = this.vertices;
  19053. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19054. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19055. }
  19056. this.mergeVertices();
  19057. // Apply radius
  19058. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19059. this.vertices[ i ].multiplyScalar( radius );
  19060. }
  19061. // Project vector onto sphere's surface
  19062. function prepare( vector ) {
  19063. var vertex = vector.normalize().clone();
  19064. vertex.index = that.vertices.push( vertex ) - 1;
  19065. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19066. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19067. var v = inclination( vector ) / Math.PI + 0.5;
  19068. vertex.uv = new THREE.UV( u, 1 - v );
  19069. return vertex;
  19070. }
  19071. // Approximate a curved face with recursively sub-divided triangles.
  19072. function make( v1, v2, v3, detail ) {
  19073. if ( detail < 1 ) {
  19074. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19075. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  19076. face.normal = face.centroid.clone().normalize();
  19077. that.faces.push( face );
  19078. var azi = azimuth( face.centroid );
  19079. that.faceVertexUvs[ 0 ].push( [
  19080. correctUV( v1.uv, v1, azi ),
  19081. correctUV( v2.uv, v2, azi ),
  19082. correctUV( v3.uv, v3, azi )
  19083. ] );
  19084. } else {
  19085. detail -= 1;
  19086. // split triangle into 4 smaller triangles
  19087. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19088. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19089. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19090. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19091. }
  19092. }
  19093. function midpoint( v1, v2 ) {
  19094. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19095. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19096. var mid = midpoints[ v1.index ][ v2.index ];
  19097. if ( mid === undefined ) {
  19098. // generate mean point and project to surface with prepare()
  19099. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19100. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  19101. );
  19102. }
  19103. return mid;
  19104. }
  19105. // Angle around the Y axis, counter-clockwise when looking from above.
  19106. function azimuth( vector ) {
  19107. return Math.atan2( vector.z, -vector.x );
  19108. }
  19109. // Angle above the XZ plane.
  19110. function inclination( vector ) {
  19111. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19112. }
  19113. // Texture fixing helper. Spheres have some odd behaviours.
  19114. function correctUV( uv, vector, azimuth ) {
  19115. if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
  19116. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  19117. return uv;
  19118. }
  19119. this.computeCentroids();
  19120. this.boundingSphere = { radius: radius };
  19121. };
  19122. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19123. /**
  19124. * @author timothypratley / https://github.com/timothypratley
  19125. */
  19126. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19127. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19128. var vertices = [
  19129. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19130. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19131. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19132. ];
  19133. var faces = [
  19134. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19135. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19136. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19137. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19138. ];
  19139. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19140. };
  19141. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19142. /**
  19143. * @author timothypratley / https://github.com/timothypratley
  19144. */
  19145. THREE.OctahedronGeometry = function ( radius, detail ) {
  19146. var vertices = [
  19147. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19148. ];
  19149. var faces = [
  19150. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19151. ];
  19152. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19153. };
  19154. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19155. /**
  19156. * @author timothypratley / https://github.com/timothypratley
  19157. */
  19158. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19159. var vertices = [
  19160. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19161. ];
  19162. var faces = [
  19163. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19164. ];
  19165. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19166. };
  19167. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19168. /**
  19169. * @author zz85 / https://github.com/zz85
  19170. * Parametric Surfaces Geometry
  19171. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19172. *
  19173. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19174. *
  19175. */
  19176. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19177. THREE.Geometry.call( this );
  19178. var verts = this.vertices;
  19179. var faces = this.faces;
  19180. var uvs = this.faceVertexUvs[ 0 ];
  19181. useTris = (useTris === undefined) ? false : useTris;
  19182. var i, il, j, p;
  19183. var u, v;
  19184. var stackCount = stacks + 1;
  19185. var sliceCount = slices + 1;
  19186. for ( i = 0; i <= stacks; i ++ ) {
  19187. v = i / stacks;
  19188. for ( j = 0; j <= slices; j ++ ) {
  19189. u = j / slices;
  19190. p = func( u, v );
  19191. verts.push( p );
  19192. }
  19193. }
  19194. var a, b, c, d;
  19195. var uva, uvb, uvc, uvd;
  19196. for ( i = 0; i < stacks; i ++ ) {
  19197. for ( j = 0; j < slices; j ++ ) {
  19198. a = i * sliceCount + j;
  19199. b = i * sliceCount + j + 1;
  19200. c = (i + 1) * sliceCount + j;
  19201. d = (i + 1) * sliceCount + j + 1;
  19202. uva = new THREE.UV( j / slices, i / stacks );
  19203. uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
  19204. uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
  19205. uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19206. if ( useTris ) {
  19207. faces.push( new THREE.Face3( a, b, c ) );
  19208. faces.push( new THREE.Face3( b, d, c ) );
  19209. uvs.push( [ uva, uvb, uvc ] );
  19210. uvs.push( [ uvb, uvd, uvc ] );
  19211. } else {
  19212. faces.push( new THREE.Face4( a, b, d, c ) );
  19213. uvs.push( [ uva, uvb, uvd, uvc ] );
  19214. }
  19215. }
  19216. }
  19217. // console.log(this);
  19218. // magic bullet
  19219. // var diff = this.mergeVertices();
  19220. // console.log('removed ', diff, ' vertices by merging');
  19221. this.computeCentroids();
  19222. this.computeFaceNormals();
  19223. this.computeVertexNormals();
  19224. };
  19225. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19226. /**
  19227. * @author qiao / https://github.com/qiao
  19228. * @fileoverview This is a convex hull generator using the incremental method.
  19229. * The complexity is O(n^2) where n is the number of vertices.
  19230. * O(nlogn) algorithms do exist, but they are much more complicated.
  19231. *
  19232. * Benchmark:
  19233. *
  19234. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19235. *
  19236. * Num Vertices Time(ms)
  19237. *
  19238. * 10 1
  19239. * 20 3
  19240. * 30 19
  19241. * 40 48
  19242. * 50 107
  19243. */
  19244. THREE.ConvexGeometry = function( vertices ) {
  19245. THREE.Geometry.call( this );
  19246. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19247. for ( var i = 3; i < vertices.length; i++ ) {
  19248. addPoint( i );
  19249. }
  19250. function addPoint( vertexId ) {
  19251. var vertex = vertices[ vertexId ].clone();
  19252. var mag = vertex.length();
  19253. vertex.x += mag * randomOffset();
  19254. vertex.y += mag * randomOffset();
  19255. vertex.z += mag * randomOffset();
  19256. var hole = [];
  19257. for ( var f = 0; f < faces.length; ) {
  19258. var face = faces[ f ];
  19259. // for each face, if the vertex can see it,
  19260. // then we try to add the face's edges into the hole.
  19261. if ( visible( face, vertex ) ) {
  19262. for ( var e = 0; e < 3; e++ ) {
  19263. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19264. var boundary = true;
  19265. // remove duplicated edges.
  19266. for ( var h = 0; h < hole.length; h++ ) {
  19267. if ( equalEdge( hole[ h ], edge ) ) {
  19268. hole[ h ] = hole[ hole.length - 1 ];
  19269. hole.pop();
  19270. boundary = false;
  19271. break;
  19272. }
  19273. }
  19274. if ( boundary ) {
  19275. hole.push( edge );
  19276. }
  19277. }
  19278. // remove faces[ f ]
  19279. faces[ f ] = faces[ faces.length - 1 ];
  19280. faces.pop();
  19281. } else { // not visible
  19282. f++;
  19283. }
  19284. }
  19285. // construct the new faces formed by the edges of the hole and the vertex
  19286. for ( var h = 0; h < hole.length; h++ ) {
  19287. faces.push( [
  19288. hole[ h ][ 0 ],
  19289. hole[ h ][ 1 ],
  19290. vertexId
  19291. ] );
  19292. }
  19293. }
  19294. /**
  19295. * Whether the face is visible from the vertex
  19296. */
  19297. function visible( face, vertex ) {
  19298. var va = vertices[ face[ 0 ] ];
  19299. var vb = vertices[ face[ 1 ] ];
  19300. var vc = vertices[ face[ 2 ] ];
  19301. var n = normal( va, vb, vc );
  19302. // distance from face to origin
  19303. var dist = n.dot( va );
  19304. return n.dot( vertex ) >= dist;
  19305. }
  19306. /**
  19307. * Face normal
  19308. */
  19309. function normal( va, vb, vc ) {
  19310. var cb = new THREE.Vector3();
  19311. var ab = new THREE.Vector3();
  19312. cb.sub( vc, vb );
  19313. ab.sub( va, vb );
  19314. cb.crossSelf( ab );
  19315. cb.normalize();
  19316. return cb;
  19317. }
  19318. /**
  19319. * Detect whether two edges are equal.
  19320. * Note that when constructing the convex hull, two same edges can only
  19321. * be of the negative direction.
  19322. */
  19323. function equalEdge( ea, eb ) {
  19324. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19325. }
  19326. /**
  19327. * Create a random offset between -1e-6 and 1e-6.
  19328. */
  19329. function randomOffset() {
  19330. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19331. }
  19332. /**
  19333. * XXX: Not sure if this is the correct approach. Need someone to review.
  19334. */
  19335. function vertexUv( vertex ) {
  19336. var mag = vertex.length();
  19337. return new THREE.UV( vertex.x / mag, vertex.y / mag );
  19338. }
  19339. // Push vertices into `this.vertices`, skipping those inside the hull
  19340. var id = 0;
  19341. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19342. for ( var i = 0; i < faces.length; i++ ) {
  19343. var face = faces[ i ];
  19344. for ( var j = 0; j < 3; j++ ) {
  19345. if ( newId[ face[ j ] ] === undefined ) {
  19346. newId[ face[ j ] ] = id++;
  19347. this.vertices.push( vertices[ face[ j ] ] );
  19348. }
  19349. face[ j ] = newId[ face[ j ] ];
  19350. }
  19351. }
  19352. // Convert faces into instances of THREE.Face3
  19353. for ( var i = 0; i < faces.length; i++ ) {
  19354. this.faces.push( new THREE.Face3(
  19355. faces[ i ][ 0 ],
  19356. faces[ i ][ 1 ],
  19357. faces[ i ][ 2 ]
  19358. ) );
  19359. }
  19360. // Compute UVs
  19361. for ( var i = 0; i < this.faces.length; i++ ) {
  19362. var face = this.faces[ i ];
  19363. this.faceVertexUvs[ 0 ].push( [
  19364. vertexUv( this.vertices[ face.a ] ),
  19365. vertexUv( this.vertices[ face.b ] ),
  19366. vertexUv( this.vertices[ face.c ])
  19367. ] );
  19368. }
  19369. this.computeCentroids();
  19370. this.computeFaceNormals();
  19371. this.computeVertexNormals();
  19372. };
  19373. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19374. /**
  19375. * @author sroucheray / http://sroucheray.org/
  19376. * @author mrdoob / http://mrdoob.com/
  19377. */
  19378. THREE.AxisHelper = function ( size ) {
  19379. var geometry = new THREE.Geometry();
  19380. geometry.vertices.push(
  19381. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  19382. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  19383. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  19384. );
  19385. geometry.colors.push(
  19386. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  19387. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  19388. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  19389. );
  19390. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19391. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19392. };
  19393. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19394. /**
  19395. * @author WestLangley / http://github.com/WestLangley
  19396. * @author zz85 / https://github.com/zz85
  19397. *
  19398. * Creates an arrow for visualizing directions
  19399. *
  19400. * Parameters:
  19401. * dir - Vector3
  19402. * origin - Vector3
  19403. * length - Number
  19404. * hex - color in hex value
  19405. */
  19406. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19407. THREE.Object3D.call( this );
  19408. if ( hex === undefined ) hex = 0xffff00;
  19409. if ( length === undefined ) length = 20;
  19410. var lineGeometry = new THREE.Geometry();
  19411. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19412. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19413. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19414. this.add( this.line );
  19415. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19416. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19417. this.cone.position.set( 0, 1, 0 );
  19418. this.add( this.cone );
  19419. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19420. this.setDirection( dir );
  19421. this.setLength( length );
  19422. };
  19423. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19424. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19425. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  19426. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  19427. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  19428. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  19429. };
  19430. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19431. this.scale.set( length, length, length );
  19432. };
  19433. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  19434. this.line.material.color.setHex( hex );
  19435. this.cone.material.color.setHex( hex );
  19436. };
  19437. /**
  19438. * @author alteredq / http://alteredqualia.com/
  19439. *
  19440. * - shows frustum, line of sight and up of the camera
  19441. * - suitable for fast updates
  19442. * - based on frustum visualization in lightgl.js shadowmap example
  19443. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  19444. */
  19445. THREE.CameraHelper = function ( camera ) {
  19446. THREE.Line.call( this );
  19447. var scope = this;
  19448. this.geometry = new THREE.Geometry();
  19449. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  19450. this.type = THREE.LinePieces;
  19451. this.matrixWorld = camera.matrixWorld;
  19452. this.matrixAutoUpdate = false;
  19453. this.pointMap = {};
  19454. // colors
  19455. var hexFrustum = 0xffaa00;
  19456. var hexCone = 0xff0000;
  19457. var hexUp = 0x00aaff;
  19458. var hexTarget = 0xffffff;
  19459. var hexCross = 0x333333;
  19460. // near
  19461. addLine( "n1", "n2", hexFrustum );
  19462. addLine( "n2", "n4", hexFrustum );
  19463. addLine( "n4", "n3", hexFrustum );
  19464. addLine( "n3", "n1", hexFrustum );
  19465. // far
  19466. addLine( "f1", "f2", hexFrustum );
  19467. addLine( "f2", "f4", hexFrustum );
  19468. addLine( "f4", "f3", hexFrustum );
  19469. addLine( "f3", "f1", hexFrustum );
  19470. // sides
  19471. addLine( "n1", "f1", hexFrustum );
  19472. addLine( "n2", "f2", hexFrustum );
  19473. addLine( "n3", "f3", hexFrustum );
  19474. addLine( "n4", "f4", hexFrustum );
  19475. // cone
  19476. addLine( "p", "n1", hexCone );
  19477. addLine( "p", "n2", hexCone );
  19478. addLine( "p", "n3", hexCone );
  19479. addLine( "p", "n4", hexCone );
  19480. // up
  19481. addLine( "u1", "u2", hexUp );
  19482. addLine( "u2", "u3", hexUp );
  19483. addLine( "u3", "u1", hexUp );
  19484. // target
  19485. addLine( "c", "t", hexTarget );
  19486. addLine( "p", "c", hexCross );
  19487. // cross
  19488. addLine( "cn1", "cn2", hexCross );
  19489. addLine( "cn3", "cn4", hexCross );
  19490. addLine( "cf1", "cf2", hexCross );
  19491. addLine( "cf3", "cf4", hexCross );
  19492. this.camera = camera;
  19493. function addLine( a, b, hex ) {
  19494. addPoint( a, hex );
  19495. addPoint( b, hex );
  19496. }
  19497. function addPoint( id, hex ) {
  19498. scope.geometry.vertices.push( new THREE.Vector3() );
  19499. scope.geometry.colors.push( new THREE.Color( hex ) );
  19500. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  19501. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  19502. }
  19503. this.update( camera );
  19504. };
  19505. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  19506. THREE.CameraHelper.prototype.update = function () {
  19507. var scope = this;
  19508. var w = 1, h = 1;
  19509. // we need just camera projection matrix
  19510. // world matrix must be identity
  19511. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  19512. // center / target
  19513. setPoint( "c", 0, 0, -1 );
  19514. setPoint( "t", 0, 0, 1 );
  19515. // near
  19516. setPoint( "n1", -w, -h, -1 );
  19517. setPoint( "n2", w, -h, -1 );
  19518. setPoint( "n3", -w, h, -1 );
  19519. setPoint( "n4", w, h, -1 );
  19520. // far
  19521. setPoint( "f1", -w, -h, 1 );
  19522. setPoint( "f2", w, -h, 1 );
  19523. setPoint( "f3", -w, h, 1 );
  19524. setPoint( "f4", w, h, 1 );
  19525. // up
  19526. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  19527. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  19528. setPoint( "u3", 0, h * 2, -1 );
  19529. // cross
  19530. setPoint( "cf1", -w, 0, 1 );
  19531. setPoint( "cf2", w, 0, 1 );
  19532. setPoint( "cf3", 0, -h, 1 );
  19533. setPoint( "cf4", 0, h, 1 );
  19534. setPoint( "cn1", -w, 0, -1 );
  19535. setPoint( "cn2", w, 0, -1 );
  19536. setPoint( "cn3", 0, -h, -1 );
  19537. setPoint( "cn4", 0, h, -1 );
  19538. function setPoint( point, x, y, z ) {
  19539. THREE.CameraHelper.__v.set( x, y, z );
  19540. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  19541. var points = scope.pointMap[ point ];
  19542. if ( points !== undefined ) {
  19543. for ( var i = 0, il = points.length; i < il; i ++ ) {
  19544. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  19545. }
  19546. }
  19547. }
  19548. this.geometry.verticesNeedUpdate = true;
  19549. };
  19550. THREE.CameraHelper.__projector = new THREE.Projector();
  19551. THREE.CameraHelper.__v = new THREE.Vector3();
  19552. THREE.CameraHelper.__c = new THREE.Camera();
  19553. /**
  19554. * @author alteredq / http://alteredqualia.com/
  19555. *
  19556. * - shows directional light color, intensity, position, orientation and target
  19557. */
  19558. THREE.DirectionalLightHelper = function ( light, sphereSize, arrowLength ) {
  19559. THREE.Object3D.call( this );
  19560. this.light = light;
  19561. // position
  19562. this.position = light.position;
  19563. // direction
  19564. this.direction = new THREE.Vector3();
  19565. this.direction.sub( light.target.position, light.position );
  19566. // color
  19567. this.color = light.color.clone();
  19568. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19569. this.color.r *= intensity;
  19570. this.color.g *= intensity;
  19571. this.color.b *= intensity;
  19572. var hexColor = this.color.getHex();
  19573. // light helper
  19574. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19575. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19576. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19577. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19578. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  19579. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19580. this.lightArrow.cone.material.fog = false;
  19581. this.lightArrow.line.material.fog = false;
  19582. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19583. this.add( this.lightArrow );
  19584. this.add( this.lightSphere );
  19585. this.add( this.lightRays );
  19586. this.lightSphere.properties.isGizmo = true;
  19587. this.lightSphere.properties.gizmoSubject = light;
  19588. this.lightSphere.properties.gizmoRoot = this;
  19589. // light target helper
  19590. this.targetSphere = null;
  19591. if ( light.target.properties.targetInverse ) {
  19592. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  19593. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  19594. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  19595. this.targetSphere.position = light.target.position;
  19596. this.targetSphere.properties.isGizmo = true;
  19597. this.targetSphere.properties.gizmoSubject = light.target;
  19598. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  19599. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  19600. var lineGeometry = new THREE.Geometry();
  19601. lineGeometry.vertices.push( this.position.clone() );
  19602. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  19603. lineGeometry.computeLineDistances();
  19604. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  19605. this.targetLine.properties.isGizmo = true;
  19606. }
  19607. //
  19608. this.properties.isGizmo = true;
  19609. }
  19610. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19611. THREE.DirectionalLightHelper.prototype.update = function () {
  19612. // update arrow orientation
  19613. // pointing from light to target
  19614. this.direction.sub( this.light.target.position, this.light.position );
  19615. this.lightArrow.setDirection( this.direction );
  19616. // update arrow, spheres, rays and line colors to light color * light intensity
  19617. this.color.copy( this.light.color );
  19618. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19619. this.color.r *= intensity;
  19620. this.color.g *= intensity;
  19621. this.color.b *= intensity;
  19622. this.lightArrow.setColor( this.color.getHex() );
  19623. this.lightSphere.material.color.copy( this.color );
  19624. this.lightRays.material.color.copy( this.color );
  19625. this.targetSphere.material.color.copy( this.color );
  19626. this.targetLine.material.color.copy( this.color );
  19627. // update target line vertices
  19628. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  19629. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  19630. this.targetLine.geometry.computeLineDistances();
  19631. this.targetLine.geometry.verticesNeedUpdate = true;
  19632. }
  19633. /**
  19634. * @author alteredq / http://alteredqualia.com/
  19635. *
  19636. * - shows hemisphere light intensity, sky and ground colors and directions
  19637. */
  19638. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  19639. THREE.Object3D.call( this );
  19640. this.light = light;
  19641. // position
  19642. this.position = light.position;
  19643. //
  19644. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19645. // sky color
  19646. this.color = light.color.clone();
  19647. this.color.r *= intensity;
  19648. this.color.g *= intensity;
  19649. this.color.b *= intensity;
  19650. var hexColor = this.color.getHex();
  19651. // ground color
  19652. this.groundColor = light.groundColor.clone();
  19653. this.groundColor.r *= intensity;
  19654. this.groundColor.g *= intensity;
  19655. this.groundColor.b *= intensity;
  19656. var hexColorGround = this.groundColor.getHex();
  19657. // double colored light bulb
  19658. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  19659. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  19660. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19661. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  19662. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  19663. bulbGeometry.faces[ i ].materialIndex = 0;
  19664. }
  19665. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  19666. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  19667. }
  19668. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  19669. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  19670. // arrows for sky and ground light directions
  19671. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  19672. this.lightArrow.rotation.x = Math.PI;
  19673. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  19674. var joint = new THREE.Object3D();
  19675. joint.rotation.x = -Math.PI * 0.5;
  19676. joint.add( this.lightSphere );
  19677. joint.add( this.lightArrow );
  19678. joint.add( this.lightArrowGround );
  19679. this.add( joint );
  19680. //
  19681. this.lightSphere.properties.isGizmo = true;
  19682. this.lightSphere.properties.gizmoSubject = light;
  19683. this.lightSphere.properties.gizmoRoot = this;
  19684. //
  19685. this.properties.isGizmo = true;
  19686. //
  19687. this.target = new THREE.Vector3();
  19688. this.lookAt( this.target );
  19689. }
  19690. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19691. THREE.HemisphereLightHelper.prototype.update = function () {
  19692. // update sphere sky and ground colors to light color * light intensity
  19693. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19694. this.color.copy( this.light.color );
  19695. this.groundColor.copy( this.light.groundColor );
  19696. this.color.r *= intensity;
  19697. this.color.g *= intensity;
  19698. this.color.b *= intensity;
  19699. this.groundColor.r *= intensity;
  19700. this.groundColor.g *= intensity;
  19701. this.groundColor.b *= intensity;
  19702. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  19703. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  19704. this.lightArrow.setColor( this.color.getHex() );
  19705. this.lightArrowGround.setColor( this.groundColor.getHex() );
  19706. this.lookAt( this.target );
  19707. }
  19708. /**
  19709. * @author alteredq / http://alteredqualia.com/
  19710. *
  19711. * - shows point light color, intensity, position and distance
  19712. */
  19713. THREE.PointLightHelper = function ( light, sphereSize ) {
  19714. THREE.Object3D.call( this );
  19715. this.light = light;
  19716. // position
  19717. this.position = light.position;
  19718. // color
  19719. this.color = light.color.clone();
  19720. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19721. this.color.r *= intensity;
  19722. this.color.g *= intensity;
  19723. this.color.b *= intensity;
  19724. var hexColor = this.color.getHex();
  19725. // light helper
  19726. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19727. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19728. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  19729. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19730. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19731. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  19732. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19733. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19734. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  19735. var d = light.distance;
  19736. if ( d === 0.0 ) {
  19737. this.lightDistance.visible = false;
  19738. } else {
  19739. this.lightDistance.scale.set( d, d, d );
  19740. }
  19741. this.add( this.lightSphere );
  19742. this.add( this.lightRays );
  19743. this.add( this.lightDistance );
  19744. //
  19745. this.lightSphere.properties.isGizmo = true;
  19746. this.lightSphere.properties.gizmoSubject = light;
  19747. this.lightSphere.properties.gizmoRoot = this;
  19748. //
  19749. this.properties.isGizmo = true;
  19750. }
  19751. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19752. THREE.PointLightHelper.prototype.update = function () {
  19753. // update sphere and rays colors to light color * light intensity
  19754. this.color.copy( this.light.color );
  19755. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19756. this.color.r *= intensity;
  19757. this.color.g *= intensity;
  19758. this.color.b *= intensity;
  19759. this.lightSphere.material.color.copy( this.color );
  19760. this.lightRays.material.color.copy( this.color );
  19761. this.lightDistance.material.color.copy( this.color );
  19762. //
  19763. var d = this.light.distance;
  19764. if ( d === 0.0 ) {
  19765. this.lightDistance.visible = false;
  19766. } else {
  19767. this.lightDistance.visible = true;
  19768. this.lightDistance.scale.set( d, d, d );
  19769. }
  19770. }
  19771. /**
  19772. * @author alteredq / http://alteredqualia.com/
  19773. *
  19774. * - shows spot light color, intensity, position, orientation, light cone and target
  19775. */
  19776. THREE.SpotLightHelper = function ( light, sphereSize, arrowLength ) {
  19777. THREE.Object3D.call( this );
  19778. this.light = light;
  19779. // position
  19780. this.position = light.position;
  19781. // direction
  19782. this.direction = new THREE.Vector3();
  19783. this.direction.sub( light.target.position, light.position );
  19784. // color
  19785. this.color = light.color.clone();
  19786. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19787. this.color.r *= intensity;
  19788. this.color.g *= intensity;
  19789. this.color.b *= intensity;
  19790. var hexColor = this.color.getHex();
  19791. // light helper
  19792. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19793. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19794. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  19795. var coneMatrix = new THREE.Matrix4();
  19796. coneMatrix.rotateX( -Math.PI/2 );
  19797. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  19798. coneGeometry.applyMatrix( coneMatrix );
  19799. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19800. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19801. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  19802. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  19803. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19804. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  19805. var coneLength = light.distance ? light.distance : 10000;
  19806. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  19807. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  19808. this.lightArrow.cone.material.fog = false;
  19809. this.lightArrow.line.material.fog = false;
  19810. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19811. this.gyroscope = new THREE.Gyroscope();
  19812. this.gyroscope.add( this.lightArrow );
  19813. this.gyroscope.add( this.lightSphere );
  19814. this.gyroscope.add( this.lightRays );
  19815. this.add( this.gyroscope );
  19816. this.add( this.lightCone );
  19817. this.lookAt( light.target.position );
  19818. this.lightSphere.properties.isGizmo = true;
  19819. this.lightSphere.properties.gizmoSubject = light;
  19820. this.lightSphere.properties.gizmoRoot = this;
  19821. // light target helper
  19822. this.targetSphere = null;
  19823. if ( light.target.properties.targetInverse ) {
  19824. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  19825. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  19826. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  19827. this.targetSphere.position = light.target.position;
  19828. this.targetSphere.properties.isGizmo = true;
  19829. this.targetSphere.properties.gizmoSubject = light.target;
  19830. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  19831. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  19832. var lineGeometry = new THREE.Geometry();
  19833. lineGeometry.vertices.push( this.position.clone() );
  19834. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  19835. lineGeometry.computeLineDistances();
  19836. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  19837. this.targetLine.properties.isGizmo = true;
  19838. }
  19839. //
  19840. this.properties.isGizmo = true;
  19841. }
  19842. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19843. THREE.SpotLightHelper.prototype.update = function () {
  19844. // update arrow orientation
  19845. // pointing from light to target
  19846. this.direction.sub( this.light.target.position, this.light.position );
  19847. this.lightArrow.setDirection( this.direction );
  19848. // update light cone orientation and size
  19849. this.lookAt( this.light.target.position );
  19850. var coneLength = this.light.distance ? this.light.distance : 10000;
  19851. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  19852. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  19853. // update arrow, spheres, rays and line colors to light color * light intensity
  19854. this.color.copy( this.light.color );
  19855. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19856. this.color.r *= intensity;
  19857. this.color.g *= intensity;
  19858. this.color.b *= intensity;
  19859. this.lightArrow.setColor( this.color.getHex() );
  19860. this.lightSphere.material.color.copy( this.color );
  19861. this.lightRays.material.color.copy( this.color );
  19862. this.lightCone.material.color.copy( this.color );
  19863. this.targetSphere.material.color.copy( this.color );
  19864. this.targetLine.material.color.copy( this.color );
  19865. // update target line vertices
  19866. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  19867. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  19868. this.targetLine.geometry.computeLineDistances();
  19869. this.targetLine.geometry.verticesNeedUpdate = true;
  19870. }
  19871. /*
  19872. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19873. *
  19874. * Subdivision Geometry Modifier
  19875. * using Catmull-Clark Subdivision Surfaces
  19876. * for creating smooth geometry meshes
  19877. *
  19878. * Note: a modifier modifies vertices and faces of geometry,
  19879. * so use geometry.clone() if original geometry needs to be retained
  19880. *
  19881. * Readings:
  19882. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19883. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  19884. * http://xrt.wikidot.com/blog:31
  19885. * "Subdivision Surfaces in Character Animation"
  19886. *
  19887. * (on boundary edges)
  19888. * http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19889. * https://graphics.stanford.edu/wikis/cs148-09-summer/Assignment3Description
  19890. *
  19891. * Supports:
  19892. * Closed and Open geometries.
  19893. *
  19894. * TODO:
  19895. * crease vertex and "semi-sharp" features
  19896. * selective subdivision
  19897. */
  19898. THREE.SubdivisionModifier = function( subdivisions ) {
  19899. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  19900. // Settings
  19901. this.useOldVertexColors = false;
  19902. this.supportUVs = true;
  19903. this.debug = false;
  19904. };
  19905. // Applies the "modify" pattern
  19906. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  19907. var repeats = this.subdivisions;
  19908. while ( repeats-- > 0 ) {
  19909. this.smooth( geometry );
  19910. }
  19911. };
  19912. /// REFACTORING THIS OUT
  19913. THREE.GeometryUtils.orderedKey = function ( a, b ) {
  19914. return Math.min( a, b ) + "_" + Math.max( a, b );
  19915. };
  19916. // Returns a hashmap - of { edge_key: face_index }
  19917. THREE.GeometryUtils.computeEdgeFaces = function ( geometry ) {
  19918. var i, il, v1, v2, j, k,
  19919. face, faceIndices, faceIndex,
  19920. edge,
  19921. hash,
  19922. edgeFaceMap = {};
  19923. var orderedKey = THREE.GeometryUtils.orderedKey;
  19924. function mapEdgeHash( hash, i ) {
  19925. if ( edgeFaceMap[ hash ] === undefined ) {
  19926. edgeFaceMap[ hash ] = [];
  19927. }
  19928. edgeFaceMap[ hash ].push( i );
  19929. }
  19930. // construct vertex -> face map
  19931. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  19932. face = geometry.faces[ i ];
  19933. if ( face instanceof THREE.Face3 ) {
  19934. hash = orderedKey( face.a, face.b );
  19935. mapEdgeHash( hash, i );
  19936. hash = orderedKey( face.b, face.c );
  19937. mapEdgeHash( hash, i );
  19938. hash = orderedKey( face.c, face.a );
  19939. mapEdgeHash( hash, i );
  19940. } else if ( face instanceof THREE.Face4 ) {
  19941. hash = orderedKey( face.a, face.b );
  19942. mapEdgeHash( hash, i );
  19943. hash = orderedKey( face.b, face.c );
  19944. mapEdgeHash( hash, i );
  19945. hash = orderedKey( face.c, face.d );
  19946. mapEdgeHash( hash, i );
  19947. hash = orderedKey( face.d, face.a );
  19948. mapEdgeHash( hash, i );
  19949. }
  19950. }
  19951. // extract faces
  19952. // var edges = [];
  19953. //
  19954. // var numOfEdges = 0;
  19955. // for (i in edgeFaceMap) {
  19956. // numOfEdges++;
  19957. //
  19958. // edge = edgeFaceMap[i];
  19959. // edges.push(edge);
  19960. //
  19961. // }
  19962. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  19963. return edgeFaceMap;
  19964. }
  19965. /////////////////////////////
  19966. // Performs an iteration of Catmull-Clark Subdivision
  19967. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  19968. //debug( 'running smooth' );
  19969. // New set of vertices, faces and uvs
  19970. var newVertices = [], newFaces = [], newUVs = [];
  19971. function v( x, y, z ) {
  19972. newVertices.push( new THREE.Vector3( x, y, z ) );
  19973. }
  19974. var scope = this;
  19975. var orderedKey = THREE.GeometryUtils.orderedKey;
  19976. var computeEdgeFaces = THREE.GeometryUtils.computeEdgeFaces;
  19977. function assert() {
  19978. if (scope.debug && console && console.assert) console.assert.apply(console, arguments);
  19979. }
  19980. function debug() {
  19981. if (scope.debug) console.log.apply(console, arguments);
  19982. }
  19983. function warn() {
  19984. if (console)
  19985. console.log.apply(console, arguments);
  19986. }
  19987. function f4( a, b, c, d, oldFace, orders, facei ) {
  19988. // TODO move vertex selection over here!
  19989. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  19990. if (scope.useOldVertexColors) {
  19991. newFace.vertexColors = [];
  19992. var color, tmpColor, order;
  19993. for (var i=0;i<4;i++) {
  19994. order = orders[i];
  19995. color = new THREE.Color(),
  19996. color.setRGB(0,0,0);
  19997. for (var j=0, jl=0; j<order.length;j++) {
  19998. tmpColor = oldFace.vertexColors[order[j]-1];
  19999. color.r += tmpColor.r;
  20000. color.g += tmpColor.g;
  20001. color.b += tmpColor.b;
  20002. }
  20003. color.r /= order.length;
  20004. color.g /= order.length;
  20005. color.b /= order.length;
  20006. newFace.vertexColors[i] = color;
  20007. }
  20008. }
  20009. newFaces.push( newFace );
  20010. if (scope.supportUVs) {
  20011. var aUv = [
  20012. getUV(a, ''),
  20013. getUV(b, facei),
  20014. getUV(c, facei),
  20015. getUV(d, facei)
  20016. ];
  20017. if (!aUv[0]) debug('a :( ', a+':'+facei);
  20018. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  20019. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  20020. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  20021. else
  20022. newUVs.push( aUv );
  20023. }
  20024. }
  20025. var originalPoints = oldGeometry.vertices;
  20026. var originalFaces = oldGeometry.faces;
  20027. var originalVerticesLength = originalPoints.length;
  20028. var newPoints = originalPoints.concat(); // New set of vertices to work on
  20029. var facePoints = [], // these are new points on exisiting faces
  20030. edgePoints = {}; // these are new points on exisiting edges
  20031. var sharpEdges = {}, sharpVertices = []; // Mark edges and vertices to prevent smoothening on them
  20032. // TODO: handle this correctly.
  20033. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  20034. function debugCoreStuff() {
  20035. console.log('facePoints', facePoints, 'edgePoints', edgePoints);
  20036. console.log('edgeFaceMap', edgeFaceMap, 'vertexEdgeMap', vertexEdgeMap);
  20037. }
  20038. function getUV(vertexNo, oldFaceNo) {
  20039. var j,jl;
  20040. var key = vertexNo+':'+oldFaceNo;
  20041. var theUV = uvForVertices[key];
  20042. if (!theUV) {
  20043. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  20044. debug('face pt');
  20045. } else {
  20046. debug('edge pt');
  20047. }
  20048. warn('warning, UV not found for', key);
  20049. return null;
  20050. }
  20051. return theUV;
  20052. // Original faces -> Vertex Nos.
  20053. // new Facepoint -> Vertex Nos.
  20054. // edge Points
  20055. }
  20056. function addUV(vertexNo, oldFaceNo, value) {
  20057. var key = vertexNo+':'+oldFaceNo;
  20058. if (!(key in uvForVertices)) {
  20059. uvForVertices[key] = value;
  20060. } else {
  20061. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  20062. }
  20063. }
  20064. // Step 1
  20065. // For each face, add a face point
  20066. // Set each face point to be the centroid of all original points for the respective face.
  20067. // debug(oldGeometry);
  20068. var i, il, j, jl, face;
  20069. // For Uvs
  20070. var uvs = oldGeometry.faceVertexUvs[0];
  20071. var abcd = 'abcd', vertice;
  20072. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  20073. if (scope.supportUVs)
  20074. for (i=0, il = uvs.length; i<il; i++ ) {
  20075. for (j=0,jl=uvs[i].length;j<jl;j++) {
  20076. vertice = originalFaces[i][abcd.charAt(j)];
  20077. addUV(vertice, i, uvs[i][j]);
  20078. }
  20079. }
  20080. if (uvs.length == 0) scope.supportUVs = false;
  20081. // Additional UVs check, if we index original
  20082. var uvCount = 0;
  20083. for (var u in uvForVertices) {
  20084. uvCount++;
  20085. }
  20086. if (!uvCount) {
  20087. scope.supportUVs = false;
  20088. debug('no uvs');
  20089. }
  20090. var avgUv ;
  20091. for (i=0, il = originalFaces.length; i<il ;i++) {
  20092. face = originalFaces[ i ];
  20093. facePoints.push( face.centroid );
  20094. newPoints.push( face.centroid );
  20095. if (!scope.supportUVs) continue;
  20096. // Prepare subdivided uv
  20097. avgUv = new THREE.UV();
  20098. if ( face instanceof THREE.Face3 ) {
  20099. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  20100. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  20101. avgUv.u /= 3;
  20102. avgUv.v /= 3;
  20103. } else if ( face instanceof THREE.Face4 ) {
  20104. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  20105. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  20106. avgUv.u /= 4;
  20107. avgUv.v /= 4;
  20108. }
  20109. addUV(originalVerticesLength + i, '', avgUv);
  20110. }
  20111. // Step 2
  20112. // For each edge, add an edge point.
  20113. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  20114. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index eg { edge_key: [face_index, face_index2 ]}
  20115. var edge, faceIndexA, faceIndexB, avg;
  20116. // debug('edgeFaceMap', edgeFaceMap);
  20117. var edgeCount = 0;
  20118. var edgeVertex, edgeVertexA, edgeVertexB;
  20119. ////
  20120. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  20121. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  20122. function addVertexEdgeMap(vertex, edge) {
  20123. if (vertexEdgeMap[vertex]===undefined) {
  20124. vertexEdgeMap[vertex] = [];
  20125. }
  20126. vertexEdgeMap[vertex].push(edge);
  20127. }
  20128. function addVertexFaceMap(vertex, face, edge) {
  20129. if (vertexFaceMap[vertex]===undefined) {
  20130. vertexFaceMap[vertex] = {};
  20131. }
  20132. vertexFaceMap[vertex][face] = edge;
  20133. // vertexFaceMap[vertex][face] = null;
  20134. }
  20135. // Prepares vertexEdgeMap and vertexFaceMap
  20136. for (i in edgeFaceMap) { // This is for every edge
  20137. edge = edgeFaceMap[i];
  20138. edgeVertex = i.split('_');
  20139. edgeVertexA = edgeVertex[0];
  20140. edgeVertexB = edgeVertex[1];
  20141. // Maps an edgeVertex to connecting edges
  20142. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  20143. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  20144. for (j=0,jl=edge.length;j<jl;j++) {
  20145. face = edge[j];
  20146. addVertexFaceMap(edgeVertexA, face, i);
  20147. addVertexFaceMap(edgeVertexB, face, i);
  20148. }
  20149. // {edge vertex: { face1: edge_key, face2: edge_key.. } }
  20150. // this thing is fishy right now.
  20151. if (edge.length < 2) {
  20152. // edge is "sharp";
  20153. sharpEdges[i] = true;
  20154. sharpVertices[edgeVertexA] = true;
  20155. sharpVertices[edgeVertexB] = true;
  20156. }
  20157. }
  20158. for (i in edgeFaceMap) {
  20159. edge = edgeFaceMap[i];
  20160. faceIndexA = edge[0]; // face index a
  20161. faceIndexB = edge[1]; // face index b
  20162. edgeVertex = i.split('_');
  20163. edgeVertexA = edgeVertex[0];
  20164. edgeVertexB = edgeVertex[1];
  20165. avg = new THREE.Vector3();
  20166. //debug(i, faceIndexB,facePoints[faceIndexB]);
  20167. assert(edge.length > 0, 'an edge without faces?!');
  20168. if (edge.length==1) {
  20169. avg.addSelf(originalPoints[edgeVertexA]);
  20170. avg.addSelf(originalPoints[edgeVertexB]);
  20171. avg.multiplyScalar(0.5);
  20172. sharpVertices[newPoints.length] = true;
  20173. } else {
  20174. avg.addSelf(facePoints[faceIndexA]);
  20175. avg.addSelf(facePoints[faceIndexB]);
  20176. avg.addSelf(originalPoints[edgeVertexA]);
  20177. avg.addSelf(originalPoints[edgeVertexB]);
  20178. avg.multiplyScalar(0.25);
  20179. }
  20180. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  20181. newPoints.push( avg );
  20182. edgeCount ++;
  20183. if (!scope.supportUVs) {
  20184. continue;
  20185. }
  20186. // Prepare subdivided uv
  20187. avgUv = new THREE.UV();
  20188. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  20189. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  20190. avgUv.u /= 2;
  20191. avgUv.v /= 2;
  20192. addUV(edgePoints[i], faceIndexA, avgUv);
  20193. if (edge.length>=2) {
  20194. assert(edge.length == 2, 'did we plan for more than 2 edges?');
  20195. avgUv = new THREE.UV();
  20196. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  20197. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  20198. avgUv.u /= 2;
  20199. avgUv.v /= 2;
  20200. addUV(edgePoints[i], faceIndexB, avgUv);
  20201. }
  20202. }
  20203. debug('-- Step 2 done');
  20204. // Step 3
  20205. // For each face point, add an edge for every edge of the face,
  20206. // connecting the face point to each edge point for the face.
  20207. var facePt, currentVerticeIndex;
  20208. var hashAB, hashBC, hashCD, hashDA, hashCA;
  20209. var abc123 = ['123', '12', '2', '23'];
  20210. var bca123 = ['123', '23', '3', '31'];
  20211. var cab123 = ['123', '31', '1', '12'];
  20212. var abc1234 = ['1234', '12', '2', '23'];
  20213. var bcd1234 = ['1234', '23', '3', '34'];
  20214. var cda1234 = ['1234', '34', '4', '41'];
  20215. var dab1234 = ['1234', '41', '1', '12'];
  20216. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  20217. facePt = facePoints[i];
  20218. face = originalFaces[i];
  20219. currentVerticeIndex = originalVerticesLength+ i;
  20220. if ( face instanceof THREE.Face3 ) {
  20221. // create 3 face4s
  20222. hashAB = orderedKey( face.a, face.b );
  20223. hashBC = orderedKey( face.b, face.c );
  20224. hashCA = orderedKey( face.c, face.a );
  20225. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  20226. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  20227. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  20228. } else if ( face instanceof THREE.Face4 ) {
  20229. // create 4 face4s
  20230. hashAB = orderedKey( face.a, face.b );
  20231. hashBC = orderedKey( face.b, face.c );
  20232. hashCD = orderedKey( face.c, face.d );
  20233. hashDA = orderedKey( face.d, face.a );
  20234. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  20235. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  20236. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  20237. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  20238. } else {
  20239. debug('face should be a face!', face);
  20240. }
  20241. }
  20242. newVertices = newPoints;
  20243. // Step 4
  20244. // For each original point P,
  20245. // take the average F of all n face points for faces touching P,
  20246. // and take the average R of all n edge midpoints for edges touching P,
  20247. // where each edge midpoint is the average of its two endpoint vertices.
  20248. // Move each original point to the point
  20249. var F = new THREE.Vector3();
  20250. var R = new THREE.Vector3();
  20251. var n;
  20252. for (i=0, il = originalPoints.length; i<il; i++) {
  20253. // (F + 2R + (n-3)P) / n
  20254. if (vertexEdgeMap[i]===undefined) continue;
  20255. F.set(0,0,0);
  20256. R.set(0,0,0);
  20257. var newPos = new THREE.Vector3(0,0,0);
  20258. var f = 0; // this counts number of faces, original vertex is connected to (also known as valance?)
  20259. for (j in vertexFaceMap[i]) {
  20260. F.addSelf(facePoints[j]);
  20261. f++;
  20262. }
  20263. var sharpEdgeCount = 0;
  20264. n = vertexEdgeMap[i].length; // given a vertex, return its connecting edges
  20265. // Are we on the border?
  20266. var boundary_case = f != n;
  20267. // if (boundary_case) {
  20268. // console.error('moo', 'o', i, 'faces touched', f, 'edges', n, n == 2);
  20269. // }
  20270. for (j=0;j<n;j++) {
  20271. if (
  20272. sharpEdges[
  20273. orderedKey(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  20274. ]) {
  20275. sharpEdgeCount++;
  20276. }
  20277. }
  20278. // if ( sharpEdgeCount==2 ) {
  20279. // continue;
  20280. // // Do not move vertex if there's 2 connecting sharp edges.
  20281. // }
  20282. /*
  20283. if (sharpEdgeCount>2) {
  20284. // TODO
  20285. }
  20286. */
  20287. F.divideScalar(f);
  20288. var boundary_edges = 0;
  20289. if (boundary_case) {
  20290. var bb_edge;
  20291. for (j=0; j<n;j++) {
  20292. edge = vertexEdgeMap[i][j];
  20293. bb_edge = edgeFaceMap[orderedKey(edge[0], edge[1])].length == 1
  20294. if (bb_edge) {
  20295. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20296. R.addSelf(midPt);
  20297. boundary_edges++;
  20298. }
  20299. }
  20300. R.divideScalar(4);
  20301. // console.log(j + ' --- ' + n + ' --- ' + boundary_edges);
  20302. assert(boundary_edges == 2, 'should have only 2 boundary edges');
  20303. } else {
  20304. for (j=0; j<n;j++) {
  20305. edge = vertexEdgeMap[i][j];
  20306. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20307. R.addSelf(midPt);
  20308. }
  20309. R.divideScalar(n);
  20310. }
  20311. // Sum the formula
  20312. newPos.addSelf(originalPoints[i]);
  20313. if (boundary_case) {
  20314. newPos.divideScalar(2);
  20315. newPos.addSelf(R);
  20316. } else {
  20317. newPos.multiplyScalar(n - 3);
  20318. newPos.addSelf(F);
  20319. newPos.addSelf(R.multiplyScalar(2));
  20320. newPos.divideScalar(n);
  20321. }
  20322. newVertices[i] = newPos;
  20323. }
  20324. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  20325. newGeometry.vertices = newVertices;
  20326. newGeometry.faces = newFaces;
  20327. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  20328. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  20329. newGeometry.computeCentroids();
  20330. newGeometry.computeFaceNormals();
  20331. newGeometry.computeVertexNormals();
  20332. };
  20333. /**
  20334. * @author alteredq / http://alteredqualia.com/
  20335. */
  20336. THREE.ImmediateRenderObject = function ( ) {
  20337. THREE.Object3D.call( this );
  20338. this.render = function ( renderCallback ) { };
  20339. };
  20340. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20341. /**
  20342. * @author mikael emtinger / http://gomo.se/
  20343. * @author alteredq / http://alteredqualia.com/
  20344. */
  20345. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20346. THREE.Object3D.call( this );
  20347. this.lensFlares = [];
  20348. this.positionScreen = new THREE.Vector3();
  20349. this.customUpdateCallback = undefined;
  20350. if( texture !== undefined ) {
  20351. this.add( texture, size, distance, blending, color );
  20352. }
  20353. };
  20354. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20355. /*
  20356. * Add: adds another flare
  20357. */
  20358. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20359. if( size === undefined ) size = -1;
  20360. if( distance === undefined ) distance = 0;
  20361. if( opacity === undefined ) opacity = 1;
  20362. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20363. if( blending === undefined ) blending = THREE.NormalBlending;
  20364. distance = Math.min( distance, Math.max( 0, distance ) );
  20365. this.lensFlares.push( { texture: texture, // THREE.Texture
  20366. size: size, // size in pixels (-1 = use texture.width)
  20367. distance: distance, // distance (0-1) from light source (0=at light source)
  20368. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20369. scale: 1, // scale
  20370. rotation: 1, // rotation
  20371. opacity: opacity, // opacity
  20372. color: color, // color
  20373. blending: blending } ); // blending
  20374. };
  20375. /*
  20376. * Update lens flares update positions on all flares based on the screen position
  20377. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20378. */
  20379. THREE.LensFlare.prototype.updateLensFlares = function () {
  20380. var f, fl = this.lensFlares.length;
  20381. var flare;
  20382. var vecX = -this.positionScreen.x * 2;
  20383. var vecY = -this.positionScreen.y * 2;
  20384. for( f = 0; f < fl; f ++ ) {
  20385. flare = this.lensFlares[ f ];
  20386. flare.x = this.positionScreen.x + vecX * flare.distance;
  20387. flare.y = this.positionScreen.y + vecY * flare.distance;
  20388. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20389. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20390. }
  20391. };
  20392. /**
  20393. * @author alteredq / http://alteredqualia.com/
  20394. */
  20395. THREE.MorphBlendMesh = function( geometry, material ) {
  20396. THREE.Mesh.call( this, geometry, material );
  20397. this.animationsMap = {};
  20398. this.animationsList = [];
  20399. // prepare default animation
  20400. // (all frames played together in 1 second)
  20401. var numFrames = this.geometry.morphTargets.length;
  20402. var name = "__default";
  20403. var startFrame = 0;
  20404. var endFrame = numFrames - 1;
  20405. var fps = numFrames / 1;
  20406. this.createAnimation( name, startFrame, endFrame, fps );
  20407. this.setAnimationWeight( name, 1 );
  20408. };
  20409. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20410. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20411. var animation = {
  20412. startFrame: start,
  20413. endFrame: end,
  20414. length: end - start + 1,
  20415. fps: fps,
  20416. duration: ( end - start ) / fps,
  20417. lastFrame: 0,
  20418. currentFrame: 0,
  20419. active: false,
  20420. time: 0,
  20421. direction: 1,
  20422. weight: 1,
  20423. directionBackwards: false,
  20424. mirroredLoop: false
  20425. };
  20426. this.animationsMap[ name ] = animation;
  20427. this.animationsList.push( animation );
  20428. };
  20429. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20430. var pattern = /([a-z]+)(\d+)/;
  20431. var firstAnimation, frameRanges = {};
  20432. var geometry = this.geometry;
  20433. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20434. var morph = geometry.morphTargets[ i ];
  20435. var chunks = morph.name.match( pattern );
  20436. if ( chunks && chunks.length > 1 ) {
  20437. var name = chunks[ 1 ];
  20438. var num = chunks[ 2 ];
  20439. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20440. var range = frameRanges[ name ];
  20441. if ( i < range.start ) range.start = i;
  20442. if ( i > range.end ) range.end = i;
  20443. if ( ! firstAnimation ) firstAnimation = name;
  20444. }
  20445. }
  20446. for ( var name in frameRanges ) {
  20447. var range = frameRanges[ name ];
  20448. this.createAnimation( name, range.start, range.end, fps );
  20449. }
  20450. this.firstAnimation = firstAnimation;
  20451. };
  20452. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20453. var animation = this.animationsMap[ name ];
  20454. if ( animation ) {
  20455. animation.direction = 1;
  20456. animation.directionBackwards = false;
  20457. }
  20458. };
  20459. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20460. var animation = this.animationsMap[ name ];
  20461. if ( animation ) {
  20462. animation.direction = -1;
  20463. animation.directionBackwards = true;
  20464. }
  20465. };
  20466. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20467. var animation = this.animationsMap[ name ];
  20468. if ( animation ) {
  20469. animation.fps = fps;
  20470. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20471. }
  20472. };
  20473. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20474. var animation = this.animationsMap[ name ];
  20475. if ( animation ) {
  20476. animation.duration = duration;
  20477. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20478. }
  20479. };
  20480. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20481. var animation = this.animationsMap[ name ];
  20482. if ( animation ) {
  20483. animation.weight = weight;
  20484. }
  20485. };
  20486. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20487. var animation = this.animationsMap[ name ];
  20488. if ( animation ) {
  20489. animation.time = time;
  20490. }
  20491. };
  20492. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20493. var time = 0;
  20494. var animation = this.animationsMap[ name ];
  20495. if ( animation ) {
  20496. time = animation.time;
  20497. }
  20498. return time;
  20499. };
  20500. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20501. var duration = -1;
  20502. var animation = this.animationsMap[ name ];
  20503. if ( animation ) {
  20504. duration = animation.duration;
  20505. }
  20506. return duration;
  20507. };
  20508. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20509. var animation = this.animationsMap[ name ];
  20510. if ( animation ) {
  20511. animation.time = 0;
  20512. animation.active = true;
  20513. } else {
  20514. console.warn( "animation[" + name + "] undefined" );
  20515. }
  20516. };
  20517. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20518. var animation = this.animationsMap[ name ];
  20519. if ( animation ) {
  20520. animation.active = false;
  20521. }
  20522. };
  20523. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20524. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20525. var animation = this.animationsList[ i ];
  20526. if ( ! animation.active ) continue;
  20527. var frameTime = animation.duration / animation.length;
  20528. animation.time += animation.direction * delta;
  20529. if ( animation.mirroredLoop ) {
  20530. if ( animation.time > animation.duration || animation.time < 0 ) {
  20531. animation.direction *= -1;
  20532. if ( animation.time > animation.duration ) {
  20533. animation.time = animation.duration;
  20534. animation.directionBackwards = true;
  20535. }
  20536. if ( animation.time < 0 ) {
  20537. animation.time = 0;
  20538. animation.directionBackwards = false;
  20539. }
  20540. }
  20541. } else {
  20542. animation.time = animation.time % animation.duration;
  20543. if ( animation.time < 0 ) animation.time += animation.duration;
  20544. }
  20545. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20546. var weight = animation.weight;
  20547. if ( keyframe !== animation.currentFrame ) {
  20548. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20549. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20550. this.morphTargetInfluences[ keyframe ] = 0;
  20551. animation.lastFrame = animation.currentFrame;
  20552. animation.currentFrame = keyframe;
  20553. }
  20554. var mix = ( animation.time % frameTime ) / frameTime;
  20555. if ( animation.directionBackwards ) mix = 1 - mix;
  20556. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20557. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20558. }
  20559. };
  20560. /**
  20561. * @author mikael emtinger / http://gomo.se/
  20562. * @author alteredq / http://alteredqualia.com/
  20563. */
  20564. THREE.LensFlarePlugin = function ( ) {
  20565. var _gl, _renderer, _lensFlare = {};
  20566. this.init = function ( renderer ) {
  20567. _gl = renderer.context;
  20568. _renderer = renderer;
  20569. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20570. _lensFlare.faces = new Uint16Array( 6 );
  20571. var i = 0;
  20572. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20573. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20574. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20575. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20576. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20577. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20578. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20579. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20580. i = 0;
  20581. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20582. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20583. // buffers
  20584. _lensFlare.vertexBuffer = _gl.createBuffer();
  20585. _lensFlare.elementBuffer = _gl.createBuffer();
  20586. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20587. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20588. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20589. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20590. // textures
  20591. _lensFlare.tempTexture = _gl.createTexture();
  20592. _lensFlare.occlusionTexture = _gl.createTexture();
  20593. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20594. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20595. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20596. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20597. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20598. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20599. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20600. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20601. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20602. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20603. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20604. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20605. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20606. _lensFlare.hasVertexTexture = false;
  20607. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  20608. } else {
  20609. _lensFlare.hasVertexTexture = true;
  20610. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  20611. }
  20612. _lensFlare.attributes = {};
  20613. _lensFlare.uniforms = {};
  20614. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20615. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20616. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20617. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20618. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20619. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20620. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20621. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20622. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20623. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20624. };
  20625. /*
  20626. * Render lens flares
  20627. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20628. * reads these back and calculates occlusion.
  20629. * Then _lensFlare.update_lensFlares() is called to re-position and
  20630. * update transparency of flares. Then they are rendered.
  20631. *
  20632. */
  20633. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20634. var flares = scene.__webglFlares,
  20635. nFlares = flares.length;
  20636. if ( ! nFlares ) return;
  20637. var tempPosition = new THREE.Vector3();
  20638. var invAspect = viewportHeight / viewportWidth,
  20639. halfViewportWidth = viewportWidth * 0.5,
  20640. halfViewportHeight = viewportHeight * 0.5;
  20641. var size = 16 / viewportHeight,
  20642. scale = new THREE.Vector2( size * invAspect, size );
  20643. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20644. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20645. var uniforms = _lensFlare.uniforms,
  20646. attributes = _lensFlare.attributes;
  20647. // set _lensFlare program and reset blending
  20648. _gl.useProgram( _lensFlare.program );
  20649. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20650. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20651. // loop through all lens flares to update their occlusion and positions
  20652. // setup gl and common used attribs/unforms
  20653. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20654. _gl.uniform1i( uniforms.map, 1 );
  20655. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20656. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20657. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20658. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20659. _gl.disable( _gl.CULL_FACE );
  20660. _gl.depthMask( false );
  20661. var i, j, jl, flare, sprite;
  20662. for ( i = 0; i < nFlares; i ++ ) {
  20663. size = 16 / viewportHeight;
  20664. scale.set( size * invAspect, size );
  20665. // calc object screen position
  20666. flare = flares[ i ];
  20667. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20668. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  20669. camera.projectionMatrix.multiplyVector3( tempPosition );
  20670. // setup arrays for gl programs
  20671. screenPosition.copy( tempPosition )
  20672. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20673. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20674. // screen cull
  20675. if ( _lensFlare.hasVertexTexture || (
  20676. screenPositionPixels.x > 0 &&
  20677. screenPositionPixels.x < viewportWidth &&
  20678. screenPositionPixels.y > 0 &&
  20679. screenPositionPixels.y < viewportHeight ) ) {
  20680. // save current RGB to temp texture
  20681. _gl.activeTexture( _gl.TEXTURE1 );
  20682. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20683. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20684. // render pink quad
  20685. _gl.uniform1i( uniforms.renderType, 0 );
  20686. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20687. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20688. _gl.disable( _gl.BLEND );
  20689. _gl.enable( _gl.DEPTH_TEST );
  20690. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20691. // copy result to occlusionMap
  20692. _gl.activeTexture( _gl.TEXTURE0 );
  20693. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20694. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20695. // restore graphics
  20696. _gl.uniform1i( uniforms.renderType, 1 );
  20697. _gl.disable( _gl.DEPTH_TEST );
  20698. _gl.activeTexture( _gl.TEXTURE1 );
  20699. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20700. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20701. // update object positions
  20702. flare.positionScreen.copy( screenPosition )
  20703. if ( flare.customUpdateCallback ) {
  20704. flare.customUpdateCallback( flare );
  20705. } else {
  20706. flare.updateLensFlares();
  20707. }
  20708. // render flares
  20709. _gl.uniform1i( uniforms.renderType, 2 );
  20710. _gl.enable( _gl.BLEND );
  20711. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20712. sprite = flare.lensFlares[ j ];
  20713. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20714. screenPosition.x = sprite.x;
  20715. screenPosition.y = sprite.y;
  20716. screenPosition.z = sprite.z;
  20717. size = sprite.size * sprite.scale / viewportHeight;
  20718. scale.x = size * invAspect;
  20719. scale.y = size;
  20720. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20721. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20722. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20723. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20724. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20725. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20726. _renderer.setTexture( sprite.texture, 1 );
  20727. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20728. }
  20729. }
  20730. }
  20731. }
  20732. // restore gl
  20733. _gl.enable( _gl.CULL_FACE );
  20734. _gl.enable( _gl.DEPTH_TEST );
  20735. _gl.depthMask( true );
  20736. };
  20737. function createProgram ( shader ) {
  20738. var program = _gl.createProgram();
  20739. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20740. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20741. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20742. _gl.shaderSource( vertexShader, shader.vertexShader );
  20743. _gl.compileShader( fragmentShader );
  20744. _gl.compileShader( vertexShader );
  20745. _gl.attachShader( program, fragmentShader );
  20746. _gl.attachShader( program, vertexShader );
  20747. _gl.linkProgram( program );
  20748. return program;
  20749. };
  20750. };/**
  20751. * @author alteredq / http://alteredqualia.com/
  20752. */
  20753. THREE.ShadowMapPlugin = function ( ) {
  20754. var _gl,
  20755. _renderer,
  20756. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20757. _frustum = new THREE.Frustum(),
  20758. _projScreenMatrix = new THREE.Matrix4(),
  20759. _min = new THREE.Vector3(),
  20760. _max = new THREE.Vector3();
  20761. this.init = function ( renderer ) {
  20762. _gl = renderer.context;
  20763. _renderer = renderer;
  20764. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20765. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20766. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20767. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20768. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20769. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20770. _depthMaterial._shadowPass = true;
  20771. _depthMaterialMorph._shadowPass = true;
  20772. _depthMaterialSkin._shadowPass = true;
  20773. _depthMaterialMorphSkin._shadowPass = true;
  20774. };
  20775. this.render = function ( scene, camera ) {
  20776. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20777. this.update( scene, camera );
  20778. };
  20779. this.update = function ( scene, camera ) {
  20780. var i, il, j, jl, n,
  20781. shadowMap, shadowMatrix, shadowCamera,
  20782. program, buffer, material,
  20783. webglObject, object, light,
  20784. renderList,
  20785. lights = [],
  20786. k = 0,
  20787. fog = null;
  20788. // set GL state for depth map
  20789. _gl.clearColor( 1, 1, 1, 1 );
  20790. _gl.disable( _gl.BLEND );
  20791. _gl.enable( _gl.CULL_FACE );
  20792. _gl.frontFace( _gl.CCW );
  20793. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  20794. _gl.cullFace( _gl.FRONT );
  20795. } else {
  20796. _gl.cullFace( _gl.BACK );
  20797. }
  20798. _renderer.setDepthTest( true );
  20799. // preprocess lights
  20800. // - skip lights that are not casting shadows
  20801. // - create virtual lights for cascaded shadow maps
  20802. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20803. light = scene.__lights[ i ];
  20804. if ( ! light.castShadow ) continue;
  20805. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20806. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20807. var virtualLight;
  20808. if ( ! light.shadowCascadeArray[ n ] ) {
  20809. virtualLight = createVirtualLight( light, n );
  20810. virtualLight.originalCamera = camera;
  20811. var gyro = new THREE.Gyroscope();
  20812. gyro.position = light.shadowCascadeOffset;
  20813. gyro.add( virtualLight );
  20814. gyro.add( virtualLight.target );
  20815. camera.add( gyro );
  20816. light.shadowCascadeArray[ n ] = virtualLight;
  20817. console.log( "Created virtualLight", virtualLight );
  20818. } else {
  20819. virtualLight = light.shadowCascadeArray[ n ];
  20820. }
  20821. updateVirtualLight( light, n );
  20822. lights[ k ] = virtualLight;
  20823. k ++;
  20824. }
  20825. } else {
  20826. lights[ k ] = light;
  20827. k ++;
  20828. }
  20829. }
  20830. // render depth map
  20831. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20832. light = lights[ i ];
  20833. if ( ! light.shadowMap ) {
  20834. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  20835. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20836. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20837. light.shadowMatrix = new THREE.Matrix4();
  20838. }
  20839. if ( ! light.shadowCamera ) {
  20840. if ( light instanceof THREE.SpotLight ) {
  20841. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20842. } else if ( light instanceof THREE.DirectionalLight ) {
  20843. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20844. } else {
  20845. console.error( "Unsupported light type for shadow" );
  20846. continue;
  20847. }
  20848. scene.add( light.shadowCamera );
  20849. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20850. }
  20851. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20852. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20853. light.shadowCamera.add( light.cameraHelper );
  20854. }
  20855. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20856. updateShadowCamera( camera, light );
  20857. }
  20858. shadowMap = light.shadowMap;
  20859. shadowMatrix = light.shadowMatrix;
  20860. shadowCamera = light.shadowCamera;
  20861. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  20862. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  20863. shadowCamera.updateMatrixWorld();
  20864. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20865. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  20866. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20867. // compute shadow matrix
  20868. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20869. 0.0, 0.5, 0.0, 0.5,
  20870. 0.0, 0.0, 0.5, 0.5,
  20871. 0.0, 0.0, 0.0, 1.0 );
  20872. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  20873. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  20874. // update camera matrices and frustum
  20875. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20876. _frustum.setFromMatrix( _projScreenMatrix );
  20877. // render shadow map
  20878. _renderer.setRenderTarget( shadowMap );
  20879. _renderer.clear();
  20880. // set object matrices & frustum culling
  20881. renderList = scene.__webglObjects;
  20882. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20883. webglObject = renderList[ j ];
  20884. object = webglObject.object;
  20885. webglObject.render = false;
  20886. if ( object.visible && object.castShadow ) {
  20887. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  20888. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20889. webglObject.render = true;
  20890. }
  20891. }
  20892. }
  20893. // render regular objects
  20894. var objectMaterial, useMorphing, useSkinning;
  20895. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20896. webglObject = renderList[ j ];
  20897. if ( webglObject.render ) {
  20898. object = webglObject.object;
  20899. buffer = webglObject.buffer;
  20900. // culling is overriden globally for all objects
  20901. // while rendering depth map
  20902. // need to deal with MeshFaceMaterial somehow
  20903. // in that case just use the first of material.materials for now
  20904. // (proper solution would require to break objects by materials
  20905. // similarly to regular rendering and then set corresponding
  20906. // depth materials per each chunk instead of just once per object)
  20907. objectMaterial = getObjectMaterial( object );
  20908. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  20909. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  20910. if ( object.customDepthMaterial ) {
  20911. material = object.customDepthMaterial;
  20912. } else if ( useSkinning ) {
  20913. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  20914. } else if ( useMorphing ) {
  20915. material = _depthMaterialMorph;
  20916. } else {
  20917. material = _depthMaterial;
  20918. }
  20919. if ( buffer instanceof THREE.BufferGeometry ) {
  20920. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  20921. } else {
  20922. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  20923. }
  20924. }
  20925. }
  20926. // set matrices and render immediate objects
  20927. renderList = scene.__webglObjectsImmediate;
  20928. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20929. webglObject = renderList[ j ];
  20930. object = webglObject.object;
  20931. if ( object.visible && object.castShadow ) {
  20932. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20933. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  20934. }
  20935. }
  20936. }
  20937. // restore GL state
  20938. var clearColor = _renderer.getClearColor(),
  20939. clearAlpha = _renderer.getClearAlpha();
  20940. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20941. _gl.enable( _gl.BLEND );
  20942. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  20943. _gl.cullFace( _gl.BACK );
  20944. }
  20945. };
  20946. function createVirtualLight( light, cascade ) {
  20947. var virtualLight = new THREE.DirectionalLight();
  20948. virtualLight.isVirtual = true;
  20949. virtualLight.onlyShadow = true;
  20950. virtualLight.castShadow = true;
  20951. virtualLight.shadowCameraNear = light.shadowCameraNear;
  20952. virtualLight.shadowCameraFar = light.shadowCameraFar;
  20953. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  20954. virtualLight.shadowCameraRight = light.shadowCameraRight;
  20955. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  20956. virtualLight.shadowCameraTop = light.shadowCameraTop;
  20957. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20958. virtualLight.shadowDarkness = light.shadowDarkness;
  20959. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20960. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  20961. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  20962. virtualLight.pointsWorld = [];
  20963. virtualLight.pointsFrustum = [];
  20964. var pointsWorld = virtualLight.pointsWorld,
  20965. pointsFrustum = virtualLight.pointsFrustum;
  20966. for ( var i = 0; i < 8; i ++ ) {
  20967. pointsWorld[ i ] = new THREE.Vector3();
  20968. pointsFrustum[ i ] = new THREE.Vector3();
  20969. }
  20970. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20971. var farZ = light.shadowCascadeFarZ[ cascade ];
  20972. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  20973. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  20974. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  20975. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  20976. pointsFrustum[ 4 ].set( -1, -1, farZ );
  20977. pointsFrustum[ 5 ].set( 1, -1, farZ );
  20978. pointsFrustum[ 6 ].set( -1, 1, farZ );
  20979. pointsFrustum[ 7 ].set( 1, 1, farZ );
  20980. return virtualLight;
  20981. }
  20982. // Synchronize virtual light with the original light
  20983. function updateVirtualLight( light, cascade ) {
  20984. var virtualLight = light.shadowCascadeArray[ cascade ];
  20985. virtualLight.position.copy( light.position );
  20986. virtualLight.target.position.copy( light.target.position );
  20987. virtualLight.lookAt( virtualLight.target );
  20988. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20989. virtualLight.shadowDarkness = light.shadowDarkness;
  20990. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20991. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20992. var farZ = light.shadowCascadeFarZ[ cascade ];
  20993. var pointsFrustum = virtualLight.pointsFrustum;
  20994. pointsFrustum[ 0 ].z = nearZ;
  20995. pointsFrustum[ 1 ].z = nearZ;
  20996. pointsFrustum[ 2 ].z = nearZ;
  20997. pointsFrustum[ 3 ].z = nearZ;
  20998. pointsFrustum[ 4 ].z = farZ;
  20999. pointsFrustum[ 5 ].z = farZ;
  21000. pointsFrustum[ 6 ].z = farZ;
  21001. pointsFrustum[ 7 ].z = farZ;
  21002. }
  21003. // Fit shadow camera's ortho frustum to camera frustum
  21004. function updateShadowCamera( camera, light ) {
  21005. var shadowCamera = light.shadowCamera,
  21006. pointsFrustum = light.pointsFrustum,
  21007. pointsWorld = light.pointsWorld;
  21008. _min.set( Infinity, Infinity, Infinity );
  21009. _max.set( -Infinity, -Infinity, -Infinity );
  21010. for ( var i = 0; i < 8; i ++ ) {
  21011. var p = pointsWorld[ i ];
  21012. p.copy( pointsFrustum[ i ] );
  21013. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21014. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  21015. if ( p.x < _min.x ) _min.x = p.x;
  21016. if ( p.x > _max.x ) _max.x = p.x;
  21017. if ( p.y < _min.y ) _min.y = p.y;
  21018. if ( p.y > _max.y ) _max.y = p.y;
  21019. if ( p.z < _min.z ) _min.z = p.z;
  21020. if ( p.z > _max.z ) _max.z = p.z;
  21021. }
  21022. shadowCamera.left = _min.x;
  21023. shadowCamera.right = _max.x;
  21024. shadowCamera.top = _max.y;
  21025. shadowCamera.bottom = _min.y;
  21026. // can't really fit near/far
  21027. //shadowCamera.near = _min.z;
  21028. //shadowCamera.far = _max.z;
  21029. shadowCamera.updateProjectionMatrix();
  21030. }
  21031. // For the moment just ignore objects that have multiple materials with different animation methods
  21032. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21033. function getObjectMaterial( object ) {
  21034. return object.material instanceof THREE.MeshFaceMaterial
  21035. ? object.material.materials[ 0 ]
  21036. : object.material;
  21037. };
  21038. };
  21039. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21040. /**
  21041. * @author mikael emtinger / http://gomo.se/
  21042. * @author alteredq / http://alteredqualia.com/
  21043. */
  21044. THREE.SpritePlugin = function ( ) {
  21045. var _gl, _renderer, _sprite = {};
  21046. this.init = function ( renderer ) {
  21047. _gl = renderer.context;
  21048. _renderer = renderer;
  21049. _sprite.vertices = new Float32Array( 8 + 8 );
  21050. _sprite.faces = new Uint16Array( 6 );
  21051. var i = 0;
  21052. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21053. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21054. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21055. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21056. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21057. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21058. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21059. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21060. i = 0;
  21061. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21062. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21063. _sprite.vertexBuffer = _gl.createBuffer();
  21064. _sprite.elementBuffer = _gl.createBuffer();
  21065. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21066. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21067. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21068. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21069. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  21070. _sprite.attributes = {};
  21071. _sprite.uniforms = {};
  21072. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21073. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21074. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21075. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21076. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21077. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21078. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21079. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21080. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21081. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21082. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21083. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21084. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21085. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21086. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21087. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21088. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21089. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21090. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21091. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21092. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21093. };
  21094. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21095. var sprites = scene.__webglSprites,
  21096. nSprites = sprites.length;
  21097. if ( ! nSprites ) return;
  21098. var attributes = _sprite.attributes,
  21099. uniforms = _sprite.uniforms;
  21100. var invAspect = viewportHeight / viewportWidth;
  21101. var halfViewportWidth = viewportWidth * 0.5,
  21102. halfViewportHeight = viewportHeight * 0.5;
  21103. // setup gl
  21104. _gl.useProgram( _sprite.program );
  21105. _gl.enableVertexAttribArray( attributes.position );
  21106. _gl.enableVertexAttribArray( attributes.uv );
  21107. _gl.disable( _gl.CULL_FACE );
  21108. _gl.enable( _gl.BLEND );
  21109. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21110. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21111. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21112. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21113. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21114. _gl.activeTexture( _gl.TEXTURE0 );
  21115. _gl.uniform1i( uniforms.map, 0 );
  21116. var oldFogType = 0;
  21117. var sceneFogType = 0;
  21118. var fog = scene.fog;
  21119. if ( fog ) {
  21120. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21121. if ( fog instanceof THREE.Fog ) {
  21122. _gl.uniform1f( uniforms.fogNear, fog.near );
  21123. _gl.uniform1f( uniforms.fogFar, fog.far );
  21124. _gl.uniform1i( uniforms.fogType, 1 );
  21125. oldFogType = 1;
  21126. sceneFogType = 1;
  21127. } else if ( fog instanceof THREE.FogExp2 ) {
  21128. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21129. _gl.uniform1i( uniforms.fogType, 2 );
  21130. oldFogType = 2;
  21131. sceneFogType = 2;
  21132. }
  21133. } else {
  21134. _gl.uniform1i( uniforms.fogType, 0 );
  21135. oldFogType = 0;
  21136. sceneFogType = 0;
  21137. }
  21138. // update positions and sort
  21139. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21140. for( i = 0; i < nSprites; i ++ ) {
  21141. sprite = sprites[ i ];
  21142. material = sprite.material;
  21143. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21144. if ( ! material.useScreenCoordinates ) {
  21145. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  21146. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21147. } else {
  21148. sprite.z = - sprite.position.z;
  21149. }
  21150. }
  21151. sprites.sort( painterSortStable );
  21152. // render all sprites
  21153. for( i = 0; i < nSprites; i ++ ) {
  21154. sprite = sprites[ i ];
  21155. material = sprite.material;
  21156. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21157. if ( material.map && material.map.image && material.map.image.width ) {
  21158. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21159. if ( material.useScreenCoordinates ) {
  21160. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21161. _gl.uniform3f(
  21162. uniforms.screenPosition,
  21163. ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  21164. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  21165. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21166. );
  21167. } else {
  21168. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21169. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21170. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21171. }
  21172. if ( scene.fog && material.fog ) {
  21173. fogType = sceneFogType;
  21174. } else {
  21175. fogType = 0;
  21176. }
  21177. if ( oldFogType !== fogType ) {
  21178. _gl.uniform1i( uniforms.fogType, fogType );
  21179. oldFogType = fogType;
  21180. }
  21181. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21182. scale[ 0 ] = size * invAspect * sprite.scale.x;
  21183. scale[ 1 ] = size * sprite.scale.y;
  21184. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21185. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21186. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21187. _gl.uniform1f( uniforms.opacity, material.opacity );
  21188. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21189. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21190. _gl.uniform2fv( uniforms.scale, scale );
  21191. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21192. _renderer.setDepthTest( material.depthTest );
  21193. _renderer.setDepthWrite( material.depthWrite );
  21194. _renderer.setTexture( material.map, 0 );
  21195. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21196. }
  21197. }
  21198. // restore gl
  21199. _gl.enable( _gl.CULL_FACE );
  21200. };
  21201. function createProgram ( shader ) {
  21202. var program = _gl.createProgram();
  21203. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21204. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21205. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21206. _gl.shaderSource( vertexShader, shader.vertexShader );
  21207. _gl.compileShader( fragmentShader );
  21208. _gl.compileShader( vertexShader );
  21209. _gl.attachShader( program, fragmentShader );
  21210. _gl.attachShader( program, vertexShader );
  21211. _gl.linkProgram( program );
  21212. return program;
  21213. };
  21214. function painterSortStable ( a, b ) {
  21215. if ( a.z !== b.z ) {
  21216. return b.z - a.z;
  21217. } else {
  21218. return b.id - a.id;
  21219. }
  21220. };
  21221. };/**
  21222. * @author alteredq / http://alteredqualia.com/
  21223. */
  21224. THREE.DepthPassPlugin = function ( ) {
  21225. this.enabled = false;
  21226. this.renderTarget = null;
  21227. var _gl,
  21228. _renderer,
  21229. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21230. _frustum = new THREE.Frustum(),
  21231. _projScreenMatrix = new THREE.Matrix4();
  21232. this.init = function ( renderer ) {
  21233. _gl = renderer.context;
  21234. _renderer = renderer;
  21235. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21236. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21237. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21238. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21239. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21240. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21241. _depthMaterial._shadowPass = true;
  21242. _depthMaterialMorph._shadowPass = true;
  21243. _depthMaterialSkin._shadowPass = true;
  21244. _depthMaterialMorphSkin._shadowPass = true;
  21245. };
  21246. this.render = function ( scene, camera ) {
  21247. if ( ! this.enabled ) return;
  21248. this.update( scene, camera );
  21249. };
  21250. this.update = function ( scene, camera ) {
  21251. var i, il, j, jl, n,
  21252. program, buffer, material,
  21253. webglObject, object, light,
  21254. renderList,
  21255. fog = null;
  21256. // set GL state for depth map
  21257. _gl.clearColor( 1, 1, 1, 1 );
  21258. _gl.disable( _gl.BLEND );
  21259. _renderer.setDepthTest( true );
  21260. // update scene
  21261. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21262. // update camera matrices and frustum
  21263. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21264. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21265. _frustum.setFromMatrix( _projScreenMatrix );
  21266. // render depth map
  21267. _renderer.setRenderTarget( this.renderTarget );
  21268. _renderer.clear();
  21269. // set object matrices & frustum culling
  21270. renderList = scene.__webglObjects;
  21271. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21272. webglObject = renderList[ j ];
  21273. object = webglObject.object;
  21274. webglObject.render = false;
  21275. if ( object.visible ) {
  21276. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21277. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21278. webglObject.render = true;
  21279. }
  21280. }
  21281. }
  21282. // render regular objects
  21283. var objectMaterial, useMorphing, useSkinning;
  21284. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21285. webglObject = renderList[ j ];
  21286. if ( webglObject.render ) {
  21287. object = webglObject.object;
  21288. buffer = webglObject.buffer;
  21289. // todo: create proper depth material for particles
  21290. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21291. objectMaterial = getObjectMaterial( object );
  21292. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21293. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21294. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21295. if ( object.customDepthMaterial ) {
  21296. material = object.customDepthMaterial;
  21297. } else if ( useSkinning ) {
  21298. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21299. } else if ( useMorphing ) {
  21300. material = _depthMaterialMorph;
  21301. } else {
  21302. material = _depthMaterial;
  21303. }
  21304. if ( buffer instanceof THREE.BufferGeometry ) {
  21305. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21306. } else {
  21307. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21308. }
  21309. }
  21310. }
  21311. // set matrices and render immediate objects
  21312. renderList = scene.__webglObjectsImmediate;
  21313. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21314. webglObject = renderList[ j ];
  21315. object = webglObject.object;
  21316. if ( object.visible ) {
  21317. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21318. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21319. }
  21320. }
  21321. // restore GL state
  21322. var clearColor = _renderer.getClearColor(),
  21323. clearAlpha = _renderer.getClearAlpha();
  21324. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21325. _gl.enable( _gl.BLEND );
  21326. };
  21327. // For the moment just ignore objects that have multiple materials with different animation methods
  21328. // Only the first material will be taken into account for deciding which depth material to use
  21329. function getObjectMaterial( object ) {
  21330. return object.material instanceof THREE.MeshFaceMaterial
  21331. ? object.material.materials[ 0 ]
  21332. : object.material;
  21333. };
  21334. };
  21335. /**
  21336. * @author mikael emtinger / http://gomo.se/
  21337. *
  21338. */
  21339. THREE.ShaderFlares = {
  21340. 'lensFlareVertexTexture': {
  21341. vertexShader: [
  21342. "uniform vec3 screenPosition;",
  21343. "uniform vec2 scale;",
  21344. "uniform float rotation;",
  21345. "uniform int renderType;",
  21346. "uniform sampler2D occlusionMap;",
  21347. "attribute vec2 position;",
  21348. "attribute vec2 uv;",
  21349. "varying vec2 vUV;",
  21350. "varying float vVisibility;",
  21351. "void main() {",
  21352. "vUV = uv;",
  21353. "vec2 pos = position;",
  21354. "if( renderType == 2 ) {",
  21355. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21356. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21357. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21358. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21359. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21360. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21361. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21362. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21363. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21364. "vVisibility = ( visibility.r / 9.0 ) *",
  21365. "( 1.0 - visibility.g / 9.0 ) *",
  21366. "( visibility.b / 9.0 ) *",
  21367. "( 1.0 - visibility.a / 9.0 );",
  21368. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21369. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21370. "}",
  21371. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21372. "}"
  21373. ].join( "\n" ),
  21374. fragmentShader: [
  21375. "precision mediump float;",
  21376. "uniform sampler2D map;",
  21377. "uniform float opacity;",
  21378. "uniform int renderType;",
  21379. "uniform vec3 color;",
  21380. "varying vec2 vUV;",
  21381. "varying float vVisibility;",
  21382. "void main() {",
  21383. // pink square
  21384. "if( renderType == 0 ) {",
  21385. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21386. // restore
  21387. "} else if( renderType == 1 ) {",
  21388. "gl_FragColor = texture2D( map, vUV );",
  21389. // flare
  21390. "} else {",
  21391. "vec4 texture = texture2D( map, vUV );",
  21392. "texture.a *= opacity * vVisibility;",
  21393. "gl_FragColor = texture;",
  21394. "gl_FragColor.rgb *= color;",
  21395. "}",
  21396. "}"
  21397. ].join( "\n" )
  21398. },
  21399. 'lensFlare': {
  21400. vertexShader: [
  21401. "uniform vec3 screenPosition;",
  21402. "uniform vec2 scale;",
  21403. "uniform float rotation;",
  21404. "uniform int renderType;",
  21405. "attribute vec2 position;",
  21406. "attribute vec2 uv;",
  21407. "varying vec2 vUV;",
  21408. "void main() {",
  21409. "vUV = uv;",
  21410. "vec2 pos = position;",
  21411. "if( renderType == 2 ) {",
  21412. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21413. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21414. "}",
  21415. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21416. "}"
  21417. ].join( "\n" ),
  21418. fragmentShader: [
  21419. "precision mediump float;",
  21420. "uniform sampler2D map;",
  21421. "uniform sampler2D occlusionMap;",
  21422. "uniform float opacity;",
  21423. "uniform int renderType;",
  21424. "uniform vec3 color;",
  21425. "varying vec2 vUV;",
  21426. "void main() {",
  21427. // pink square
  21428. "if( renderType == 0 ) {",
  21429. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21430. // restore
  21431. "} else if( renderType == 1 ) {",
  21432. "gl_FragColor = texture2D( map, vUV );",
  21433. // flare
  21434. "} else {",
  21435. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21436. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21437. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21438. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21439. "visibility = ( 1.0 - visibility / 4.0 );",
  21440. "vec4 texture = texture2D( map, vUV );",
  21441. "texture.a *= opacity * visibility;",
  21442. "gl_FragColor = texture;",
  21443. "gl_FragColor.rgb *= color;",
  21444. "}",
  21445. "}"
  21446. ].join( "\n" )
  21447. }
  21448. };
  21449. /**
  21450. * @author mikael emtinger / http://gomo.se/
  21451. * @author alteredq / http://alteredqualia.com/
  21452. *
  21453. */
  21454. THREE.ShaderSprite = {
  21455. 'sprite': {
  21456. vertexShader: [
  21457. "uniform int useScreenCoordinates;",
  21458. "uniform int sizeAttenuation;",
  21459. "uniform vec3 screenPosition;",
  21460. "uniform mat4 modelViewMatrix;",
  21461. "uniform mat4 projectionMatrix;",
  21462. "uniform float rotation;",
  21463. "uniform vec2 scale;",
  21464. "uniform vec2 alignment;",
  21465. "uniform vec2 uvOffset;",
  21466. "uniform vec2 uvScale;",
  21467. "attribute vec2 position;",
  21468. "attribute vec2 uv;",
  21469. "varying vec2 vUV;",
  21470. "void main() {",
  21471. "vUV = uvOffset + uv * uvScale;",
  21472. "vec2 alignedPosition = position + alignment;",
  21473. "vec2 rotatedPosition;",
  21474. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21475. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21476. "vec4 finalPosition;",
  21477. "if( useScreenCoordinates != 0 ) {",
  21478. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21479. "} else {",
  21480. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21481. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21482. "}",
  21483. "gl_Position = finalPosition;",
  21484. "}"
  21485. ].join( "\n" ),
  21486. fragmentShader: [
  21487. "precision mediump float;",
  21488. "uniform vec3 color;",
  21489. "uniform sampler2D map;",
  21490. "uniform float opacity;",
  21491. "uniform int fogType;",
  21492. "uniform vec3 fogColor;",
  21493. "uniform float fogDensity;",
  21494. "uniform float fogNear;",
  21495. "uniform float fogFar;",
  21496. "uniform float alphaTest;",
  21497. "varying vec2 vUV;",
  21498. "void main() {",
  21499. "vec4 texture = texture2D( map, vUV );",
  21500. "if ( texture.a < alphaTest ) discard;",
  21501. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21502. "if ( fogType > 0 ) {",
  21503. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21504. "float fogFactor = 0.0;",
  21505. "if ( fogType == 1 ) {",
  21506. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21507. "} else {",
  21508. "const float LOG2 = 1.442695;",
  21509. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21510. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21511. "}",
  21512. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21513. "}",
  21514. "}"
  21515. ].join( "\n" )
  21516. }
  21517. };