three.js 807 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. * @author bhouston / http://exocortex.com
  5. */
  6. var THREE = THREE || { REVISION: '59dev' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. self.Int32Array = self.Int32Array || Array;
  15. self.Float32Array = self.Float32Array || Array;
  16. String.prototype.trim = String.prototype.trim || function () {
  17. return this.replace( /^\s+|\s+$/g, '' );
  18. };
  19. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  20. THREE.extend = function ( obj, source ) {
  21. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  22. if ( Object.keys ) {
  23. var keys = Object.keys( source );
  24. for (var i = 0, il = keys.length; i < il; i++) {
  25. var prop = keys[i];
  26. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  27. }
  28. } else {
  29. var safeHasOwnProperty = {}.hasOwnProperty;
  30. for ( var prop in source ) {
  31. if ( safeHasOwnProperty.call( source, prop ) ) {
  32. obj[prop] = source[prop];
  33. }
  34. }
  35. }
  36. return obj;
  37. };
  38. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  39. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  40. // requestAnimationFrame polyfill by Erik Möller
  41. // fixes from Paul Irish and Tino Zijdel
  42. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  43. ( function () {
  44. var lastTime = 0;
  45. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  46. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  47. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  48. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  49. }
  50. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  51. self.requestAnimationFrame = function ( callback ) {
  52. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  53. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  54. lastTime = currTime + timeToCall;
  55. return id;
  56. };
  57. }
  58. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  59. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  60. }
  61. }() );
  62. // GL STATE CONSTANTS
  63. THREE.CullFaceNone = 0;
  64. THREE.CullFaceBack = 1;
  65. THREE.CullFaceFront = 2;
  66. THREE.CullFaceFrontBack = 3;
  67. THREE.FrontFaceDirectionCW = 0;
  68. THREE.FrontFaceDirectionCCW = 1;
  69. // SHADOWING TYPES
  70. THREE.BasicShadowMap = 0;
  71. THREE.PCFShadowMap = 1;
  72. THREE.PCFSoftShadowMap = 2;
  73. // MATERIAL CONSTANTS
  74. // side
  75. THREE.FrontSide = 0;
  76. THREE.BackSide = 1;
  77. THREE.DoubleSide = 2;
  78. // shading
  79. THREE.NoShading = 0;
  80. THREE.FlatShading = 1;
  81. THREE.SmoothShading = 2;
  82. // colors
  83. THREE.NoColors = 0;
  84. THREE.FaceColors = 1;
  85. THREE.VertexColors = 2;
  86. // blending modes
  87. THREE.NoBlending = 0;
  88. THREE.NormalBlending = 1;
  89. THREE.AdditiveBlending = 2;
  90. THREE.SubtractiveBlending = 3;
  91. THREE.MultiplyBlending = 4;
  92. THREE.CustomBlending = 5;
  93. // custom blending equations
  94. // (numbers start from 100 not to clash with other
  95. // mappings to OpenGL constants defined in Texture.js)
  96. THREE.AddEquation = 100;
  97. THREE.SubtractEquation = 101;
  98. THREE.ReverseSubtractEquation = 102;
  99. // custom blending destination factors
  100. THREE.ZeroFactor = 200;
  101. THREE.OneFactor = 201;
  102. THREE.SrcColorFactor = 202;
  103. THREE.OneMinusSrcColorFactor = 203;
  104. THREE.SrcAlphaFactor = 204;
  105. THREE.OneMinusSrcAlphaFactor = 205;
  106. THREE.DstAlphaFactor = 206;
  107. THREE.OneMinusDstAlphaFactor = 207;
  108. // custom blending source factors
  109. //THREE.ZeroFactor = 200;
  110. //THREE.OneFactor = 201;
  111. //THREE.SrcAlphaFactor = 204;
  112. //THREE.OneMinusSrcAlphaFactor = 205;
  113. //THREE.DstAlphaFactor = 206;
  114. //THREE.OneMinusDstAlphaFactor = 207;
  115. THREE.DstColorFactor = 208;
  116. THREE.OneMinusDstColorFactor = 209;
  117. THREE.SrcAlphaSaturateFactor = 210;
  118. // TEXTURE CONSTANTS
  119. THREE.MultiplyOperation = 0;
  120. THREE.MixOperation = 1;
  121. THREE.AddOperation = 2;
  122. // Mapping modes
  123. THREE.UVMapping = function () {};
  124. THREE.CubeReflectionMapping = function () {};
  125. THREE.CubeRefractionMapping = function () {};
  126. THREE.SphericalReflectionMapping = function () {};
  127. THREE.SphericalRefractionMapping = function () {};
  128. // Wrapping modes
  129. THREE.RepeatWrapping = 1000;
  130. THREE.ClampToEdgeWrapping = 1001;
  131. THREE.MirroredRepeatWrapping = 1002;
  132. // Filters
  133. THREE.NearestFilter = 1003;
  134. THREE.NearestMipMapNearestFilter = 1004;
  135. THREE.NearestMipMapLinearFilter = 1005;
  136. THREE.LinearFilter = 1006;
  137. THREE.LinearMipMapNearestFilter = 1007;
  138. THREE.LinearMipMapLinearFilter = 1008;
  139. // Data types
  140. THREE.UnsignedByteType = 1009;
  141. THREE.ByteType = 1010;
  142. THREE.ShortType = 1011;
  143. THREE.UnsignedShortType = 1012;
  144. THREE.IntType = 1013;
  145. THREE.UnsignedIntType = 1014;
  146. THREE.FloatType = 1015;
  147. // Pixel types
  148. //THREE.UnsignedByteType = 1009;
  149. THREE.UnsignedShort4444Type = 1016;
  150. THREE.UnsignedShort5551Type = 1017;
  151. THREE.UnsignedShort565Type = 1018;
  152. // Pixel formats
  153. THREE.AlphaFormat = 1019;
  154. THREE.RGBFormat = 1020;
  155. THREE.RGBAFormat = 1021;
  156. THREE.LuminanceFormat = 1022;
  157. THREE.LuminanceAlphaFormat = 1023;
  158. // Compressed texture formats
  159. THREE.RGB_S3TC_DXT1_Format = 2001;
  160. THREE.RGBA_S3TC_DXT1_Format = 2002;
  161. THREE.RGBA_S3TC_DXT3_Format = 2003;
  162. THREE.RGBA_S3TC_DXT5_Format = 2004;
  163. /*
  164. // Potential future PVRTC compressed texture formats
  165. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  166. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  167. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  168. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  169. */
  170. /**
  171. * @author mrdoob / http://mrdoob.com/
  172. */
  173. THREE.Color = function ( value ) {
  174. if ( value !== undefined ) this.set( value );
  175. return this;
  176. };
  177. THREE.Color.prototype = {
  178. constructor: THREE.Color,
  179. r: 1, g: 1, b: 1,
  180. set: function ( value ) {
  181. if ( value instanceof THREE.Color ) {
  182. this.copy( value );
  183. } else if ( typeof value === 'number' ) {
  184. this.setHex( value );
  185. } else if ( typeof value === 'string' ) {
  186. this.setStyle( value );
  187. }
  188. return this;
  189. },
  190. setHex: function ( hex ) {
  191. hex = Math.floor( hex );
  192. this.r = ( hex >> 16 & 255 ) / 255;
  193. this.g = ( hex >> 8 & 255 ) / 255;
  194. this.b = ( hex & 255 ) / 255;
  195. return this;
  196. },
  197. setRGB: function ( r, g, b ) {
  198. this.r = r;
  199. this.g = g;
  200. this.b = b;
  201. return this;
  202. },
  203. setHSL: function ( h, s, l ) {
  204. // h,s,l ranges are in 0.0 - 1.0
  205. if ( s === 0 ) {
  206. this.r = this.g = this.b = l;
  207. } else {
  208. var hue2rgb = function ( p, q, t ) {
  209. if ( t < 0 ) t += 1;
  210. if ( t > 1 ) t -= 1;
  211. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  212. if ( t < 1 / 2 ) return q;
  213. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  214. return p;
  215. };
  216. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  217. var q = ( 2 * l ) - p;
  218. this.r = hue2rgb( q, p, h + 1 / 3 );
  219. this.g = hue2rgb( q, p, h );
  220. this.b = hue2rgb( q, p, h - 1 / 3 );
  221. }
  222. return this;
  223. },
  224. setStyle: function ( style ) {
  225. // rgb(255,0,0)
  226. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  227. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  228. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  229. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  230. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  231. return this;
  232. }
  233. // rgb(100%,0%,0%)
  234. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  235. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  236. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  237. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  238. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  239. return this;
  240. }
  241. // #ff0000
  242. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  243. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  244. this.setHex( parseInt( color[ 1 ], 16 ) );
  245. return this;
  246. }
  247. // #f00
  248. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  249. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  250. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  251. return this;
  252. }
  253. // red
  254. if ( /^(\w+)$/i.test( style ) ) {
  255. this.setHex( THREE.ColorKeywords[ style ] );
  256. return this;
  257. }
  258. },
  259. copy: function ( color ) {
  260. this.r = color.r;
  261. this.g = color.g;
  262. this.b = color.b;
  263. return this;
  264. },
  265. copyGammaToLinear: function ( color ) {
  266. this.r = color.r * color.r;
  267. this.g = color.g * color.g;
  268. this.b = color.b * color.b;
  269. return this;
  270. },
  271. copyLinearToGamma: function ( color ) {
  272. this.r = Math.sqrt( color.r );
  273. this.g = Math.sqrt( color.g );
  274. this.b = Math.sqrt( color.b );
  275. return this;
  276. },
  277. convertGammaToLinear: function () {
  278. var r = this.r, g = this.g, b = this.b;
  279. this.r = r * r;
  280. this.g = g * g;
  281. this.b = b * b;
  282. return this;
  283. },
  284. convertLinearToGamma: function () {
  285. this.r = Math.sqrt( this.r );
  286. this.g = Math.sqrt( this.g );
  287. this.b = Math.sqrt( this.b );
  288. return this;
  289. },
  290. getHex: function () {
  291. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  292. },
  293. getHexString: function () {
  294. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  295. },
  296. getHSL: function () {
  297. var hsl = { h: 0, s: 0, l: 0 };
  298. return function () {
  299. // h,s,l ranges are in 0.0 - 1.0
  300. var r = this.r, g = this.g, b = this.b;
  301. var max = Math.max( r, g, b );
  302. var min = Math.min( r, g, b );
  303. var hue, saturation;
  304. var lightness = ( min + max ) / 2.0;
  305. if ( min === max ) {
  306. hue = 0;
  307. saturation = 0;
  308. } else {
  309. var delta = max - min;
  310. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  311. switch ( max ) {
  312. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  313. case g: hue = ( b - r ) / delta + 2; break;
  314. case b: hue = ( r - g ) / delta + 4; break;
  315. }
  316. hue /= 6;
  317. }
  318. hsl.h = hue;
  319. hsl.s = saturation;
  320. hsl.l = lightness;
  321. return hsl;
  322. };
  323. }(),
  324. getStyle: function () {
  325. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  326. },
  327. offsetHSL: function ( h, s, l ) {
  328. var hsl = this.getHSL();
  329. hsl.h += h; hsl.s += s; hsl.l += l;
  330. this.setHSL( hsl.h, hsl.s, hsl.l );
  331. return this;
  332. },
  333. add: function ( color ) {
  334. this.r += color.r;
  335. this.g += color.g;
  336. this.b += color.b;
  337. return this;
  338. },
  339. addColors: function ( color1, color2 ) {
  340. this.r = color1.r + color2.r;
  341. this.g = color1.g + color2.g;
  342. this.b = color1.b + color2.b;
  343. return this;
  344. },
  345. addScalar: function ( s ) {
  346. this.r += s;
  347. this.g += s;
  348. this.b += s;
  349. return this;
  350. },
  351. multiply: function ( color ) {
  352. this.r *= color.r;
  353. this.g *= color.g;
  354. this.b *= color.b;
  355. return this;
  356. },
  357. multiplyScalar: function ( s ) {
  358. this.r *= s;
  359. this.g *= s;
  360. this.b *= s;
  361. return this;
  362. },
  363. lerp: function ( color, alpha ) {
  364. this.r += ( color.r - this.r ) * alpha;
  365. this.g += ( color.g - this.g ) * alpha;
  366. this.b += ( color.b - this.b ) * alpha;
  367. return this;
  368. },
  369. equals: function ( c ) {
  370. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  371. },
  372. clone: function () {
  373. return new THREE.Color().setRGB( this.r, this.g, this.b );
  374. }
  375. };
  376. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  377. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  378. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  379. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  380. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  381. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  382. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  383. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  384. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  385. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  386. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  387. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  388. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  389. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  390. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  391. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  392. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  393. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  394. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  395. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  396. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  397. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  398. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  399. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  400. /**
  401. * @author mikael emtinger / http://gomo.se/
  402. * @author alteredq / http://alteredqualia.com/
  403. * @author WestLangley / http://github.com/WestLangley
  404. * @author bhouston / http://exocortex.com
  405. */
  406. THREE.Quaternion = function( x, y, z, w ) {
  407. this.x = x || 0;
  408. this.y = y || 0;
  409. this.z = z || 0;
  410. this.w = ( w !== undefined ) ? w : 1;
  411. };
  412. THREE.Quaternion.prototype = {
  413. constructor: THREE.Quaternion,
  414. set: function ( x, y, z, w ) {
  415. this.x = x;
  416. this.y = y;
  417. this.z = z;
  418. this.w = w;
  419. return this;
  420. },
  421. copy: function ( q ) {
  422. this.x = q.x;
  423. this.y = q.y;
  424. this.z = q.z;
  425. this.w = q.w;
  426. return this;
  427. },
  428. setFromEuler: function ( v, order ) {
  429. // http://www.mathworks.com/matlabcentral/fileexchange/
  430. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  431. // content/SpinCalc.m
  432. var c1 = Math.cos( v.x / 2 );
  433. var c2 = Math.cos( v.y / 2 );
  434. var c3 = Math.cos( v.z / 2 );
  435. var s1 = Math.sin( v.x / 2 );
  436. var s2 = Math.sin( v.y / 2 );
  437. var s3 = Math.sin( v.z / 2 );
  438. if ( order === undefined || order === 'XYZ' ) {
  439. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  440. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  441. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  442. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  443. } else if ( order === 'YXZ' ) {
  444. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  445. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  446. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  447. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  448. } else if ( order === 'ZXY' ) {
  449. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  450. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  451. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  452. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  453. } else if ( order === 'ZYX' ) {
  454. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  455. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  456. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  457. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  458. } else if ( order === 'YZX' ) {
  459. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  460. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  461. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  462. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  463. } else if ( order === 'XZY' ) {
  464. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  465. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  466. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  467. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  468. }
  469. return this;
  470. },
  471. setFromAxisAngle: function ( axis, angle ) {
  472. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  473. // axis have to be normalized
  474. var halfAngle = angle / 2,
  475. s = Math.sin( halfAngle );
  476. this.x = axis.x * s;
  477. this.y = axis.y * s;
  478. this.z = axis.z * s;
  479. this.w = Math.cos( halfAngle );
  480. return this;
  481. },
  482. setFromRotationMatrix: function ( m ) {
  483. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  484. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  485. var te = m.elements,
  486. m11 = te[0], m12 = te[4], m13 = te[8],
  487. m21 = te[1], m22 = te[5], m23 = te[9],
  488. m31 = te[2], m32 = te[6], m33 = te[10],
  489. trace = m11 + m22 + m33,
  490. s;
  491. if ( trace > 0 ) {
  492. s = 0.5 / Math.sqrt( trace + 1.0 );
  493. this.w = 0.25 / s;
  494. this.x = ( m32 - m23 ) * s;
  495. this.y = ( m13 - m31 ) * s;
  496. this.z = ( m21 - m12 ) * s;
  497. } else if ( m11 > m22 && m11 > m33 ) {
  498. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  499. this.w = (m32 - m23 ) / s;
  500. this.x = 0.25 * s;
  501. this.y = (m12 + m21 ) / s;
  502. this.z = (m13 + m31 ) / s;
  503. } else if ( m22 > m33 ) {
  504. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  505. this.w = (m13 - m31 ) / s;
  506. this.x = (m12 + m21 ) / s;
  507. this.y = 0.25 * s;
  508. this.z = (m23 + m32 ) / s;
  509. } else {
  510. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  511. this.w = ( m21 - m12 ) / s;
  512. this.x = ( m13 + m31 ) / s;
  513. this.y = ( m23 + m32 ) / s;
  514. this.z = 0.25 * s;
  515. }
  516. return this;
  517. },
  518. inverse: function () {
  519. this.conjugate().normalize();
  520. return this;
  521. },
  522. conjugate: function () {
  523. this.x *= -1;
  524. this.y *= -1;
  525. this.z *= -1;
  526. return this;
  527. },
  528. lengthSq: function () {
  529. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  530. },
  531. length: function () {
  532. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  533. },
  534. normalize: function () {
  535. var l = this.length();
  536. if ( l === 0 ) {
  537. this.x = 0;
  538. this.y = 0;
  539. this.z = 0;
  540. this.w = 1;
  541. } else {
  542. l = 1 / l;
  543. this.x = this.x * l;
  544. this.y = this.y * l;
  545. this.z = this.z * l;
  546. this.w = this.w * l;
  547. }
  548. return this;
  549. },
  550. multiply: function ( q, p ) {
  551. if ( p !== undefined ) {
  552. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  553. return this.multiplyQuaternions( q, p );
  554. }
  555. return this.multiplyQuaternions( this, q );
  556. },
  557. multiplyQuaternions: function ( a, b ) {
  558. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  559. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  560. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  561. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  562. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  563. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  564. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  565. return this;
  566. },
  567. multiplyVector3: function ( vector ) {
  568. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  569. return vector.applyQuaternion( this );
  570. },
  571. slerp: function ( qb, t ) {
  572. var x = this.x, y = this.y, z = this.z, w = this.w;
  573. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  574. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  575. if ( cosHalfTheta < 0 ) {
  576. this.w = -qb.w;
  577. this.x = -qb.x;
  578. this.y = -qb.y;
  579. this.z = -qb.z;
  580. cosHalfTheta = -cosHalfTheta;
  581. } else {
  582. this.copy( qb );
  583. }
  584. if ( cosHalfTheta >= 1.0 ) {
  585. this.w = w;
  586. this.x = x;
  587. this.y = y;
  588. this.z = z;
  589. return this;
  590. }
  591. var halfTheta = Math.acos( cosHalfTheta );
  592. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  593. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  594. this.w = 0.5 * ( w + this.w );
  595. this.x = 0.5 * ( x + this.x );
  596. this.y = 0.5 * ( y + this.y );
  597. this.z = 0.5 * ( z + this.z );
  598. return this;
  599. }
  600. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  601. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  602. this.w = ( w * ratioA + this.w * ratioB );
  603. this.x = ( x * ratioA + this.x * ratioB );
  604. this.y = ( y * ratioA + this.y * ratioB );
  605. this.z = ( z * ratioA + this.z * ratioB );
  606. return this;
  607. },
  608. equals: function ( v ) {
  609. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  610. },
  611. fromArray: function ( array ) {
  612. this.x = array[ 0 ];
  613. this.y = array[ 1 ];
  614. this.z = array[ 2 ];
  615. this.w = array[ 3 ];
  616. return this;
  617. },
  618. toArray: function () {
  619. return [ this.x, this.y, this.z, this.w ];
  620. },
  621. clone: function () {
  622. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  623. }
  624. };
  625. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  626. return qm.copy( qa ).slerp( qb, t );
  627. }
  628. /**
  629. * @author mrdoob / http://mrdoob.com/
  630. * @author philogb / http://blog.thejit.org/
  631. * @author egraether / http://egraether.com/
  632. * @author zz85 / http://www.lab4games.net/zz85/blog
  633. */
  634. THREE.Vector2 = function ( x, y ) {
  635. this.x = x || 0;
  636. this.y = y || 0;
  637. };
  638. THREE.Vector2.prototype = {
  639. constructor: THREE.Vector2,
  640. set: function ( x, y ) {
  641. this.x = x;
  642. this.y = y;
  643. return this;
  644. },
  645. setX: function ( x ) {
  646. this.x = x;
  647. return this;
  648. },
  649. setY: function ( y ) {
  650. this.y = y;
  651. return this;
  652. },
  653. setComponent: function ( index, value ) {
  654. switch ( index ) {
  655. case 0: this.x = value; break;
  656. case 1: this.y = value; break;
  657. default: throw new Error( "index is out of range: " + index );
  658. }
  659. },
  660. getComponent: function ( index ) {
  661. switch ( index ) {
  662. case 0: return this.x;
  663. case 1: return this.y;
  664. default: throw new Error( "index is out of range: " + index );
  665. }
  666. },
  667. copy: function ( v ) {
  668. this.x = v.x;
  669. this.y = v.y;
  670. return this;
  671. },
  672. add: function ( v, w ) {
  673. if ( w !== undefined ) {
  674. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  675. return this.addVectors( v, w );
  676. }
  677. this.x += v.x;
  678. this.y += v.y;
  679. return this;
  680. },
  681. addVectors: function ( a, b ) {
  682. this.x = a.x + b.x;
  683. this.y = a.y + b.y;
  684. return this;
  685. },
  686. addScalar: function ( s ) {
  687. this.x += s;
  688. this.y += s;
  689. return this;
  690. },
  691. sub: function ( v, w ) {
  692. if ( w !== undefined ) {
  693. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  694. return this.subVectors( v, w );
  695. }
  696. this.x -= v.x;
  697. this.y -= v.y;
  698. return this;
  699. },
  700. subVectors: function ( a, b ) {
  701. this.x = a.x - b.x;
  702. this.y = a.y - b.y;
  703. return this;
  704. },
  705. multiplyScalar: function ( s ) {
  706. this.x *= s;
  707. this.y *= s;
  708. return this;
  709. },
  710. divideScalar: function ( s ) {
  711. if ( s !== 0 ) {
  712. this.x /= s;
  713. this.y /= s;
  714. } else {
  715. this.set( 0, 0 );
  716. }
  717. return this;
  718. },
  719. min: function ( v ) {
  720. if ( this.x > v.x ) {
  721. this.x = v.x;
  722. }
  723. if ( this.y > v.y ) {
  724. this.y = v.y;
  725. }
  726. return this;
  727. },
  728. max: function ( v ) {
  729. if ( this.x < v.x ) {
  730. this.x = v.x;
  731. }
  732. if ( this.y < v.y ) {
  733. this.y = v.y;
  734. }
  735. return this;
  736. },
  737. clamp: function ( min, max ) {
  738. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  739. if ( this.x < min.x ) {
  740. this.x = min.x;
  741. } else if ( this.x > max.x ) {
  742. this.x = max.x;
  743. }
  744. if ( this.y < min.y ) {
  745. this.y = min.y;
  746. } else if ( this.y > max.y ) {
  747. this.y = max.y;
  748. }
  749. return this;
  750. },
  751. negate: function() {
  752. return this.multiplyScalar( - 1 );
  753. },
  754. dot: function ( v ) {
  755. return this.x * v.x + this.y * v.y;
  756. },
  757. lengthSq: function () {
  758. return this.x * this.x + this.y * this.y;
  759. },
  760. length: function () {
  761. return Math.sqrt( this.x * this.x + this.y * this.y );
  762. },
  763. normalize: function () {
  764. return this.divideScalar( this.length() );
  765. },
  766. distanceTo: function ( v ) {
  767. return Math.sqrt( this.distanceToSquared( v ) );
  768. },
  769. distanceToSquared: function ( v ) {
  770. var dx = this.x - v.x, dy = this.y - v.y;
  771. return dx * dx + dy * dy;
  772. },
  773. setLength: function ( l ) {
  774. var oldLength = this.length();
  775. if ( oldLength !== 0 && l !== oldLength ) {
  776. this.multiplyScalar( l / oldLength );
  777. }
  778. return this;
  779. },
  780. lerp: function ( v, alpha ) {
  781. this.x += ( v.x - this.x ) * alpha;
  782. this.y += ( v.y - this.y ) * alpha;
  783. return this;
  784. },
  785. equals: function( v ) {
  786. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  787. },
  788. fromArray: function ( array ) {
  789. this.x = array[ 0 ];
  790. this.y = array[ 1 ];
  791. return this;
  792. },
  793. toArray: function () {
  794. return [ this.x, this.y ];
  795. },
  796. clone: function () {
  797. return new THREE.Vector2( this.x, this.y );
  798. }
  799. };
  800. /**
  801. * @author mrdoob / http://mrdoob.com/
  802. * @author *kile / http://kile.stravaganza.org/
  803. * @author philogb / http://blog.thejit.org/
  804. * @author mikael emtinger / http://gomo.se/
  805. * @author egraether / http://egraether.com/
  806. * @author WestLangley / http://github.com/WestLangley
  807. */
  808. THREE.Vector3 = function ( x, y, z ) {
  809. this.x = x || 0;
  810. this.y = y || 0;
  811. this.z = z || 0;
  812. };
  813. THREE.Vector3.prototype = {
  814. constructor: THREE.Vector3,
  815. set: function ( x, y, z ) {
  816. this.x = x;
  817. this.y = y;
  818. this.z = z;
  819. return this;
  820. },
  821. setX: function ( x ) {
  822. this.x = x;
  823. return this;
  824. },
  825. setY: function ( y ) {
  826. this.y = y;
  827. return this;
  828. },
  829. setZ: function ( z ) {
  830. this.z = z;
  831. return this;
  832. },
  833. setComponent: function ( index, value ) {
  834. switch ( index ) {
  835. case 0: this.x = value; break;
  836. case 1: this.y = value; break;
  837. case 2: this.z = value; break;
  838. default: throw new Error( "index is out of range: " + index );
  839. }
  840. },
  841. getComponent: function ( index ) {
  842. switch ( index ) {
  843. case 0: return this.x;
  844. case 1: return this.y;
  845. case 2: return this.z;
  846. default: throw new Error( "index is out of range: " + index );
  847. }
  848. },
  849. copy: function ( v ) {
  850. this.x = v.x;
  851. this.y = v.y;
  852. this.z = v.z;
  853. return this;
  854. },
  855. add: function ( v, w ) {
  856. if ( w !== undefined ) {
  857. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  858. return this.addVectors( v, w );
  859. }
  860. this.x += v.x;
  861. this.y += v.y;
  862. this.z += v.z;
  863. return this;
  864. },
  865. addScalar: function ( s ) {
  866. this.x += s;
  867. this.y += s;
  868. this.z += s;
  869. return this;
  870. },
  871. addVectors: function ( a, b ) {
  872. this.x = a.x + b.x;
  873. this.y = a.y + b.y;
  874. this.z = a.z + b.z;
  875. return this;
  876. },
  877. sub: function ( v, w ) {
  878. if ( w !== undefined ) {
  879. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  880. return this.subVectors( v, w );
  881. }
  882. this.x -= v.x;
  883. this.y -= v.y;
  884. this.z -= v.z;
  885. return this;
  886. },
  887. subVectors: function ( a, b ) {
  888. this.x = a.x - b.x;
  889. this.y = a.y - b.y;
  890. this.z = a.z - b.z;
  891. return this;
  892. },
  893. multiply: function ( v, w ) {
  894. if ( w !== undefined ) {
  895. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  896. return this.multiplyVectors( v, w );
  897. }
  898. this.x *= v.x;
  899. this.y *= v.y;
  900. this.z *= v.z;
  901. return this;
  902. },
  903. multiplyScalar: function ( s ) {
  904. this.x *= s;
  905. this.y *= s;
  906. this.z *= s;
  907. return this;
  908. },
  909. multiplyVectors: function ( a, b ) {
  910. this.x = a.x * b.x;
  911. this.y = a.y * b.y;
  912. this.z = a.z * b.z;
  913. return this;
  914. },
  915. applyMatrix3: function ( m ) {
  916. var x = this.x;
  917. var y = this.y;
  918. var z = this.z;
  919. var e = m.elements;
  920. this.x = e[0] * x + e[3] * y + e[6] * z;
  921. this.y = e[1] * x + e[4] * y + e[7] * z;
  922. this.z = e[2] * x + e[5] * y + e[8] * z;
  923. return this;
  924. },
  925. applyMatrix4: function ( m ) {
  926. // input: THREE.Matrix4 affine matrix
  927. var x = this.x, y = this.y, z = this.z;
  928. var e = m.elements;
  929. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  930. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  931. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  932. return this;
  933. },
  934. applyProjection: function ( m ) {
  935. // input: THREE.Matrix4 projection matrix
  936. var x = this.x, y = this.y, z = this.z;
  937. var e = m.elements;
  938. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  939. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  940. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  941. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  942. return this;
  943. },
  944. applyQuaternion: function ( q ) {
  945. var x = this.x;
  946. var y = this.y;
  947. var z = this.z;
  948. var qx = q.x;
  949. var qy = q.y;
  950. var qz = q.z;
  951. var qw = q.w;
  952. // calculate quat * vector
  953. var ix = qw * x + qy * z - qz * y;
  954. var iy = qw * y + qz * x - qx * z;
  955. var iz = qw * z + qx * y - qy * x;
  956. var iw = -qx * x - qy * y - qz * z;
  957. // calculate result * inverse quat
  958. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  959. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  960. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  961. return this;
  962. },
  963. transformDirection: function ( m ) {
  964. // input: THREE.Matrix4 affine matrix
  965. // vector interpreted as a direction
  966. var x = this.x, y = this.y, z = this.z;
  967. var e = m.elements;
  968. this.x = e[0] * x + e[4] * y + e[8] * z;
  969. this.y = e[1] * x + e[5] * y + e[9] * z;
  970. this.z = e[2] * x + e[6] * y + e[10] * z;
  971. this.normalize();
  972. return this;
  973. },
  974. divide: function ( v ) {
  975. this.x /= v.x;
  976. this.y /= v.y;
  977. this.z /= v.z;
  978. return this;
  979. },
  980. divideScalar: function ( s ) {
  981. if ( s !== 0 ) {
  982. this.x /= s;
  983. this.y /= s;
  984. this.z /= s;
  985. } else {
  986. this.x = 0;
  987. this.y = 0;
  988. this.z = 0;
  989. }
  990. return this;
  991. },
  992. min: function ( v ) {
  993. if ( this.x > v.x ) {
  994. this.x = v.x;
  995. }
  996. if ( this.y > v.y ) {
  997. this.y = v.y;
  998. }
  999. if ( this.z > v.z ) {
  1000. this.z = v.z;
  1001. }
  1002. return this;
  1003. },
  1004. max: function ( v ) {
  1005. if ( this.x < v.x ) {
  1006. this.x = v.x;
  1007. }
  1008. if ( this.y < v.y ) {
  1009. this.y = v.y;
  1010. }
  1011. if ( this.z < v.z ) {
  1012. this.z = v.z;
  1013. }
  1014. return this;
  1015. },
  1016. clamp: function ( min, max ) {
  1017. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1018. if ( this.x < min.x ) {
  1019. this.x = min.x;
  1020. } else if ( this.x > max.x ) {
  1021. this.x = max.x;
  1022. }
  1023. if ( this.y < min.y ) {
  1024. this.y = min.y;
  1025. } else if ( this.y > max.y ) {
  1026. this.y = max.y;
  1027. }
  1028. if ( this.z < min.z ) {
  1029. this.z = min.z;
  1030. } else if ( this.z > max.z ) {
  1031. this.z = max.z;
  1032. }
  1033. return this;
  1034. },
  1035. negate: function () {
  1036. return this.multiplyScalar( - 1 );
  1037. },
  1038. dot: function ( v ) {
  1039. return this.x * v.x + this.y * v.y + this.z * v.z;
  1040. },
  1041. lengthSq: function () {
  1042. return this.x * this.x + this.y * this.y + this.z * this.z;
  1043. },
  1044. length: function () {
  1045. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1046. },
  1047. lengthManhattan: function () {
  1048. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1049. },
  1050. normalize: function () {
  1051. return this.divideScalar( this.length() );
  1052. },
  1053. setLength: function ( l ) {
  1054. var oldLength = this.length();
  1055. if ( oldLength !== 0 && l !== oldLength ) {
  1056. this.multiplyScalar( l / oldLength );
  1057. }
  1058. return this;
  1059. },
  1060. lerp: function ( v, alpha ) {
  1061. this.x += ( v.x - this.x ) * alpha;
  1062. this.y += ( v.y - this.y ) * alpha;
  1063. this.z += ( v.z - this.z ) * alpha;
  1064. return this;
  1065. },
  1066. cross: function ( v, w ) {
  1067. if ( w !== undefined ) {
  1068. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1069. return this.crossVectors( v, w );
  1070. }
  1071. var x = this.x, y = this.y, z = this.z;
  1072. this.x = y * v.z - z * v.y;
  1073. this.y = z * v.x - x * v.z;
  1074. this.z = x * v.y - y * v.x;
  1075. return this;
  1076. },
  1077. crossVectors: function ( a, b ) {
  1078. this.x = a.y * b.z - a.z * b.y;
  1079. this.y = a.z * b.x - a.x * b.z;
  1080. this.z = a.x * b.y - a.y * b.x;
  1081. return this;
  1082. },
  1083. angleTo: function ( v ) {
  1084. var theta = this.dot( v ) / ( this.length() * v.length() );
  1085. // clamp, to handle numerical problems
  1086. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1087. },
  1088. distanceTo: function ( v ) {
  1089. return Math.sqrt( this.distanceToSquared( v ) );
  1090. },
  1091. distanceToSquared: function ( v ) {
  1092. var dx = this.x - v.x;
  1093. var dy = this.y - v.y;
  1094. var dz = this.z - v.z;
  1095. return dx * dx + dy * dy + dz * dz;
  1096. },
  1097. setEulerFromRotationMatrix: function ( m, order ) {
  1098. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1099. // clamp, to handle numerical problems
  1100. function clamp( x ) {
  1101. return Math.min( Math.max( x, -1 ), 1 );
  1102. }
  1103. var te = m.elements;
  1104. var m11 = te[0], m12 = te[4], m13 = te[8];
  1105. var m21 = te[1], m22 = te[5], m23 = te[9];
  1106. var m31 = te[2], m32 = te[6], m33 = te[10];
  1107. if ( order === undefined || order === 'XYZ' ) {
  1108. this.y = Math.asin( clamp( m13 ) );
  1109. if ( Math.abs( m13 ) < 0.99999 ) {
  1110. this.x = Math.atan2( - m23, m33 );
  1111. this.z = Math.atan2( - m12, m11 );
  1112. } else {
  1113. this.x = Math.atan2( m32, m22 );
  1114. this.z = 0;
  1115. }
  1116. } else if ( order === 'YXZ' ) {
  1117. this.x = Math.asin( - clamp( m23 ) );
  1118. if ( Math.abs( m23 ) < 0.99999 ) {
  1119. this.y = Math.atan2( m13, m33 );
  1120. this.z = Math.atan2( m21, m22 );
  1121. } else {
  1122. this.y = Math.atan2( - m31, m11 );
  1123. this.z = 0;
  1124. }
  1125. } else if ( order === 'ZXY' ) {
  1126. this.x = Math.asin( clamp( m32 ) );
  1127. if ( Math.abs( m32 ) < 0.99999 ) {
  1128. this.y = Math.atan2( - m31, m33 );
  1129. this.z = Math.atan2( - m12, m22 );
  1130. } else {
  1131. this.y = 0;
  1132. this.z = Math.atan2( m21, m11 );
  1133. }
  1134. } else if ( order === 'ZYX' ) {
  1135. this.y = Math.asin( - clamp( m31 ) );
  1136. if ( Math.abs( m31 ) < 0.99999 ) {
  1137. this.x = Math.atan2( m32, m33 );
  1138. this.z = Math.atan2( m21, m11 );
  1139. } else {
  1140. this.x = 0;
  1141. this.z = Math.atan2( - m12, m22 );
  1142. }
  1143. } else if ( order === 'YZX' ) {
  1144. this.z = Math.asin( clamp( m21 ) );
  1145. if ( Math.abs( m21 ) < 0.99999 ) {
  1146. this.x = Math.atan2( - m23, m22 );
  1147. this.y = Math.atan2( - m31, m11 );
  1148. } else {
  1149. this.x = 0;
  1150. this.y = Math.atan2( m13, m33 );
  1151. }
  1152. } else if ( order === 'XZY' ) {
  1153. this.z = Math.asin( - clamp( m12 ) );
  1154. if ( Math.abs( m12 ) < 0.99999 ) {
  1155. this.x = Math.atan2( m32, m22 );
  1156. this.y = Math.atan2( m13, m11 );
  1157. } else {
  1158. this.x = Math.atan2( - m23, m33 );
  1159. this.y = 0;
  1160. }
  1161. }
  1162. return this;
  1163. },
  1164. setEulerFromQuaternion: function ( q, order ) {
  1165. // q is assumed to be normalized
  1166. // clamp, to handle numerical problems
  1167. function clamp( x ) {
  1168. return Math.min( Math.max( x, -1 ), 1 );
  1169. }
  1170. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1171. var sqx = q.x * q.x;
  1172. var sqy = q.y * q.y;
  1173. var sqz = q.z * q.z;
  1174. var sqw = q.w * q.w;
  1175. if ( order === undefined || order === 'XYZ' ) {
  1176. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1177. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1178. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1179. } else if ( order === 'YXZ' ) {
  1180. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1181. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1182. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1183. } else if ( order === 'ZXY' ) {
  1184. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1185. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1186. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1187. } else if ( order === 'ZYX' ) {
  1188. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1189. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1190. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1191. } else if ( order === 'YZX' ) {
  1192. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1193. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1194. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1195. } else if ( order === 'XZY' ) {
  1196. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1197. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1198. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1199. }
  1200. return this;
  1201. },
  1202. getPositionFromMatrix: function ( m ) {
  1203. this.x = m.elements[12];
  1204. this.y = m.elements[13];
  1205. this.z = m.elements[14];
  1206. return this;
  1207. },
  1208. getScaleFromMatrix: function ( m ) {
  1209. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1210. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1211. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1212. this.x = sx;
  1213. this.y = sy;
  1214. this.z = sz;
  1215. return this;
  1216. },
  1217. getColumnFromMatrix: function ( index, matrix ) {
  1218. var offset = index * 4;
  1219. var me = matrix.elements;
  1220. this.x = me[ offset ];
  1221. this.y = me[ offset + 1 ];
  1222. this.z = me[ offset + 2 ];
  1223. return this;
  1224. },
  1225. equals: function ( v ) {
  1226. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1227. },
  1228. fromArray: function ( array ) {
  1229. this.x = array[ 0 ];
  1230. this.y = array[ 1 ];
  1231. this.z = array[ 2 ];
  1232. return this;
  1233. },
  1234. toArray: function () {
  1235. return [ this.x, this.y, this.z ];
  1236. },
  1237. clone: function () {
  1238. return new THREE.Vector3( this.x, this.y, this.z );
  1239. }
  1240. };
  1241. THREE.extend( THREE.Vector3.prototype, {
  1242. applyEuler: function () {
  1243. var q1 = new THREE.Quaternion();
  1244. return function ( v, eulerOrder ) {
  1245. var quaternion = q1.setFromEuler( v, eulerOrder );
  1246. this.applyQuaternion( quaternion );
  1247. return this;
  1248. };
  1249. }(),
  1250. applyAxisAngle: function () {
  1251. var q1 = new THREE.Quaternion();
  1252. return function ( axis, angle ) {
  1253. var quaternion = q1.setFromAxisAngle( axis, angle );
  1254. this.applyQuaternion( quaternion );
  1255. return this;
  1256. };
  1257. }(),
  1258. projectOnVector: function () {
  1259. var v1 = new THREE.Vector3();
  1260. return function ( vector ) {
  1261. v1.copy( vector ).normalize();
  1262. var d = this.dot( v1 );
  1263. return this.copy( v1 ).multiplyScalar( d );
  1264. };
  1265. }(),
  1266. projectOnPlane: function () {
  1267. var v1 = new THREE.Vector3();
  1268. return function ( planeNormal ) {
  1269. v1.copy( this ).projectOnVector( planeNormal );
  1270. return this.sub( v1 );
  1271. }
  1272. }(),
  1273. reflect: function () {
  1274. var v1 = new THREE.Vector3();
  1275. return function ( vector ) {
  1276. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1277. return this.subVectors( v1, this );
  1278. }
  1279. }()
  1280. } );
  1281. /**
  1282. * @author supereggbert / http://www.paulbrunt.co.uk/
  1283. * @author philogb / http://blog.thejit.org/
  1284. * @author mikael emtinger / http://gomo.se/
  1285. * @author egraether / http://egraether.com/
  1286. * @author WestLangley / http://github.com/WestLangley
  1287. */
  1288. THREE.Vector4 = function ( x, y, z, w ) {
  1289. this.x = x || 0;
  1290. this.y = y || 0;
  1291. this.z = z || 0;
  1292. this.w = ( w !== undefined ) ? w : 1;
  1293. };
  1294. THREE.Vector4.prototype = {
  1295. constructor: THREE.Vector4,
  1296. set: function ( x, y, z, w ) {
  1297. this.x = x;
  1298. this.y = y;
  1299. this.z = z;
  1300. this.w = w;
  1301. return this;
  1302. },
  1303. setX: function ( x ) {
  1304. this.x = x;
  1305. return this;
  1306. },
  1307. setY: function ( y ) {
  1308. this.y = y;
  1309. return this;
  1310. },
  1311. setZ: function ( z ) {
  1312. this.z = z;
  1313. return this;
  1314. },
  1315. setW: function ( w ) {
  1316. this.w = w;
  1317. return this;
  1318. },
  1319. setComponent: function ( index, value ) {
  1320. switch ( index ) {
  1321. case 0: this.x = value; break;
  1322. case 1: this.y = value; break;
  1323. case 2: this.z = value; break;
  1324. case 3: this.w = value; break;
  1325. default: throw new Error( "index is out of range: " + index );
  1326. }
  1327. },
  1328. getComponent: function ( index ) {
  1329. switch ( index ) {
  1330. case 0: return this.x;
  1331. case 1: return this.y;
  1332. case 2: return this.z;
  1333. case 3: return this.w;
  1334. default: throw new Error( "index is out of range: " + index );
  1335. }
  1336. },
  1337. copy: function ( v ) {
  1338. this.x = v.x;
  1339. this.y = v.y;
  1340. this.z = v.z;
  1341. this.w = ( v.w !== undefined ) ? v.w : 1;
  1342. return this;
  1343. },
  1344. add: function ( v, w ) {
  1345. if ( w !== undefined ) {
  1346. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1347. return this.addVectors( v, w );
  1348. }
  1349. this.x += v.x;
  1350. this.y += v.y;
  1351. this.z += v.z;
  1352. this.w += v.w;
  1353. return this;
  1354. },
  1355. addScalar: function ( s ) {
  1356. this.x += s;
  1357. this.y += s;
  1358. this.z += s;
  1359. this.w += s;
  1360. return this;
  1361. },
  1362. addVectors: function ( a, b ) {
  1363. this.x = a.x + b.x;
  1364. this.y = a.y + b.y;
  1365. this.z = a.z + b.z;
  1366. this.w = a.w + b.w;
  1367. return this;
  1368. },
  1369. sub: function ( v, w ) {
  1370. if ( w !== undefined ) {
  1371. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1372. return this.subVectors( v, w );
  1373. }
  1374. this.x -= v.x;
  1375. this.y -= v.y;
  1376. this.z -= v.z;
  1377. this.w -= v.w;
  1378. return this;
  1379. },
  1380. subVectors: function ( a, b ) {
  1381. this.x = a.x - b.x;
  1382. this.y = a.y - b.y;
  1383. this.z = a.z - b.z;
  1384. this.w = a.w - b.w;
  1385. return this;
  1386. },
  1387. multiplyScalar: function ( s ) {
  1388. this.x *= s;
  1389. this.y *= s;
  1390. this.z *= s;
  1391. this.w *= s;
  1392. return this;
  1393. },
  1394. applyMatrix4: function ( m ) {
  1395. var x = this.x;
  1396. var y = this.y;
  1397. var z = this.z;
  1398. var w = this.w;
  1399. var e = m.elements;
  1400. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1401. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1402. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1403. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1404. return this;
  1405. },
  1406. divideScalar: function ( s ) {
  1407. if ( s !== 0 ) {
  1408. this.x /= s;
  1409. this.y /= s;
  1410. this.z /= s;
  1411. this.w /= s;
  1412. } else {
  1413. this.x = 0;
  1414. this.y = 0;
  1415. this.z = 0;
  1416. this.w = 1;
  1417. }
  1418. return this;
  1419. },
  1420. setAxisAngleFromQuaternion: function ( q ) {
  1421. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1422. // q is assumed to be normalized
  1423. this.w = 2 * Math.acos( q.w );
  1424. var s = Math.sqrt( 1 - q.w * q.w );
  1425. if ( s < 0.0001 ) {
  1426. this.x = 1;
  1427. this.y = 0;
  1428. this.z = 0;
  1429. } else {
  1430. this.x = q.x / s;
  1431. this.y = q.y / s;
  1432. this.z = q.z / s;
  1433. }
  1434. return this;
  1435. },
  1436. setAxisAngleFromRotationMatrix: function ( m ) {
  1437. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1438. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1439. var angle, x, y, z, // variables for result
  1440. epsilon = 0.01, // margin to allow for rounding errors
  1441. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1442. te = m.elements,
  1443. m11 = te[0], m12 = te[4], m13 = te[8],
  1444. m21 = te[1], m22 = te[5], m23 = te[9],
  1445. m31 = te[2], m32 = te[6], m33 = te[10];
  1446. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1447. && ( Math.abs( m13 - m31 ) < epsilon )
  1448. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1449. // singularity found
  1450. // first check for identity matrix which must have +1 for all terms
  1451. // in leading diagonal and zero in other terms
  1452. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1453. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1454. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1455. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1456. // this singularity is identity matrix so angle = 0
  1457. this.set( 1, 0, 0, 0 );
  1458. return this; // zero angle, arbitrary axis
  1459. }
  1460. // otherwise this singularity is angle = 180
  1461. angle = Math.PI;
  1462. var xx = ( m11 + 1 ) / 2;
  1463. var yy = ( m22 + 1 ) / 2;
  1464. var zz = ( m33 + 1 ) / 2;
  1465. var xy = ( m12 + m21 ) / 4;
  1466. var xz = ( m13 + m31 ) / 4;
  1467. var yz = ( m23 + m32 ) / 4;
  1468. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1469. if ( xx < epsilon ) {
  1470. x = 0;
  1471. y = 0.707106781;
  1472. z = 0.707106781;
  1473. } else {
  1474. x = Math.sqrt( xx );
  1475. y = xy / x;
  1476. z = xz / x;
  1477. }
  1478. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1479. if ( yy < epsilon ) {
  1480. x = 0.707106781;
  1481. y = 0;
  1482. z = 0.707106781;
  1483. } else {
  1484. y = Math.sqrt( yy );
  1485. x = xy / y;
  1486. z = yz / y;
  1487. }
  1488. } else { // m33 is the largest diagonal term so base result on this
  1489. if ( zz < epsilon ) {
  1490. x = 0.707106781;
  1491. y = 0.707106781;
  1492. z = 0;
  1493. } else {
  1494. z = Math.sqrt( zz );
  1495. x = xz / z;
  1496. y = yz / z;
  1497. }
  1498. }
  1499. this.set( x, y, z, angle );
  1500. return this; // return 180 deg rotation
  1501. }
  1502. // as we have reached here there are no singularities so we can handle normally
  1503. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1504. + ( m13 - m31 ) * ( m13 - m31 )
  1505. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1506. if ( Math.abs( s ) < 0.001 ) s = 1;
  1507. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1508. // caught by singularity test above, but I've left it in just in case
  1509. this.x = ( m32 - m23 ) / s;
  1510. this.y = ( m13 - m31 ) / s;
  1511. this.z = ( m21 - m12 ) / s;
  1512. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1513. return this;
  1514. },
  1515. min: function ( v ) {
  1516. if ( this.x > v.x ) {
  1517. this.x = v.x;
  1518. }
  1519. if ( this.y > v.y ) {
  1520. this.y = v.y;
  1521. }
  1522. if ( this.z > v.z ) {
  1523. this.z = v.z;
  1524. }
  1525. if ( this.w > v.w ) {
  1526. this.w = v.w;
  1527. }
  1528. return this;
  1529. },
  1530. max: function ( v ) {
  1531. if ( this.x < v.x ) {
  1532. this.x = v.x;
  1533. }
  1534. if ( this.y < v.y ) {
  1535. this.y = v.y;
  1536. }
  1537. if ( this.z < v.z ) {
  1538. this.z = v.z;
  1539. }
  1540. if ( this.w < v.w ) {
  1541. this.w = v.w;
  1542. }
  1543. return this;
  1544. },
  1545. clamp: function ( min, max ) {
  1546. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1547. if ( this.x < min.x ) {
  1548. this.x = min.x;
  1549. } else if ( this.x > max.x ) {
  1550. this.x = max.x;
  1551. }
  1552. if ( this.y < min.y ) {
  1553. this.y = min.y;
  1554. } else if ( this.y > max.y ) {
  1555. this.y = max.y;
  1556. }
  1557. if ( this.z < min.z ) {
  1558. this.z = min.z;
  1559. } else if ( this.z > max.z ) {
  1560. this.z = max.z;
  1561. }
  1562. if ( this.w < min.w ) {
  1563. this.w = min.w;
  1564. } else if ( this.w > max.w ) {
  1565. this.w = max.w;
  1566. }
  1567. return this;
  1568. },
  1569. negate: function() {
  1570. return this.multiplyScalar( -1 );
  1571. },
  1572. dot: function ( v ) {
  1573. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1574. },
  1575. lengthSq: function () {
  1576. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1577. },
  1578. length: function () {
  1579. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1580. },
  1581. lengthManhattan: function () {
  1582. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1583. },
  1584. normalize: function () {
  1585. return this.divideScalar( this.length() );
  1586. },
  1587. setLength: function ( l ) {
  1588. var oldLength = this.length();
  1589. if ( oldLength !== 0 && l !== oldLength ) {
  1590. this.multiplyScalar( l / oldLength );
  1591. }
  1592. return this;
  1593. },
  1594. lerp: function ( v, alpha ) {
  1595. this.x += ( v.x - this.x ) * alpha;
  1596. this.y += ( v.y - this.y ) * alpha;
  1597. this.z += ( v.z - this.z ) * alpha;
  1598. this.w += ( v.w - this.w ) * alpha;
  1599. return this;
  1600. },
  1601. equals: function ( v ) {
  1602. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1603. },
  1604. fromArray: function ( array ) {
  1605. this.x = array[ 0 ];
  1606. this.y = array[ 1 ];
  1607. this.z = array[ 2 ];
  1608. this.w = array[ 3 ];
  1609. return this;
  1610. },
  1611. toArray: function () {
  1612. return [ this.x, this.y, this.z, this.w ];
  1613. },
  1614. clone: function () {
  1615. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1616. }
  1617. };
  1618. /**
  1619. * @author bhouston / http://exocortex.com
  1620. */
  1621. THREE.Line3 = function ( start, end ) {
  1622. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1623. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1624. };
  1625. THREE.Line3.prototype = {
  1626. constructor: THREE.Line3,
  1627. set: function ( start, end ) {
  1628. this.start.copy( start );
  1629. this.end.copy( end );
  1630. return this;
  1631. },
  1632. copy: function ( line ) {
  1633. this.start.copy( line.start );
  1634. this.end.copy( line.end );
  1635. return this;
  1636. },
  1637. center: function ( optionalTarget ) {
  1638. var result = optionalTarget || new THREE.Vector3();
  1639. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1640. },
  1641. delta: function ( optionalTarget ) {
  1642. var result = optionalTarget || new THREE.Vector3();
  1643. return result.subVectors( this.end, this.start );
  1644. },
  1645. distanceSq: function () {
  1646. return this.start.distanceToSquared( this.end );
  1647. },
  1648. distance: function () {
  1649. return this.start.distanceTo( this.end );
  1650. },
  1651. at: function ( t, optionalTarget ) {
  1652. var result = optionalTarget || new THREE.Vector3();
  1653. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1654. },
  1655. closestPointToPointParameter: function() {
  1656. var startP = new THREE.Vector3();
  1657. var startEnd = new THREE.Vector3();
  1658. return function ( point, clampToLine ) {
  1659. startP.subVectors( point, this.start );
  1660. startEnd.subVectors( this.end, this.start );
  1661. var startEnd2 = startEnd.dot( startEnd );
  1662. var startEnd_startP = startEnd.dot( startP );
  1663. var t = startEnd_startP / startEnd2;
  1664. if ( clampToLine ) {
  1665. t = THREE.Math.clamp( t, 0, 1 );
  1666. }
  1667. return t;
  1668. };
  1669. }(),
  1670. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1671. var t = this.closestPointToPointParameter( point, clampToLine );
  1672. var result = optionalTarget || new THREE.Vector3();
  1673. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1674. },
  1675. applyMatrix4: function ( matrix ) {
  1676. this.start.applyMatrix4( matrix );
  1677. this.end.applyMatrix4( matrix );
  1678. return this;
  1679. },
  1680. equals: function ( line ) {
  1681. return line.start.equals( this.start ) && line.end.equals( this.end );
  1682. },
  1683. clone: function () {
  1684. return new THREE.Line3().copy( this );
  1685. }
  1686. };
  1687. /**
  1688. * @author bhouston / http://exocortex.com
  1689. */
  1690. THREE.Box2 = function ( min, max ) {
  1691. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1692. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1693. };
  1694. THREE.Box2.prototype = {
  1695. constructor: THREE.Box2,
  1696. set: function ( min, max ) {
  1697. this.min.copy( min );
  1698. this.max.copy( max );
  1699. return this;
  1700. },
  1701. setFromPoints: function ( points ) {
  1702. if ( points.length > 0 ) {
  1703. var point = points[ 0 ];
  1704. this.min.copy( point );
  1705. this.max.copy( point );
  1706. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1707. point = points[ i ];
  1708. if ( point.x < this.min.x ) {
  1709. this.min.x = point.x;
  1710. } else if ( point.x > this.max.x ) {
  1711. this.max.x = point.x;
  1712. }
  1713. if ( point.y < this.min.y ) {
  1714. this.min.y = point.y;
  1715. } else if ( point.y > this.max.y ) {
  1716. this.max.y = point.y;
  1717. }
  1718. }
  1719. } else {
  1720. this.makeEmpty();
  1721. }
  1722. return this;
  1723. },
  1724. setFromCenterAndSize: function () {
  1725. var v1 = new THREE.Vector2();
  1726. return function ( center, size ) {
  1727. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1728. this.min.copy( center ).sub( halfSize );
  1729. this.max.copy( center ).add( halfSize );
  1730. return this;
  1731. };
  1732. }(),
  1733. copy: function ( box ) {
  1734. this.min.copy( box.min );
  1735. this.max.copy( box.max );
  1736. return this;
  1737. },
  1738. makeEmpty: function () {
  1739. this.min.x = this.min.y = Infinity;
  1740. this.max.x = this.max.y = -Infinity;
  1741. return this;
  1742. },
  1743. empty: function () {
  1744. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1745. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1746. },
  1747. center: function ( optionalTarget ) {
  1748. var result = optionalTarget || new THREE.Vector2();
  1749. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1750. },
  1751. size: function ( optionalTarget ) {
  1752. var result = optionalTarget || new THREE.Vector2();
  1753. return result.subVectors( this.max, this.min );
  1754. },
  1755. expandByPoint: function ( point ) {
  1756. this.min.min( point );
  1757. this.max.max( point );
  1758. return this;
  1759. },
  1760. expandByVector: function ( vector ) {
  1761. this.min.sub( vector );
  1762. this.max.add( vector );
  1763. return this;
  1764. },
  1765. expandByScalar: function ( scalar ) {
  1766. this.min.addScalar( -scalar );
  1767. this.max.addScalar( scalar );
  1768. return this;
  1769. },
  1770. containsPoint: function ( point ) {
  1771. if ( point.x < this.min.x || point.x > this.max.x ||
  1772. point.y < this.min.y || point.y > this.max.y ) {
  1773. return false;
  1774. }
  1775. return true;
  1776. },
  1777. containsBox: function ( box ) {
  1778. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1779. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1780. return true;
  1781. }
  1782. return false;
  1783. },
  1784. getParameter: function ( point ) {
  1785. // This can potentially have a divide by zero if the box
  1786. // has a size dimension of 0.
  1787. return new THREE.Vector2(
  1788. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1789. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1790. );
  1791. },
  1792. isIntersectionBox: function ( box ) {
  1793. // using 6 splitting planes to rule out intersections.
  1794. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1795. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1796. return false;
  1797. }
  1798. return true;
  1799. },
  1800. clampPoint: function ( point, optionalTarget ) {
  1801. var result = optionalTarget || new THREE.Vector2();
  1802. return result.copy( point ).clamp( this.min, this.max );
  1803. },
  1804. distanceToPoint: function () {
  1805. var v1 = new THREE.Vector2();
  1806. return function ( point ) {
  1807. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1808. return clampedPoint.sub( point ).length();
  1809. };
  1810. }(),
  1811. intersect: function ( box ) {
  1812. this.min.max( box.min );
  1813. this.max.min( box.max );
  1814. return this;
  1815. },
  1816. union: function ( box ) {
  1817. this.min.min( box.min );
  1818. this.max.max( box.max );
  1819. return this;
  1820. },
  1821. translate: function ( offset ) {
  1822. this.min.add( offset );
  1823. this.max.add( offset );
  1824. return this;
  1825. },
  1826. equals: function ( box ) {
  1827. return box.min.equals( this.min ) && box.max.equals( this.max );
  1828. },
  1829. clone: function () {
  1830. return new THREE.Box2().copy( this );
  1831. }
  1832. };
  1833. /**
  1834. * @author bhouston / http://exocortex.com
  1835. */
  1836. THREE.Box3 = function ( min, max ) {
  1837. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  1838. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1839. };
  1840. THREE.Box3.prototype = {
  1841. constructor: THREE.Box3,
  1842. set: function ( min, max ) {
  1843. this.min.copy( min );
  1844. this.max.copy( max );
  1845. return this;
  1846. },
  1847. setFromPoints: function ( points ) {
  1848. if ( points.length > 0 ) {
  1849. var point = points[ 0 ];
  1850. this.min.copy( point );
  1851. this.max.copy( point );
  1852. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1853. point = points[ i ];
  1854. if ( point.x < this.min.x ) {
  1855. this.min.x = point.x;
  1856. } else if ( point.x > this.max.x ) {
  1857. this.max.x = point.x;
  1858. }
  1859. if ( point.y < this.min.y ) {
  1860. this.min.y = point.y;
  1861. } else if ( point.y > this.max.y ) {
  1862. this.max.y = point.y;
  1863. }
  1864. if ( point.z < this.min.z ) {
  1865. this.min.z = point.z;
  1866. } else if ( point.z > this.max.z ) {
  1867. this.max.z = point.z;
  1868. }
  1869. }
  1870. } else {
  1871. this.makeEmpty();
  1872. }
  1873. return this;
  1874. },
  1875. setFromCenterAndSize: function() {
  1876. var v1 = new THREE.Vector3();
  1877. return function ( center, size ) {
  1878. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1879. this.min.copy( center ).sub( halfSize );
  1880. this.max.copy( center ).add( halfSize );
  1881. return this;
  1882. };
  1883. }(),
  1884. copy: function ( box ) {
  1885. this.min.copy( box.min );
  1886. this.max.copy( box.max );
  1887. return this;
  1888. },
  1889. makeEmpty: function () {
  1890. this.min.x = this.min.y = this.min.z = Infinity;
  1891. this.max.x = this.max.y = this.max.z = -Infinity;
  1892. return this;
  1893. },
  1894. empty: function () {
  1895. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1896. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1897. },
  1898. center: function ( optionalTarget ) {
  1899. var result = optionalTarget || new THREE.Vector3();
  1900. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1901. },
  1902. size: function ( optionalTarget ) {
  1903. var result = optionalTarget || new THREE.Vector3();
  1904. return result.subVectors( this.max, this.min );
  1905. },
  1906. expandByPoint: function ( point ) {
  1907. this.min.min( point );
  1908. this.max.max( point );
  1909. return this;
  1910. },
  1911. expandByVector: function ( vector ) {
  1912. this.min.sub( vector );
  1913. this.max.add( vector );
  1914. return this;
  1915. },
  1916. expandByScalar: function ( scalar ) {
  1917. this.min.addScalar( -scalar );
  1918. this.max.addScalar( scalar );
  1919. return this;
  1920. },
  1921. containsPoint: function ( point ) {
  1922. if ( point.x < this.min.x || point.x > this.max.x ||
  1923. point.y < this.min.y || point.y > this.max.y ||
  1924. point.z < this.min.z || point.z > this.max.z ) {
  1925. return false;
  1926. }
  1927. return true;
  1928. },
  1929. containsBox: function ( box ) {
  1930. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1931. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1932. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1933. return true;
  1934. }
  1935. return false;
  1936. },
  1937. getParameter: function ( point ) {
  1938. // This can potentially have a divide by zero if the box
  1939. // has a size dimension of 0.
  1940. return new THREE.Vector3(
  1941. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1942. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1943. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1944. );
  1945. },
  1946. isIntersectionBox: function ( box ) {
  1947. // using 6 splitting planes to rule out intersections.
  1948. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1949. box.max.y < this.min.y || box.min.y > this.max.y ||
  1950. box.max.z < this.min.z || box.min.z > this.max.z ) {
  1951. return false;
  1952. }
  1953. return true;
  1954. },
  1955. clampPoint: function ( point, optionalTarget ) {
  1956. var result = optionalTarget || new THREE.Vector3();
  1957. return result.copy( point ).clamp( this.min, this.max );
  1958. },
  1959. distanceToPoint: function() {
  1960. var v1 = new THREE.Vector3();
  1961. return function ( point ) {
  1962. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1963. return clampedPoint.sub( point ).length();
  1964. };
  1965. }(),
  1966. getBoundingSphere: function() {
  1967. var v1 = new THREE.Vector3();
  1968. return function ( optionalTarget ) {
  1969. var result = optionalTarget || new THREE.Sphere();
  1970. result.center = this.center();
  1971. result.radius = this.size( v1 ).length() * 0.5;
  1972. return result;
  1973. };
  1974. }(),
  1975. intersect: function ( box ) {
  1976. this.min.max( box.min );
  1977. this.max.min( box.max );
  1978. return this;
  1979. },
  1980. union: function ( box ) {
  1981. this.min.min( box.min );
  1982. this.max.max( box.max );
  1983. return this;
  1984. },
  1985. applyMatrix4: function() {
  1986. var points = [
  1987. new THREE.Vector3(),
  1988. new THREE.Vector3(),
  1989. new THREE.Vector3(),
  1990. new THREE.Vector3(),
  1991. new THREE.Vector3(),
  1992. new THREE.Vector3(),
  1993. new THREE.Vector3(),
  1994. new THREE.Vector3()
  1995. ];
  1996. return function ( matrix ) {
  1997. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  1998. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  1999. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2000. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2001. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2002. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2003. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2004. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2005. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2006. this.makeEmpty();
  2007. this.setFromPoints( points );
  2008. return this;
  2009. };
  2010. }(),
  2011. translate: function ( offset ) {
  2012. this.min.add( offset );
  2013. this.max.add( offset );
  2014. return this;
  2015. },
  2016. equals: function ( box ) {
  2017. return box.min.equals( this.min ) && box.max.equals( this.max );
  2018. },
  2019. clone: function () {
  2020. return new THREE.Box3().copy( this );
  2021. }
  2022. };
  2023. /**
  2024. * @author alteredq / http://alteredqualia.com/
  2025. * @author WestLangley / http://github.com/WestLangley
  2026. * @author bhouston / http://exocortex.com
  2027. */
  2028. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2029. this.elements = new Float32Array(9);
  2030. this.set(
  2031. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2032. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2033. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2034. );
  2035. };
  2036. THREE.Matrix3.prototype = {
  2037. constructor: THREE.Matrix3,
  2038. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2039. var te = this.elements;
  2040. te[0] = n11; te[3] = n12; te[6] = n13;
  2041. te[1] = n21; te[4] = n22; te[7] = n23;
  2042. te[2] = n31; te[5] = n32; te[8] = n33;
  2043. return this;
  2044. },
  2045. identity: function () {
  2046. this.set(
  2047. 1, 0, 0,
  2048. 0, 1, 0,
  2049. 0, 0, 1
  2050. );
  2051. return this;
  2052. },
  2053. copy: function ( m ) {
  2054. var me = m.elements;
  2055. this.set(
  2056. me[0], me[3], me[6],
  2057. me[1], me[4], me[7],
  2058. me[2], me[5], me[8]
  2059. );
  2060. return this;
  2061. },
  2062. multiplyVector3: function ( vector ) {
  2063. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2064. return vector.applyMatrix3( this );
  2065. },
  2066. multiplyVector3Array: function() {
  2067. var v1 = new THREE.Vector3();
  2068. return function ( a ) {
  2069. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2070. v1.x = a[ i ];
  2071. v1.y = a[ i + 1 ];
  2072. v1.z = a[ i + 2 ];
  2073. v1.applyMatrix3(this);
  2074. a[ i ] = v1.x;
  2075. a[ i + 1 ] = v1.y;
  2076. a[ i + 2 ] = v1.z;
  2077. }
  2078. return a;
  2079. };
  2080. }(),
  2081. multiplyScalar: function ( s ) {
  2082. var te = this.elements;
  2083. te[0] *= s; te[3] *= s; te[6] *= s;
  2084. te[1] *= s; te[4] *= s; te[7] *= s;
  2085. te[2] *= s; te[5] *= s; te[8] *= s;
  2086. return this;
  2087. },
  2088. determinant: function () {
  2089. var te = this.elements;
  2090. var a = te[0], b = te[1], c = te[2],
  2091. d = te[3], e = te[4], f = te[5],
  2092. g = te[6], h = te[7], i = te[8];
  2093. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2094. },
  2095. getInverse: function ( matrix, throwOnInvertible ) {
  2096. // input: THREE.Matrix4
  2097. // ( based on http://code.google.com/p/webgl-mjs/ )
  2098. var me = matrix.elements;
  2099. var te = this.elements;
  2100. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2101. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2102. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2103. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2104. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2105. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2106. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2107. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2108. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2109. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2110. // no inverse
  2111. if ( det === 0 ) {
  2112. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2113. if ( throwOnInvertible || false ) {
  2114. throw new Error( msg );
  2115. } else {
  2116. console.warn( msg );
  2117. }
  2118. this.identity();
  2119. return this;
  2120. }
  2121. this.multiplyScalar( 1.0 / det );
  2122. return this;
  2123. },
  2124. transpose: function () {
  2125. var tmp, m = this.elements;
  2126. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2127. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2128. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2129. return this;
  2130. },
  2131. getNormalMatrix: function ( m ) {
  2132. // input: THREE.Matrix4
  2133. this.getInverse( m ).transpose();
  2134. return this;
  2135. },
  2136. transposeIntoArray: function ( r ) {
  2137. var m = this.elements;
  2138. r[ 0 ] = m[ 0 ];
  2139. r[ 1 ] = m[ 3 ];
  2140. r[ 2 ] = m[ 6 ];
  2141. r[ 3 ] = m[ 1 ];
  2142. r[ 4 ] = m[ 4 ];
  2143. r[ 5 ] = m[ 7 ];
  2144. r[ 6 ] = m[ 2 ];
  2145. r[ 7 ] = m[ 5 ];
  2146. r[ 8 ] = m[ 8 ];
  2147. return this;
  2148. },
  2149. clone: function () {
  2150. var te = this.elements;
  2151. return new THREE.Matrix3(
  2152. te[0], te[3], te[6],
  2153. te[1], te[4], te[7],
  2154. te[2], te[5], te[8]
  2155. );
  2156. }
  2157. };
  2158. /**
  2159. * @author mrdoob / http://mrdoob.com/
  2160. * @author supereggbert / http://www.paulbrunt.co.uk/
  2161. * @author philogb / http://blog.thejit.org/
  2162. * @author jordi_ros / http://plattsoft.com
  2163. * @author D1plo1d / http://github.com/D1plo1d
  2164. * @author alteredq / http://alteredqualia.com/
  2165. * @author mikael emtinger / http://gomo.se/
  2166. * @author timknip / http://www.floorplanner.com/
  2167. * @author bhouston / http://exocortex.com
  2168. * @author WestLangley / http://github.com/WestLangley
  2169. */
  2170. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2171. var te = this.elements = new Float32Array( 16 );
  2172. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2173. // we should not support semi specification of Matrix4, it is just weird.
  2174. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2175. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2176. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2177. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2178. };
  2179. THREE.Matrix4.prototype = {
  2180. constructor: THREE.Matrix4,
  2181. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2182. var te = this.elements;
  2183. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2184. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2185. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2186. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2187. return this;
  2188. },
  2189. identity: function () {
  2190. this.set(
  2191. 1, 0, 0, 0,
  2192. 0, 1, 0, 0,
  2193. 0, 0, 1, 0,
  2194. 0, 0, 0, 1
  2195. );
  2196. return this;
  2197. },
  2198. copy: function ( m ) {
  2199. var me = m.elements;
  2200. this.set(
  2201. me[0], me[4], me[8], me[12],
  2202. me[1], me[5], me[9], me[13],
  2203. me[2], me[6], me[10], me[14],
  2204. me[3], me[7], me[11], me[15]
  2205. );
  2206. return this;
  2207. },
  2208. extractPosition: function ( m ) {
  2209. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2210. return this.copyPosition( m );
  2211. },
  2212. copyPosition: function ( m ) {
  2213. var te = this.elements;
  2214. var me = m.elements;
  2215. te[12] = me[12];
  2216. te[13] = me[13];
  2217. te[14] = me[14];
  2218. return this;
  2219. },
  2220. extractRotation: function () {
  2221. var v1 = new THREE.Vector3();
  2222. return function ( m ) {
  2223. var te = this.elements;
  2224. var me = m.elements;
  2225. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2226. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2227. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2228. te[0] = me[0] * scaleX;
  2229. te[1] = me[1] * scaleX;
  2230. te[2] = me[2] * scaleX;
  2231. te[4] = me[4] * scaleY;
  2232. te[5] = me[5] * scaleY;
  2233. te[6] = me[6] * scaleY;
  2234. te[8] = me[8] * scaleZ;
  2235. te[9] = me[9] * scaleZ;
  2236. te[10] = me[10] * scaleZ;
  2237. return this;
  2238. };
  2239. }(),
  2240. setRotationFromEuler: function ( v, order ) {
  2241. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromEuler() has been deprecated in favor of makeRotationFromEuler. Please update your code.' );
  2242. return this.makeRotationFromEuler( v, order );
  2243. },
  2244. makeRotationFromEuler: function ( v, order ) {
  2245. var te = this.elements;
  2246. var x = v.x, y = v.y, z = v.z;
  2247. var a = Math.cos( x ), b = Math.sin( x );
  2248. var c = Math.cos( y ), d = Math.sin( y );
  2249. var e = Math.cos( z ), f = Math.sin( z );
  2250. if ( order === undefined || order === 'XYZ' ) {
  2251. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2252. te[0] = c * e;
  2253. te[4] = - c * f;
  2254. te[8] = d;
  2255. te[1] = af + be * d;
  2256. te[5] = ae - bf * d;
  2257. te[9] = - b * c;
  2258. te[2] = bf - ae * d;
  2259. te[6] = be + af * d;
  2260. te[10] = a * c;
  2261. } else if ( order === 'YXZ' ) {
  2262. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2263. te[0] = ce + df * b;
  2264. te[4] = de * b - cf;
  2265. te[8] = a * d;
  2266. te[1] = a * f;
  2267. te[5] = a * e;
  2268. te[9] = - b;
  2269. te[2] = cf * b - de;
  2270. te[6] = df + ce * b;
  2271. te[10] = a * c;
  2272. } else if ( order === 'ZXY' ) {
  2273. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2274. te[0] = ce - df * b;
  2275. te[4] = - a * f;
  2276. te[8] = de + cf * b;
  2277. te[1] = cf + de * b;
  2278. te[5] = a * e;
  2279. te[9] = df - ce * b;
  2280. te[2] = - a * d;
  2281. te[6] = b;
  2282. te[10] = a * c;
  2283. } else if ( order === 'ZYX' ) {
  2284. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2285. te[0] = c * e;
  2286. te[4] = be * d - af;
  2287. te[8] = ae * d + bf;
  2288. te[1] = c * f;
  2289. te[5] = bf * d + ae;
  2290. te[9] = af * d - be;
  2291. te[2] = - d;
  2292. te[6] = b * c;
  2293. te[10] = a * c;
  2294. } else if ( order === 'YZX' ) {
  2295. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2296. te[0] = c * e;
  2297. te[4] = bd - ac * f;
  2298. te[8] = bc * f + ad;
  2299. te[1] = f;
  2300. te[5] = a * e;
  2301. te[9] = - b * e;
  2302. te[2] = - d * e;
  2303. te[6] = ad * f + bc;
  2304. te[10] = ac - bd * f;
  2305. } else if ( order === 'XZY' ) {
  2306. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2307. te[0] = c * e;
  2308. te[4] = - f;
  2309. te[8] = d * e;
  2310. te[1] = ac * f + bd;
  2311. te[5] = a * e;
  2312. te[9] = ad * f - bc;
  2313. te[2] = bc * f - ad;
  2314. te[6] = b * e;
  2315. te[10] = bd * f + ac;
  2316. }
  2317. // last column
  2318. te[3] = 0;
  2319. te[7] = 0;
  2320. te[11] = 0;
  2321. // bottom row
  2322. te[12] = 0;
  2323. te[13] = 0;
  2324. te[14] = 0;
  2325. te[15] = 1;
  2326. return this;
  2327. },
  2328. setRotationFromQuaternion: function ( q ) {
  2329. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2330. return this.makeRotationFromQuaternion( q );
  2331. },
  2332. makeRotationFromQuaternion: function ( q ) {
  2333. var te = this.elements;
  2334. var x = q.x, y = q.y, z = q.z, w = q.w;
  2335. var x2 = x + x, y2 = y + y, z2 = z + z;
  2336. var xx = x * x2, xy = x * y2, xz = x * z2;
  2337. var yy = y * y2, yz = y * z2, zz = z * z2;
  2338. var wx = w * x2, wy = w * y2, wz = w * z2;
  2339. te[0] = 1 - ( yy + zz );
  2340. te[4] = xy - wz;
  2341. te[8] = xz + wy;
  2342. te[1] = xy + wz;
  2343. te[5] = 1 - ( xx + zz );
  2344. te[9] = yz - wx;
  2345. te[2] = xz - wy;
  2346. te[6] = yz + wx;
  2347. te[10] = 1 - ( xx + yy );
  2348. // last column
  2349. te[3] = 0;
  2350. te[7] = 0;
  2351. te[11] = 0;
  2352. // bottom row
  2353. te[12] = 0;
  2354. te[13] = 0;
  2355. te[14] = 0;
  2356. te[15] = 1;
  2357. return this;
  2358. },
  2359. lookAt: function() {
  2360. var x = new THREE.Vector3();
  2361. var y = new THREE.Vector3();
  2362. var z = new THREE.Vector3();
  2363. return function ( eye, target, up ) {
  2364. var te = this.elements;
  2365. z.subVectors( eye, target ).normalize();
  2366. if ( z.length() === 0 ) {
  2367. z.z = 1;
  2368. }
  2369. x.crossVectors( up, z ).normalize();
  2370. if ( x.length() === 0 ) {
  2371. z.x += 0.0001;
  2372. x.crossVectors( up, z ).normalize();
  2373. }
  2374. y.crossVectors( z, x );
  2375. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2376. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2377. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2378. return this;
  2379. };
  2380. }(),
  2381. multiply: function ( m, n ) {
  2382. if ( n !== undefined ) {
  2383. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2384. return this.multiplyMatrices( m, n );
  2385. }
  2386. return this.multiplyMatrices( this, m );
  2387. },
  2388. multiplyMatrices: function ( a, b ) {
  2389. var ae = a.elements;
  2390. var be = b.elements;
  2391. var te = this.elements;
  2392. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2393. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2394. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2395. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2396. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2397. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2398. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2399. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2400. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2401. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2402. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2403. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2404. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2405. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2406. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2407. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2408. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2409. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2410. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2411. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2412. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2413. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2414. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2415. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2416. return this;
  2417. },
  2418. multiplyToArray: function ( a, b, r ) {
  2419. var te = this.elements;
  2420. this.multiplyMatrices( a, b );
  2421. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2422. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2423. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2424. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2425. return this;
  2426. },
  2427. multiplyScalar: function ( s ) {
  2428. var te = this.elements;
  2429. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2430. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2431. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2432. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2433. return this;
  2434. },
  2435. multiplyVector3: function ( vector ) {
  2436. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2437. return vector.applyProjection( this );
  2438. },
  2439. multiplyVector4: function ( vector ) {
  2440. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2441. return vector.applyMatrix4( this );
  2442. },
  2443. multiplyVector3Array: function() {
  2444. var v1 = new THREE.Vector3();
  2445. return function ( a ) {
  2446. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2447. v1.x = a[ i ];
  2448. v1.y = a[ i + 1 ];
  2449. v1.z = a[ i + 2 ];
  2450. v1.applyProjection( this );
  2451. a[ i ] = v1.x;
  2452. a[ i + 1 ] = v1.y;
  2453. a[ i + 2 ] = v1.z;
  2454. }
  2455. return a;
  2456. };
  2457. }(),
  2458. rotateAxis: function ( v ) {
  2459. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2460. v.transformDirection( this );
  2461. },
  2462. crossVector: function ( vector ) {
  2463. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2464. return vector.applyMatrix4( this );
  2465. },
  2466. determinant: function () {
  2467. var te = this.elements;
  2468. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2469. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2470. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2471. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2472. //TODO: make this more efficient
  2473. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2474. return (
  2475. n41 * (
  2476. +n14 * n23 * n32
  2477. -n13 * n24 * n32
  2478. -n14 * n22 * n33
  2479. +n12 * n24 * n33
  2480. +n13 * n22 * n34
  2481. -n12 * n23 * n34
  2482. ) +
  2483. n42 * (
  2484. +n11 * n23 * n34
  2485. -n11 * n24 * n33
  2486. +n14 * n21 * n33
  2487. -n13 * n21 * n34
  2488. +n13 * n24 * n31
  2489. -n14 * n23 * n31
  2490. ) +
  2491. n43 * (
  2492. +n11 * n24 * n32
  2493. -n11 * n22 * n34
  2494. -n14 * n21 * n32
  2495. +n12 * n21 * n34
  2496. +n14 * n22 * n31
  2497. -n12 * n24 * n31
  2498. ) +
  2499. n44 * (
  2500. -n13 * n22 * n31
  2501. -n11 * n23 * n32
  2502. +n11 * n22 * n33
  2503. +n13 * n21 * n32
  2504. -n12 * n21 * n33
  2505. +n12 * n23 * n31
  2506. )
  2507. );
  2508. },
  2509. transpose: function () {
  2510. var te = this.elements;
  2511. var tmp;
  2512. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2513. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2514. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2515. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2516. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2517. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2518. return this;
  2519. },
  2520. flattenToArray: function ( flat ) {
  2521. var te = this.elements;
  2522. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2523. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2524. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2525. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2526. return flat;
  2527. },
  2528. flattenToArrayOffset: function( flat, offset ) {
  2529. var te = this.elements;
  2530. flat[ offset ] = te[0];
  2531. flat[ offset + 1 ] = te[1];
  2532. flat[ offset + 2 ] = te[2];
  2533. flat[ offset + 3 ] = te[3];
  2534. flat[ offset + 4 ] = te[4];
  2535. flat[ offset + 5 ] = te[5];
  2536. flat[ offset + 6 ] = te[6];
  2537. flat[ offset + 7 ] = te[7];
  2538. flat[ offset + 8 ] = te[8];
  2539. flat[ offset + 9 ] = te[9];
  2540. flat[ offset + 10 ] = te[10];
  2541. flat[ offset + 11 ] = te[11];
  2542. flat[ offset + 12 ] = te[12];
  2543. flat[ offset + 13 ] = te[13];
  2544. flat[ offset + 14 ] = te[14];
  2545. flat[ offset + 15 ] = te[15];
  2546. return flat;
  2547. },
  2548. getPosition: function() {
  2549. var v1 = new THREE.Vector3();
  2550. return function () {
  2551. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.getPositionFromMatrix( matrix ) instead.' );
  2552. var te = this.elements;
  2553. return v1.set( te[12], te[13], te[14] );
  2554. };
  2555. }(),
  2556. setPosition: function ( v ) {
  2557. var te = this.elements;
  2558. te[12] = v.x;
  2559. te[13] = v.y;
  2560. te[14] = v.z;
  2561. return this;
  2562. },
  2563. getInverse: function ( m, throwOnInvertible ) {
  2564. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2565. var te = this.elements;
  2566. var me = m.elements;
  2567. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2568. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2569. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2570. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2571. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2572. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2573. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2574. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2575. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2576. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2577. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2578. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2579. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2580. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2581. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2582. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2583. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2584. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2585. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2586. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2587. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2588. if ( det == 0 ) {
  2589. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2590. if ( throwOnInvertible || false ) {
  2591. throw new Error( msg );
  2592. } else {
  2593. console.warn( msg );
  2594. }
  2595. this.identity();
  2596. return this;
  2597. }
  2598. this.multiplyScalar( 1 / det );
  2599. return this;
  2600. },
  2601. translate: function ( v ) {
  2602. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2603. },
  2604. rotateX: function ( angle ) {
  2605. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2606. },
  2607. rotateY: function ( angle ) {
  2608. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2609. },
  2610. rotateZ: function ( angle ) {
  2611. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2612. },
  2613. rotateByAxis: function ( axis, angle ) {
  2614. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2615. },
  2616. scale: function ( v ) {
  2617. var te = this.elements;
  2618. var x = v.x, y = v.y, z = v.z;
  2619. te[0] *= x; te[4] *= y; te[8] *= z;
  2620. te[1] *= x; te[5] *= y; te[9] *= z;
  2621. te[2] *= x; te[6] *= y; te[10] *= z;
  2622. te[3] *= x; te[7] *= y; te[11] *= z;
  2623. return this;
  2624. },
  2625. getMaxScaleOnAxis: function () {
  2626. var te = this.elements;
  2627. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2628. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2629. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2630. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2631. },
  2632. makeTranslation: function ( x, y, z ) {
  2633. this.set(
  2634. 1, 0, 0, x,
  2635. 0, 1, 0, y,
  2636. 0, 0, 1, z,
  2637. 0, 0, 0, 1
  2638. );
  2639. return this;
  2640. },
  2641. makeRotationX: function ( theta ) {
  2642. var c = Math.cos( theta ), s = Math.sin( theta );
  2643. this.set(
  2644. 1, 0, 0, 0,
  2645. 0, c, -s, 0,
  2646. 0, s, c, 0,
  2647. 0, 0, 0, 1
  2648. );
  2649. return this;
  2650. },
  2651. makeRotationY: function ( theta ) {
  2652. var c = Math.cos( theta ), s = Math.sin( theta );
  2653. this.set(
  2654. c, 0, s, 0,
  2655. 0, 1, 0, 0,
  2656. -s, 0, c, 0,
  2657. 0, 0, 0, 1
  2658. );
  2659. return this;
  2660. },
  2661. makeRotationZ: function ( theta ) {
  2662. var c = Math.cos( theta ), s = Math.sin( theta );
  2663. this.set(
  2664. c, -s, 0, 0,
  2665. s, c, 0, 0,
  2666. 0, 0, 1, 0,
  2667. 0, 0, 0, 1
  2668. );
  2669. return this;
  2670. },
  2671. makeRotationAxis: function ( axis, angle ) {
  2672. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2673. var c = Math.cos( angle );
  2674. var s = Math.sin( angle );
  2675. var t = 1 - c;
  2676. var x = axis.x, y = axis.y, z = axis.z;
  2677. var tx = t * x, ty = t * y;
  2678. this.set(
  2679. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2680. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2681. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2682. 0, 0, 0, 1
  2683. );
  2684. return this;
  2685. },
  2686. makeScale: function ( x, y, z ) {
  2687. this.set(
  2688. x, 0, 0, 0,
  2689. 0, y, 0, 0,
  2690. 0, 0, z, 0,
  2691. 0, 0, 0, 1
  2692. );
  2693. return this;
  2694. },
  2695. compose: function ( position, quaternion, scale ) {
  2696. console.warn( 'DEPRECATED: Matrix4\'s .compose() has been deprecated in favor of makeFromPositionQuaternionScale. Please update your code.' );
  2697. return this.makeFromPositionQuaternionScale( position, quaternion, scale );
  2698. },
  2699. makeFromPositionQuaternionScale: function ( position, quaternion, scale ) {
  2700. this.makeRotationFromQuaternion( quaternion );
  2701. this.scale( scale );
  2702. this.setPosition( position );
  2703. return this;
  2704. },
  2705. makeFromPositionEulerScale: function ( position, rotation, eulerOrder, scale ) {
  2706. this.makeRotationFromEuler( rotation, eulerOrder );
  2707. this.scale( scale );
  2708. this.setPosition( position );
  2709. return this;
  2710. },
  2711. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2712. var te = this.elements;
  2713. var x = 2 * near / ( right - left );
  2714. var y = 2 * near / ( top - bottom );
  2715. var a = ( right + left ) / ( right - left );
  2716. var b = ( top + bottom ) / ( top - bottom );
  2717. var c = - ( far + near ) / ( far - near );
  2718. var d = - 2 * far * near / ( far - near );
  2719. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2720. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2721. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2722. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2723. return this;
  2724. },
  2725. makePerspective: function ( fov, aspect, near, far ) {
  2726. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2727. var ymin = - ymax;
  2728. var xmin = ymin * aspect;
  2729. var xmax = ymax * aspect;
  2730. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2731. },
  2732. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2733. var te = this.elements;
  2734. var w = right - left;
  2735. var h = top - bottom;
  2736. var p = far - near;
  2737. var x = ( right + left ) / w;
  2738. var y = ( top + bottom ) / h;
  2739. var z = ( far + near ) / p;
  2740. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2741. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2742. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2743. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2744. return this;
  2745. },
  2746. clone: function () {
  2747. var te = this.elements;
  2748. return new THREE.Matrix4(
  2749. te[0], te[4], te[8], te[12],
  2750. te[1], te[5], te[9], te[13],
  2751. te[2], te[6], te[10], te[14],
  2752. te[3], te[7], te[11], te[15]
  2753. );
  2754. }
  2755. };
  2756. THREE.extend( THREE.Matrix4.prototype, {
  2757. decompose: function() {
  2758. var x = new THREE.Vector3();
  2759. var y = new THREE.Vector3();
  2760. var z = new THREE.Vector3();
  2761. var matrix = new THREE.Matrix4();
  2762. return function ( position, quaternion, scale ) {
  2763. var te = this.elements;
  2764. // grab the axis vectors
  2765. x.set( te[0], te[1], te[2] );
  2766. y.set( te[4], te[5], te[6] );
  2767. z.set( te[8], te[9], te[10] );
  2768. position = ( position instanceof THREE.Vector3 ) ? position : new THREE.Vector3();
  2769. quaternion = ( quaternion instanceof THREE.Quaternion ) ? quaternion : new THREE.Quaternion();
  2770. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2771. scale.x = x.length();
  2772. scale.y = y.length();
  2773. scale.z = z.length();
  2774. position.x = te[12];
  2775. position.y = te[13];
  2776. position.z = te[14];
  2777. // scale the rotation part
  2778. matrix.copy( this );
  2779. matrix.elements[0] /= scale.x;
  2780. matrix.elements[1] /= scale.x;
  2781. matrix.elements[2] /= scale.x;
  2782. matrix.elements[4] /= scale.y;
  2783. matrix.elements[5] /= scale.y;
  2784. matrix.elements[6] /= scale.y;
  2785. matrix.elements[8] /= scale.z;
  2786. matrix.elements[9] /= scale.z;
  2787. matrix.elements[10] /= scale.z;
  2788. quaternion.setFromRotationMatrix( matrix );
  2789. return [ position, quaternion, scale ];
  2790. };
  2791. }()
  2792. } );
  2793. /**
  2794. * @author bhouston / http://exocortex.com
  2795. */
  2796. THREE.Ray = function ( origin, direction ) {
  2797. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2798. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2799. };
  2800. THREE.Ray.prototype = {
  2801. constructor: THREE.Ray,
  2802. set: function ( origin, direction ) {
  2803. this.origin.copy( origin );
  2804. this.direction.copy( direction );
  2805. return this;
  2806. },
  2807. copy: function ( ray ) {
  2808. this.origin.copy( ray.origin );
  2809. this.direction.copy( ray.direction );
  2810. return this;
  2811. },
  2812. at: function( t, optionalTarget ) {
  2813. var result = optionalTarget || new THREE.Vector3();
  2814. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2815. },
  2816. recast: function() {
  2817. var v1 = new THREE.Vector3();
  2818. return function ( t ) {
  2819. this.origin.copy( this.at( t, v1 ) );
  2820. return this;
  2821. };
  2822. }(),
  2823. closestPointToPoint: function ( point, optionalTarget ) {
  2824. var result = optionalTarget || new THREE.Vector3();
  2825. result.subVectors( point, this.origin );
  2826. var directionDistance = result.dot( this.direction );
  2827. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2828. },
  2829. distanceToPoint: function() {
  2830. var v1 = new THREE.Vector3();
  2831. return function ( point ) {
  2832. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  2833. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2834. return v1.distanceTo( point );
  2835. };
  2836. }(),
  2837. isIntersectionSphere: function( sphere ) {
  2838. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  2839. },
  2840. isIntersectionPlane: function ( plane ) {
  2841. // check if the line and plane are non-perpendicular, if they
  2842. // eventually they will intersect.
  2843. var denominator = plane.normal.dot( this.direction );
  2844. if ( denominator != 0 ) {
  2845. return true;
  2846. }
  2847. // line is coplanar, return origin
  2848. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2849. return true;
  2850. }
  2851. return false;
  2852. },
  2853. distanceToPlane: function ( plane ) {
  2854. var denominator = plane.normal.dot( this.direction );
  2855. if ( denominator == 0 ) {
  2856. // line is coplanar, return origin
  2857. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2858. return 0;
  2859. }
  2860. // Unsure if this is the correct method to handle this case.
  2861. return undefined;
  2862. }
  2863. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2864. return t;
  2865. },
  2866. intersectPlane: function ( plane, optionalTarget ) {
  2867. var t = this.distanceToPlane( plane );
  2868. if ( t === undefined ) {
  2869. return undefined;
  2870. }
  2871. return this.at( t, optionalTarget );
  2872. },
  2873. applyMatrix4: function ( matrix4 ) {
  2874. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  2875. this.origin.applyMatrix4( matrix4 );
  2876. this.direction.sub( this.origin );
  2877. return this;
  2878. },
  2879. equals: function ( ray ) {
  2880. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  2881. },
  2882. clone: function () {
  2883. return new THREE.Ray().copy( this );
  2884. }
  2885. };
  2886. /**
  2887. * @author bhouston / http://exocortex.com
  2888. * @author mrdoob / http://mrdoob.com/
  2889. */
  2890. THREE.Sphere = function ( center, radius ) {
  2891. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  2892. this.radius = ( radius !== undefined ) ? radius : 0;
  2893. };
  2894. THREE.Sphere.prototype = {
  2895. constructor: THREE.Sphere,
  2896. set: function ( center, radius ) {
  2897. this.center.copy( center );
  2898. this.radius = radius;
  2899. return this;
  2900. },
  2901. setFromCenterAndPoints: function ( center, points ) {
  2902. var maxRadiusSq = 0;
  2903. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2904. var radiusSq = center.distanceToSquared( points[ i ] );
  2905. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2906. }
  2907. this.center = center;
  2908. this.radius = Math.sqrt( maxRadiusSq );
  2909. return this;
  2910. },
  2911. copy: function ( sphere ) {
  2912. this.center.copy( sphere.center );
  2913. this.radius = sphere.radius;
  2914. return this;
  2915. },
  2916. empty: function () {
  2917. return ( this.radius <= 0 );
  2918. },
  2919. containsPoint: function ( point ) {
  2920. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2921. },
  2922. distanceToPoint: function ( point ) {
  2923. return ( point.distanceTo( this.center ) - this.radius );
  2924. },
  2925. intersectsSphere: function ( sphere ) {
  2926. var radiusSum = this.radius + sphere.radius;
  2927. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2928. },
  2929. clampPoint: function ( point, optionalTarget ) {
  2930. var deltaLengthSq = this.center.distanceToSquared( point );
  2931. var result = optionalTarget || new THREE.Vector3();
  2932. result.copy( point );
  2933. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2934. result.sub( this.center ).normalize();
  2935. result.multiplyScalar( this.radius ).add( this.center );
  2936. }
  2937. return result;
  2938. },
  2939. getBoundingBox: function ( optionalTarget ) {
  2940. var box = optionalTarget || new THREE.Box3();
  2941. box.set( this.center, this.center );
  2942. box.expandByScalar( this.radius );
  2943. return box;
  2944. },
  2945. applyMatrix4: function ( matrix ) {
  2946. this.center.applyMatrix4( matrix );
  2947. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2948. return this;
  2949. },
  2950. translate: function ( offset ) {
  2951. this.center.add( offset );
  2952. return this;
  2953. },
  2954. equals: function ( sphere ) {
  2955. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2956. },
  2957. clone: function () {
  2958. return new THREE.Sphere().copy( this );
  2959. }
  2960. };
  2961. /**
  2962. * @author mrdoob / http://mrdoob.com/
  2963. * @author alteredq / http://alteredqualia.com/
  2964. * @author bhouston / http://exocortex.com
  2965. */
  2966. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  2967. this.planes = [
  2968. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  2969. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  2970. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  2971. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  2972. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  2973. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  2974. ];
  2975. };
  2976. THREE.Frustum.prototype = {
  2977. constructor: THREE.Frustum,
  2978. set: function ( p0, p1, p2, p3, p4, p5 ) {
  2979. var planes = this.planes;
  2980. planes[0].copy( p0 );
  2981. planes[1].copy( p1 );
  2982. planes[2].copy( p2 );
  2983. planes[3].copy( p3 );
  2984. planes[4].copy( p4 );
  2985. planes[5].copy( p5 );
  2986. return this;
  2987. },
  2988. copy: function ( frustum ) {
  2989. var planes = this.planes;
  2990. for( var i = 0; i < 6; i ++ ) {
  2991. planes[i].copy( frustum.planes[i] );
  2992. }
  2993. return this;
  2994. },
  2995. setFromMatrix: function ( m ) {
  2996. var planes = this.planes;
  2997. var me = m.elements;
  2998. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  2999. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3000. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3001. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3002. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3003. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3004. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3005. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3006. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3007. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3008. return this;
  3009. },
  3010. intersectsObject: function () {
  3011. var center = new THREE.Vector3();
  3012. return function ( object ) {
  3013. // this method is expanded inlined for performance reasons.
  3014. var matrix = object.matrixWorld;
  3015. var planes = this.planes;
  3016. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  3017. center.getPositionFromMatrix( matrix );
  3018. for ( var i = 0; i < 6; i ++ ) {
  3019. var distance = planes[ i ].distanceToPoint( center );
  3020. if ( distance < negRadius ) {
  3021. return false;
  3022. }
  3023. }
  3024. return true;
  3025. };
  3026. }(),
  3027. intersectsSphere: function ( sphere ) {
  3028. var planes = this.planes;
  3029. var center = sphere.center;
  3030. var negRadius = -sphere.radius;
  3031. for ( var i = 0; i < 6; i ++ ) {
  3032. var distance = planes[ i ].distanceToPoint( center );
  3033. if ( distance < negRadius ) {
  3034. return false;
  3035. }
  3036. }
  3037. return true;
  3038. },
  3039. containsPoint: function ( point ) {
  3040. var planes = this.planes;
  3041. for ( var i = 0; i < 6; i ++ ) {
  3042. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3043. return false;
  3044. }
  3045. }
  3046. return true;
  3047. },
  3048. clone: function () {
  3049. return new THREE.Frustum().copy( this );
  3050. }
  3051. };
  3052. /**
  3053. * @author bhouston / http://exocortex.com
  3054. */
  3055. THREE.Plane = function ( normal, constant ) {
  3056. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3057. this.constant = ( constant !== undefined ) ? constant : 0;
  3058. };
  3059. THREE.Plane.prototype = {
  3060. constructor: THREE.Plane,
  3061. set: function ( normal, constant ) {
  3062. this.normal.copy( normal );
  3063. this.constant = constant;
  3064. return this;
  3065. },
  3066. setComponents: function ( x, y, z, w ) {
  3067. this.normal.set( x, y, z );
  3068. this.constant = w;
  3069. return this;
  3070. },
  3071. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3072. this.normal.copy( normal );
  3073. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3074. return this;
  3075. },
  3076. setFromCoplanarPoints: function() {
  3077. var v1 = new THREE.Vector3();
  3078. var v2 = new THREE.Vector3();
  3079. return function ( a, b, c ) {
  3080. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3081. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3082. this.setFromNormalAndCoplanarPoint( normal, a );
  3083. return this;
  3084. };
  3085. }(),
  3086. copy: function ( plane ) {
  3087. this.normal.copy( plane.normal );
  3088. this.constant = plane.constant;
  3089. return this;
  3090. },
  3091. normalize: function () {
  3092. // Note: will lead to a divide by zero if the plane is invalid.
  3093. var inverseNormalLength = 1.0 / this.normal.length();
  3094. this.normal.multiplyScalar( inverseNormalLength );
  3095. this.constant *= inverseNormalLength;
  3096. return this;
  3097. },
  3098. negate: function () {
  3099. this.constant *= -1;
  3100. this.normal.negate();
  3101. return this;
  3102. },
  3103. distanceToPoint: function ( point ) {
  3104. return this.normal.dot( point ) + this.constant;
  3105. },
  3106. distanceToSphere: function ( sphere ) {
  3107. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3108. },
  3109. projectPoint: function ( point, optionalTarget ) {
  3110. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3111. },
  3112. orthoPoint: function ( point, optionalTarget ) {
  3113. var perpendicularMagnitude = this.distanceToPoint( point );
  3114. var result = optionalTarget || new THREE.Vector3();
  3115. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3116. },
  3117. isIntersectionLine: function ( line ) {
  3118. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3119. var startSign = this.distanceToPoint( line.start );
  3120. var endSign = this.distanceToPoint( line.end );
  3121. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3122. },
  3123. intersectLine: function() {
  3124. var v1 = new THREE.Vector3();
  3125. return function ( line, optionalTarget ) {
  3126. var result = optionalTarget || new THREE.Vector3();
  3127. var direction = line.delta( v1 );
  3128. var denominator = this.normal.dot( direction );
  3129. if ( denominator == 0 ) {
  3130. // line is coplanar, return origin
  3131. if( this.distanceToPoint( line.start ) == 0 ) {
  3132. return result.copy( line.start );
  3133. }
  3134. // Unsure if this is the correct method to handle this case.
  3135. return undefined;
  3136. }
  3137. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3138. if( t < 0 || t > 1 ) {
  3139. return undefined;
  3140. }
  3141. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3142. };
  3143. }(),
  3144. coplanarPoint: function ( optionalTarget ) {
  3145. var result = optionalTarget || new THREE.Vector3();
  3146. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3147. },
  3148. applyMatrix4: function() {
  3149. var v1 = new THREE.Vector3();
  3150. var v2 = new THREE.Vector3();
  3151. return function ( matrix, optionalNormalMatrix ) {
  3152. // compute new normal based on theory here:
  3153. // http://www.songho.ca/opengl/gl_normaltransform.html
  3154. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getNormalMatrix( matrix );
  3155. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3156. var newCoplanarPoint = this.coplanarPoint( v2 );
  3157. newCoplanarPoint.applyMatrix4( matrix );
  3158. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3159. return this;
  3160. };
  3161. }(),
  3162. translate: function ( offset ) {
  3163. this.constant = this.constant - offset.dot( this.normal );
  3164. return this;
  3165. },
  3166. equals: function ( plane ) {
  3167. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3168. },
  3169. clone: function () {
  3170. return new THREE.Plane().copy( this );
  3171. }
  3172. };
  3173. /**
  3174. * @author alteredq / http://alteredqualia.com/
  3175. * @author mrdoob / http://mrdoob.com/
  3176. */
  3177. THREE.Math = {
  3178. generateUUID: function () {
  3179. // http://www.broofa.com/Tools/Math.uuid.htm
  3180. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3181. var uuid = new Array(36);
  3182. var rnd = 0, r;
  3183. return function () {
  3184. for ( var i = 0; i < 36; i ++ ) {
  3185. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3186. uuid[ i ] = '-';
  3187. } else if ( i == 14 ) {
  3188. uuid[ i ] = '4';
  3189. } else {
  3190. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3191. r = rnd & 0xf;
  3192. rnd = rnd >> 4;
  3193. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3194. }
  3195. }
  3196. return uuid.join('');
  3197. };
  3198. }(),
  3199. // Clamp value to range <a, b>
  3200. clamp: function ( x, a, b ) {
  3201. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3202. },
  3203. // Clamp value to range <a, inf)
  3204. clampBottom: function ( x, a ) {
  3205. return x < a ? a : x;
  3206. },
  3207. // Linear mapping from range <a1, a2> to range <b1, b2>
  3208. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3209. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3210. },
  3211. // http://en.wikipedia.org/wiki/Smoothstep
  3212. smoothstep: function ( x, min, max ) {
  3213. if ( x <= min ) return 0;
  3214. if ( x >= max ) return 1;
  3215. x = ( x - min )/( max - min );
  3216. return x*x*(3 - 2*x);
  3217. },
  3218. smootherstep: function ( x, min, max ) {
  3219. if ( x <= min ) return 0;
  3220. if ( x >= max ) return 1;
  3221. x = ( x - min )/( max - min );
  3222. return x*x*x*(x*(x*6 - 15) + 10);
  3223. },
  3224. // Random float from <0, 1> with 16 bits of randomness
  3225. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3226. random16: function () {
  3227. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3228. },
  3229. // Random integer from <low, high> interval
  3230. randInt: function ( low, high ) {
  3231. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3232. },
  3233. // Random float from <low, high> interval
  3234. randFloat: function ( low, high ) {
  3235. return low + Math.random() * ( high - low );
  3236. },
  3237. // Random float from <-range/2, range/2> interval
  3238. randFloatSpread: function ( range ) {
  3239. return range * ( 0.5 - Math.random() );
  3240. },
  3241. sign: function ( x ) {
  3242. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3243. },
  3244. degToRad: function() {
  3245. var degreeToRadiansFactor = Math.PI / 180;
  3246. return function ( degrees ) {
  3247. return degrees * degreeToRadiansFactor;
  3248. };
  3249. }(),
  3250. radToDeg: function() {
  3251. var radianToDegreesFactor = 180 / Math.PI;
  3252. return function ( radians ) {
  3253. return radians * radianToDegreesFactor;
  3254. };
  3255. }()
  3256. };
  3257. /**
  3258. * Spline from Tween.js, slightly optimized (and trashed)
  3259. * http://sole.github.com/tween.js/examples/05_spline.html
  3260. *
  3261. * @author mrdoob / http://mrdoob.com/
  3262. * @author alteredq / http://alteredqualia.com/
  3263. */
  3264. THREE.Spline = function ( points ) {
  3265. this.points = points;
  3266. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3267. point, intPoint, weight, w2, w3,
  3268. pa, pb, pc, pd;
  3269. this.initFromArray = function( a ) {
  3270. this.points = [];
  3271. for ( var i = 0; i < a.length; i++ ) {
  3272. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3273. }
  3274. };
  3275. this.getPoint = function ( k ) {
  3276. point = ( this.points.length - 1 ) * k;
  3277. intPoint = Math.floor( point );
  3278. weight = point - intPoint;
  3279. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3280. c[ 1 ] = intPoint;
  3281. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3282. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3283. pa = this.points[ c[ 0 ] ];
  3284. pb = this.points[ c[ 1 ] ];
  3285. pc = this.points[ c[ 2 ] ];
  3286. pd = this.points[ c[ 3 ] ];
  3287. w2 = weight * weight;
  3288. w3 = weight * w2;
  3289. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3290. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3291. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3292. return v3;
  3293. };
  3294. this.getControlPointsArray = function () {
  3295. var i, p, l = this.points.length,
  3296. coords = [];
  3297. for ( i = 0; i < l; i ++ ) {
  3298. p = this.points[ i ];
  3299. coords[ i ] = [ p.x, p.y, p.z ];
  3300. }
  3301. return coords;
  3302. };
  3303. // approximate length by summing linear segments
  3304. this.getLength = function ( nSubDivisions ) {
  3305. var i, index, nSamples, position,
  3306. point = 0, intPoint = 0, oldIntPoint = 0,
  3307. oldPosition = new THREE.Vector3(),
  3308. tmpVec = new THREE.Vector3(),
  3309. chunkLengths = [],
  3310. totalLength = 0;
  3311. // first point has 0 length
  3312. chunkLengths[ 0 ] = 0;
  3313. if ( !nSubDivisions ) nSubDivisions = 100;
  3314. nSamples = this.points.length * nSubDivisions;
  3315. oldPosition.copy( this.points[ 0 ] );
  3316. for ( i = 1; i < nSamples; i ++ ) {
  3317. index = i / nSamples;
  3318. position = this.getPoint( index );
  3319. tmpVec.copy( position );
  3320. totalLength += tmpVec.distanceTo( oldPosition );
  3321. oldPosition.copy( position );
  3322. point = ( this.points.length - 1 ) * index;
  3323. intPoint = Math.floor( point );
  3324. if ( intPoint != oldIntPoint ) {
  3325. chunkLengths[ intPoint ] = totalLength;
  3326. oldIntPoint = intPoint;
  3327. }
  3328. }
  3329. // last point ends with total length
  3330. chunkLengths[ chunkLengths.length ] = totalLength;
  3331. return { chunks: chunkLengths, total: totalLength };
  3332. };
  3333. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3334. var i, j,
  3335. index, indexCurrent, indexNext,
  3336. linearDistance, realDistance,
  3337. sampling, position,
  3338. newpoints = [],
  3339. tmpVec = new THREE.Vector3(),
  3340. sl = this.getLength();
  3341. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3342. for ( i = 1; i < this.points.length; i++ ) {
  3343. //tmpVec.copy( this.points[ i - 1 ] );
  3344. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3345. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3346. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3347. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3348. indexNext = i / ( this.points.length - 1 );
  3349. for ( j = 1; j < sampling - 1; j++ ) {
  3350. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3351. position = this.getPoint( index );
  3352. newpoints.push( tmpVec.copy( position ).clone() );
  3353. }
  3354. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3355. }
  3356. this.points = newpoints;
  3357. };
  3358. // Catmull-Rom
  3359. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3360. var v0 = ( p2 - p0 ) * 0.5,
  3361. v1 = ( p3 - p1 ) * 0.5;
  3362. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3363. };
  3364. };
  3365. /**
  3366. * @author bhouston / http://exocortex.com
  3367. * @author mrdoob / http://mrdoob.com/
  3368. */
  3369. THREE.Triangle = function ( a, b, c ) {
  3370. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3371. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3372. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3373. };
  3374. THREE.Triangle.normal = function() {
  3375. var v0 = new THREE.Vector3();
  3376. return function ( a, b, c, optionalTarget ) {
  3377. var result = optionalTarget || new THREE.Vector3();
  3378. result.subVectors( c, b );
  3379. v0.subVectors( a, b );
  3380. result.cross( v0 );
  3381. var resultLengthSq = result.lengthSq();
  3382. if( resultLengthSq > 0 ) {
  3383. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3384. }
  3385. return result.set( 0, 0, 0 );
  3386. };
  3387. }();
  3388. // static/instance method to calculate barycoordinates
  3389. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3390. THREE.Triangle.barycoordFromPoint = function() {
  3391. var v0 = new THREE.Vector3();
  3392. var v1 = new THREE.Vector3();
  3393. var v2 = new THREE.Vector3();
  3394. return function ( point, a, b, c, optionalTarget ) {
  3395. v0.subVectors( c, a );
  3396. v1.subVectors( b, a );
  3397. v2.subVectors( point, a );
  3398. var dot00 = v0.dot( v0 );
  3399. var dot01 = v0.dot( v1 );
  3400. var dot02 = v0.dot( v2 );
  3401. var dot11 = v1.dot( v1 );
  3402. var dot12 = v1.dot( v2 );
  3403. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3404. var result = optionalTarget || new THREE.Vector3();
  3405. // colinear or singular triangle
  3406. if( denom == 0 ) {
  3407. // arbitrary location outside of triangle?
  3408. // not sure if this is the best idea, maybe should be returning undefined
  3409. return result.set( -2, -1, -1 );
  3410. }
  3411. var invDenom = 1 / denom;
  3412. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3413. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3414. // barycoordinates must always sum to 1
  3415. return result.set( 1 - u - v, v, u );
  3416. };
  3417. }();
  3418. THREE.Triangle.containsPoint = function() {
  3419. var v1 = new THREE.Vector3();
  3420. return function ( point, a, b, c ) {
  3421. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3422. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3423. };
  3424. }();
  3425. THREE.Triangle.prototype = {
  3426. constructor: THREE.Triangle,
  3427. set: function ( a, b, c ) {
  3428. this.a.copy( a );
  3429. this.b.copy( b );
  3430. this.c.copy( c );
  3431. return this;
  3432. },
  3433. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3434. this.a.copy( points[i0] );
  3435. this.b.copy( points[i1] );
  3436. this.c.copy( points[i2] );
  3437. return this;
  3438. },
  3439. copy: function ( triangle ) {
  3440. this.a.copy( triangle.a );
  3441. this.b.copy( triangle.b );
  3442. this.c.copy( triangle.c );
  3443. return this;
  3444. },
  3445. area: function() {
  3446. var v0 = new THREE.Vector3();
  3447. var v1 = new THREE.Vector3();
  3448. return function () {
  3449. v0.subVectors( this.c, this.b );
  3450. v1.subVectors( this.a, this.b );
  3451. return v0.cross( v1 ).length() * 0.5;
  3452. };
  3453. }(),
  3454. midpoint: function ( optionalTarget ) {
  3455. var result = optionalTarget || new THREE.Vector3();
  3456. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3457. },
  3458. normal: function ( optionalTarget ) {
  3459. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3460. },
  3461. plane: function ( optionalTarget ) {
  3462. var result = optionalTarget || new THREE.Plane();
  3463. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3464. },
  3465. barycoordFromPoint: function ( point, optionalTarget ) {
  3466. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3467. },
  3468. containsPoint: function ( point ) {
  3469. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3470. },
  3471. equals: function ( triangle ) {
  3472. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3473. },
  3474. clone: function () {
  3475. return new THREE.Triangle().copy( this );
  3476. }
  3477. };
  3478. /**
  3479. * @author mrdoob / http://mrdoob.com/
  3480. */
  3481. THREE.Vertex = function ( v ) {
  3482. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3483. return v;
  3484. };
  3485. /**
  3486. * @author mrdoob / http://mrdoob.com/
  3487. */
  3488. THREE.UV = function ( u, v ) {
  3489. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3490. return new THREE.Vector2( u, v );
  3491. };
  3492. /**
  3493. * @author alteredq / http://alteredqualia.com/
  3494. */
  3495. THREE.Clock = function ( autoStart ) {
  3496. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3497. this.startTime = 0;
  3498. this.oldTime = 0;
  3499. this.elapsedTime = 0;
  3500. this.running = false;
  3501. };
  3502. THREE.Clock.prototype = {
  3503. constructor: THREE.Clock,
  3504. start: function () {
  3505. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  3506. ? self.performance.now()
  3507. : Date.now();
  3508. this.oldTime = this.startTime;
  3509. this.running = true;
  3510. },
  3511. stop: function () {
  3512. this.getElapsedTime();
  3513. this.running = false;
  3514. },
  3515. getElapsedTime: function () {
  3516. this.getDelta();
  3517. return this.elapsedTime;
  3518. },
  3519. getDelta: function () {
  3520. var diff = 0;
  3521. if ( this.autoStart && ! this.running ) {
  3522. this.start();
  3523. }
  3524. if ( this.running ) {
  3525. var newTime = self.performance !== undefined && self.performance.now !== undefined
  3526. ? self.performance.now()
  3527. : Date.now();
  3528. diff = 0.001 * ( newTime - this.oldTime );
  3529. this.oldTime = newTime;
  3530. this.elapsedTime += diff;
  3531. }
  3532. return diff;
  3533. }
  3534. };
  3535. /**
  3536. * https://github.com/mrdoob/eventdispatcher.js/
  3537. */
  3538. THREE.EventDispatcher = function () {}
  3539. THREE.EventDispatcher.prototype = {
  3540. constructor: THREE.EventDispatcher,
  3541. addEventListener: function ( type, listener ) {
  3542. if ( this._listeners === undefined ) this._listeners = {};
  3543. var listeners = this._listeners;
  3544. if ( listeners[ type ] === undefined ) {
  3545. listeners[ type ] = [];
  3546. }
  3547. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3548. listeners[ type ].push( listener );
  3549. }
  3550. },
  3551. hasEventListener: function ( type, listener ) {
  3552. if ( this._listeners === undefined ) return false;
  3553. var listeners = this._listeners;
  3554. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3555. return true;
  3556. }
  3557. return false;
  3558. },
  3559. removeEventListener: function ( type, listener ) {
  3560. if ( this._listeners === undefined ) return;
  3561. var listeners = this._listeners;
  3562. var index = listeners[ type ].indexOf( listener );
  3563. if ( index !== - 1 ) {
  3564. listeners[ type ].splice( index, 1 );
  3565. }
  3566. },
  3567. dispatchEvent: function ( event ) {
  3568. if ( this._listeners === undefined ) return;
  3569. var listeners = this._listeners;
  3570. var listenerArray = listeners[ event.type ];
  3571. if ( listenerArray !== undefined ) {
  3572. event.target = this;
  3573. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3574. listenerArray[ i ].call( this, event );
  3575. }
  3576. }
  3577. }
  3578. };
  3579. /**
  3580. * @author mrdoob / http://mrdoob.com/
  3581. * @author bhouston / http://exocortex.com/
  3582. */
  3583. ( function ( THREE ) {
  3584. THREE.Raycaster = function ( origin, direction, near, far ) {
  3585. this.ray = new THREE.Ray( origin, direction );
  3586. // normalized ray.direction required for accurate distance calculations
  3587. if ( this.ray.direction.lengthSq() > 0 ) {
  3588. this.ray.direction.normalize();
  3589. }
  3590. this.near = near || 0;
  3591. this.far = far || Infinity;
  3592. };
  3593. var sphere = new THREE.Sphere();
  3594. var localRay = new THREE.Ray();
  3595. var facePlane = new THREE.Plane();
  3596. var intersectPoint = new THREE.Vector3();
  3597. var matrixPosition = new THREE.Vector3();
  3598. var inverseMatrix = new THREE.Matrix4();
  3599. var descSort = function ( a, b ) {
  3600. return a.distance - b.distance;
  3601. };
  3602. var intersectObject = function ( object, raycaster, intersects ) {
  3603. if ( object instanceof THREE.Particle ) {
  3604. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3605. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  3606. if ( distance > object.scale.x ) {
  3607. return intersects;
  3608. }
  3609. intersects.push( {
  3610. distance: distance,
  3611. point: object.position,
  3612. face: null,
  3613. object: object
  3614. } );
  3615. } else if ( object instanceof THREE.LOD ) {
  3616. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3617. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  3618. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  3619. } else if (object instanceof THREE.Mesh ) {
  3620. // Checking boundingSphere distance to ray
  3621. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3622. sphere.set( matrixPosition, object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  3623. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  3624. return intersects;
  3625. }
  3626. var geometry = object.geometry;
  3627. var vertices = geometry.vertices;
  3628. if ( geometry instanceof THREE.BufferGeometry ) {
  3629. var material = object.material;
  3630. if ( material === undefined ) return intersects;
  3631. if ( ! geometry.dynamic ) return intersects;
  3632. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3633. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3634. var side = object.material.side;
  3635. var a, b, c;
  3636. var precision = raycaster.precision;
  3637. inverseMatrix.getInverse( object.matrixWorld );
  3638. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3639. var fl;
  3640. var indexed = false;
  3641. if ( geometry.attributes.index ) {
  3642. indexed = true;
  3643. fl = geometry.attributes.index.numItems / 3;
  3644. } else {
  3645. fl = geometry.attributes.position.numItems / 9;
  3646. }
  3647. var vA = new THREE.Vector3();
  3648. var vB = new THREE.Vector3();
  3649. var vC = new THREE.Vector3();
  3650. var vCB = new THREE.Vector3();
  3651. var vAB = new THREE.Vector3();
  3652. for ( var oi = 0; oi < geometry.offsets.length; ++oi ) {
  3653. var start = geometry.offsets[ oi ].start;
  3654. var count = geometry.offsets[ oi ].count;
  3655. var index = geometry.offsets[ oi ].index;
  3656. for ( var i = start, il = start + count; i < il; i += 3 ) {
  3657. if ( indexed ) {
  3658. a = index + geometry.attributes.index.array[ i ];
  3659. b = index + geometry.attributes.index.array[ i + 1 ];
  3660. c = index + geometry.attributes.index.array[ i + 2 ];
  3661. } else {
  3662. a = index;
  3663. b = index + 1;
  3664. c = index + 2;
  3665. }
  3666. vA.set( geometry.attributes.position.array[ a * 3 ],
  3667. geometry.attributes.position.array[ a * 3 + 1 ],
  3668. geometry.attributes.position.array[ a * 3 + 2] );
  3669. vB.set( geometry.attributes.position.array[ b * 3 ],
  3670. geometry.attributes.position.array[ b * 3 + 1 ],
  3671. geometry.attributes.position.array[ b * 3 + 2] );
  3672. vC.set( geometry.attributes.position.array[ c * 3 ],
  3673. geometry.attributes.position.array[ c * 3 + 1 ],
  3674. geometry.attributes.position.array[ c * 3 + 2 ] );
  3675. facePlane.setFromCoplanarPoints( vA, vB, vC );
  3676. var planeDistance = localRay.distanceToPlane( facePlane );
  3677. // bail if raycaster and plane are parallel
  3678. if ( Math.abs( planeDistance ) < precision ) continue;
  3679. // if negative distance, then plane is behind raycaster
  3680. if ( planeDistance < 0 ) continue;
  3681. // check if we hit the wrong side of a single sided face
  3682. side = material.side;
  3683. if ( side !== THREE.DoubleSide ) {
  3684. var planeSign = localRay.direction.dot( facePlane.normal );
  3685. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3686. }
  3687. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3688. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3689. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3690. if ( ! THREE.Triangle.containsPoint( intersectPoint, vA, vB, vC ) ) continue;
  3691. intersects.push( {
  3692. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3693. point: raycaster.ray.at(planeDistance),
  3694. face: null,
  3695. faceIndex: null,
  3696. object: object
  3697. } );
  3698. }
  3699. }
  3700. } else if ( geometry instanceof THREE.Geometry ) {
  3701. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3702. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3703. var side = object.material.side;
  3704. var a, b, c, d;
  3705. var precision = raycaster.precision;
  3706. inverseMatrix.getInverse( object.matrixWorld );
  3707. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3708. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3709. var face = geometry.faces[ f ];
  3710. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3711. if ( material === undefined ) continue;
  3712. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3713. var planeDistance = localRay.distanceToPlane( facePlane );
  3714. // bail if raycaster and plane are parallel
  3715. if ( Math.abs( planeDistance ) < precision ) continue;
  3716. // if negative distance, then plane is behind raycaster
  3717. if ( planeDistance < 0 ) continue;
  3718. // check if we hit the wrong side of a single sided face
  3719. side = material.side;
  3720. if ( side !== THREE.DoubleSide ) {
  3721. var planeSign = localRay.direction.dot( facePlane.normal );
  3722. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3723. }
  3724. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3725. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3726. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3727. if ( face instanceof THREE.Face3 ) {
  3728. a = vertices[ face.a ];
  3729. b = vertices[ face.b ];
  3730. c = vertices[ face.c ];
  3731. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3732. } else if ( face instanceof THREE.Face4 ) {
  3733. a = vertices[ face.a ];
  3734. b = vertices[ face.b ];
  3735. c = vertices[ face.c ];
  3736. d = vertices[ face.d ];
  3737. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3738. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3739. } else {
  3740. // This is added because if we call out of this if/else group when none of the cases
  3741. // match it will add a point to the intersection list erroneously.
  3742. throw Error( "face type not supported" );
  3743. }
  3744. intersects.push( {
  3745. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3746. point: raycaster.ray.at( planeDistance ),
  3747. face: face,
  3748. faceIndex: f,
  3749. object: object
  3750. } );
  3751. }
  3752. }
  3753. }
  3754. };
  3755. var intersectDescendants = function ( object, raycaster, intersects ) {
  3756. var descendants = object.getDescendants();
  3757. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3758. intersectObject( descendants[ i ], raycaster, intersects );
  3759. }
  3760. };
  3761. //
  3762. THREE.Raycaster.prototype.precision = 0.0001;
  3763. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3764. this.ray.set( origin, direction );
  3765. // normalized ray.direction required for accurate distance calculations
  3766. if ( this.ray.direction.length() > 0 ) {
  3767. this.ray.direction.normalize();
  3768. }
  3769. };
  3770. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3771. var intersects = [];
  3772. if ( recursive === true ) {
  3773. intersectDescendants( object, this, intersects );
  3774. }
  3775. intersectObject( object, this, intersects );
  3776. intersects.sort( descSort );
  3777. return intersects;
  3778. };
  3779. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3780. var intersects = [];
  3781. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3782. intersectObject( objects[ i ], this, intersects );
  3783. if ( recursive === true ) {
  3784. intersectDescendants( objects[ i ], this, intersects );
  3785. }
  3786. }
  3787. intersects.sort( descSort );
  3788. return intersects;
  3789. };
  3790. }( THREE ) );
  3791. /**
  3792. * @author mrdoob / http://mrdoob.com/
  3793. * @author mikael emtinger / http://gomo.se/
  3794. * @author alteredq / http://alteredqualia.com/
  3795. * @author WestLangley / http://github.com/WestLangley
  3796. */
  3797. THREE.Object3D = function () {
  3798. this.id = THREE.Math.generateUUID();
  3799. this.name = '';
  3800. this.parent = undefined;
  3801. this.children = [];
  3802. this.up = new THREE.Vector3( 0, 1, 0 );
  3803. this.position = new THREE.Vector3();
  3804. this.rotation = new THREE.Vector3();
  3805. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3806. this.scale = new THREE.Vector3( 1, 1, 1 );
  3807. this.renderDepth = null;
  3808. this.rotationAutoUpdate = true;
  3809. this.matrix = new THREE.Matrix4();
  3810. this.matrixWorld = new THREE.Matrix4();
  3811. this.matrixAutoUpdate = true;
  3812. this.matrixWorldNeedsUpdate = true;
  3813. this.quaternion = new THREE.Quaternion();
  3814. this.useQuaternion = false;
  3815. this.visible = true;
  3816. this.castShadow = false;
  3817. this.receiveShadow = false;
  3818. this.frustumCulled = true;
  3819. this.userData = {};
  3820. };
  3821. THREE.Object3D.prototype = {
  3822. constructor: THREE.Object3D,
  3823. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  3824. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  3825. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  3826. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  3827. applyMatrix: function () {
  3828. var m1 = new THREE.Matrix4();
  3829. return function ( matrix ) {
  3830. this.matrix.multiplyMatrices( matrix, this.matrix );
  3831. this.position.getPositionFromMatrix( this.matrix );
  3832. this.scale.getScaleFromMatrix( this.matrix );
  3833. m1.extractRotation( this.matrix );
  3834. if ( this.useQuaternion === true ) {
  3835. this.quaternion.setFromRotationMatrix( m1 );
  3836. } else {
  3837. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  3838. }
  3839. }
  3840. }(),
  3841. rotateOnAxis: function() {
  3842. // rotate object on axis in object space
  3843. // axis is assumed to be normalized
  3844. var q1 = new THREE.Quaternion();
  3845. var q2 = new THREE.Quaternion();
  3846. return function ( axis, angle ) {
  3847. q1.setFromAxisAngle( axis, angle );
  3848. if ( this.useQuaternion === true ) {
  3849. this.quaternion.multiply( q1 );
  3850. } else {
  3851. q2.setFromEuler( this.rotation, this.eulerOrder );
  3852. q2.multiply( q1 );
  3853. this.rotation.setEulerFromQuaternion( q2, this.eulerOrder );
  3854. }
  3855. return this;
  3856. }
  3857. }(),
  3858. translateOnAxis: function () {
  3859. // translate object by distance along axis in object space
  3860. // axis is assumed to be normalized
  3861. var v1 = new THREE.Vector3();
  3862. return function ( axis, distance ) {
  3863. v1.copy( axis );
  3864. if ( this.useQuaternion === true ) {
  3865. v1.applyQuaternion( this.quaternion );
  3866. } else {
  3867. v1.applyEuler( this.rotation, this.eulerOrder );
  3868. }
  3869. this.position.add( v1.multiplyScalar( distance ) );
  3870. return this;
  3871. }
  3872. }(),
  3873. translate: function ( distance, axis ) {
  3874. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  3875. return this.translateOnAxis( axis, distance );
  3876. },
  3877. translateX: function () {
  3878. var v1 = new THREE.Vector3( 1, 0, 0 );
  3879. return function ( distance ) {
  3880. return this.translateOnAxis( v1, distance );
  3881. };
  3882. }(),
  3883. translateY: function () {
  3884. var v1 = new THREE.Vector3( 0, 1, 0 );
  3885. return function ( distance ) {
  3886. return this.translateOnAxis( v1, distance );
  3887. };
  3888. }(),
  3889. translateZ: function () {
  3890. var v1 = new THREE.Vector3( 0, 0, 1 );
  3891. return function ( distance ) {
  3892. return this.translateOnAxis( v1, distance );
  3893. };
  3894. }(),
  3895. localToWorld: function ( vector ) {
  3896. return vector.applyMatrix4( this.matrixWorld );
  3897. },
  3898. worldToLocal: function () {
  3899. var m1 = new THREE.Matrix4();
  3900. return function ( vector ) {
  3901. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  3902. };
  3903. }(),
  3904. lookAt: function () {
  3905. // This routine does not support objects with rotated and/or translated parent(s)
  3906. var m1 = new THREE.Matrix4();
  3907. return function ( vector ) {
  3908. m1.lookAt( vector, this.position, this.up );
  3909. if ( this.useQuaternion === true ) {
  3910. this.quaternion.setFromRotationMatrix( m1 );
  3911. } else {
  3912. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  3913. }
  3914. };
  3915. }(),
  3916. add: function ( object ) {
  3917. if ( object === this ) {
  3918. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3919. return;
  3920. }
  3921. if ( object instanceof THREE.Object3D ) {
  3922. if ( object.parent !== undefined ) {
  3923. object.parent.remove( object );
  3924. }
  3925. object.parent = this;
  3926. this.children.push( object );
  3927. // add to scene
  3928. var scene = this;
  3929. while ( scene.parent !== undefined ) {
  3930. scene = scene.parent;
  3931. }
  3932. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3933. scene.__addObject( object );
  3934. }
  3935. }
  3936. },
  3937. remove: function ( object ) {
  3938. var index = this.children.indexOf( object );
  3939. if ( index !== - 1 ) {
  3940. object.parent = undefined;
  3941. this.children.splice( index, 1 );
  3942. // remove from scene
  3943. var scene = this;
  3944. while ( scene.parent !== undefined ) {
  3945. scene = scene.parent;
  3946. }
  3947. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3948. scene.__removeObject( object );
  3949. }
  3950. }
  3951. },
  3952. traverse: function ( callback ) {
  3953. callback( this );
  3954. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3955. this.children[ i ].traverse( callback );
  3956. }
  3957. },
  3958. getObjectById: function ( id, recursive ) {
  3959. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3960. var child = this.children[ i ];
  3961. if ( child.id === id ) {
  3962. return child;
  3963. }
  3964. if ( recursive === true ) {
  3965. child = child.getObjectById( id, recursive );
  3966. if ( child !== undefined ) {
  3967. return child;
  3968. }
  3969. }
  3970. }
  3971. return undefined;
  3972. },
  3973. getObjectByName: function ( name, recursive ) {
  3974. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3975. var child = this.children[ i ];
  3976. if ( child.name === name ) {
  3977. return child;
  3978. }
  3979. if ( recursive === true ) {
  3980. child = child.getObjectByName( name, recursive );
  3981. if ( child !== undefined ) {
  3982. return child;
  3983. }
  3984. }
  3985. }
  3986. return undefined;
  3987. },
  3988. getChildByName: function ( name, recursive ) {
  3989. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  3990. return this.getObjectByName( name, recursive );
  3991. },
  3992. getDescendants: function ( array ) {
  3993. if ( array === undefined ) array = [];
  3994. Array.prototype.push.apply( array, this.children );
  3995. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3996. this.children[ i ].getDescendants( array );
  3997. }
  3998. return array;
  3999. },
  4000. updateMatrix: function () {
  4001. // if we are not using a quaternion directly, convert Euler rotation to this.quaternion.
  4002. if ( this.useQuaternion === false ) {
  4003. this.matrix.makeFromPositionEulerScale( this.position, this.rotation, this.eulerOrder, this.scale );
  4004. } else {
  4005. this.matrix.makeFromPositionQuaternionScale( this.position, this.quaternion, this.scale );
  4006. }
  4007. this.matrixWorldNeedsUpdate = true;
  4008. },
  4009. updateMatrixWorld: function ( force ) {
  4010. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4011. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4012. if ( this.parent === undefined ) {
  4013. this.matrixWorld.copy( this.matrix );
  4014. } else {
  4015. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4016. }
  4017. this.matrixWorldNeedsUpdate = false;
  4018. force = true;
  4019. }
  4020. // update children
  4021. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4022. this.children[ i ].updateMatrixWorld( force );
  4023. }
  4024. },
  4025. clone: function ( object, recursive ) {
  4026. if ( object === undefined ) object = new THREE.Object3D();
  4027. if ( recursive === undefined ) recursive = true;
  4028. object.name = this.name;
  4029. object.up.copy( this.up );
  4030. object.position.copy( this.position );
  4031. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  4032. object.eulerOrder = this.eulerOrder;
  4033. object.scale.copy( this.scale );
  4034. object.renderDepth = this.renderDepth;
  4035. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4036. object.matrix.copy( this.matrix );
  4037. object.matrixWorld.copy( this.matrixWorld );
  4038. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4039. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4040. object.quaternion.copy( this.quaternion );
  4041. object.useQuaternion = this.useQuaternion;
  4042. object.visible = this.visible;
  4043. object.castShadow = this.castShadow;
  4044. object.receiveShadow = this.receiveShadow;
  4045. object.frustumCulled = this.frustumCulled;
  4046. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4047. if ( recursive ) {
  4048. for ( var i = 0; i < this.children.length; i ++ ) {
  4049. var child = this.children[ i ];
  4050. object.add( child.clone() );
  4051. }
  4052. }
  4053. return object;
  4054. }
  4055. };
  4056. THREE.Object3D.defaultEulerOrder = 'XYZ';
  4057. /**
  4058. * @author mrdoob / http://mrdoob.com/
  4059. * @author supereggbert / http://www.paulbrunt.co.uk/
  4060. * @author julianwa / https://github.com/julianwa
  4061. */
  4062. THREE.Projector = function () {
  4063. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4064. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4065. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  4066. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  4067. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4068. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  4069. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  4070. _vector3 = new THREE.Vector3(),
  4071. _vector4 = new THREE.Vector4(),
  4072. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4073. _boundingBox = new THREE.Box3(),
  4074. _points3 = new Array( 3 ),
  4075. _points4 = new Array( 4 ),
  4076. _viewMatrix = new THREE.Matrix4(),
  4077. _viewProjectionMatrix = new THREE.Matrix4(),
  4078. _modelMatrix,
  4079. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4080. _normalMatrix = new THREE.Matrix3(),
  4081. _normalViewMatrix = new THREE.Matrix3(),
  4082. _centroid = new THREE.Vector3(),
  4083. _frustum = new THREE.Frustum(),
  4084. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4085. _clippedVertex2PositionScreen = new THREE.Vector4();
  4086. this.projectVector = function ( vector, camera ) {
  4087. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4088. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4089. return vector.applyProjection( _viewProjectionMatrix );
  4090. };
  4091. this.unprojectVector = function ( vector, camera ) {
  4092. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4093. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  4094. return vector.applyProjection( _viewProjectionMatrix );
  4095. };
  4096. this.pickingRay = function ( vector, camera ) {
  4097. // set two vectors with opposing z values
  4098. vector.z = -1.0;
  4099. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4100. this.unprojectVector( vector, camera );
  4101. this.unprojectVector( end, camera );
  4102. // find direction from vector to end
  4103. end.sub( vector ).normalize();
  4104. return new THREE.Raycaster( vector, end );
  4105. };
  4106. var getObject = function ( object ) {
  4107. _object = getNextObjectInPool();
  4108. _object.object = object;
  4109. if ( object.renderDepth !== null ) {
  4110. _object.z = object.renderDepth;
  4111. } else {
  4112. _vector3.getPositionFromMatrix( object.matrixWorld );
  4113. _vector3.applyProjection( _viewProjectionMatrix );
  4114. _object.z = _vector3.z;
  4115. }
  4116. return _object;
  4117. };
  4118. var projectObject = function ( object ) {
  4119. if ( object.visible === false ) return;
  4120. if ( object instanceof THREE.Light ) {
  4121. _renderData.lights.push( object );
  4122. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4123. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4124. _renderData.objects.push( getObject( object ) );
  4125. }
  4126. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  4127. _renderData.sprites.push( getObject( object ) );
  4128. }
  4129. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4130. projectObject( object.children[ i ] );
  4131. }
  4132. };
  4133. var projectGraph = function ( root, sortObjects ) {
  4134. _objectCount = 0;
  4135. _renderData.objects.length = 0;
  4136. _renderData.sprites.length = 0;
  4137. _renderData.lights.length = 0;
  4138. projectObject( root );
  4139. if ( sortObjects === true ) {
  4140. _renderData.objects.sort( painterSort );
  4141. }
  4142. };
  4143. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4144. var visible = false,
  4145. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4146. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4147. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4148. _face3Count = 0;
  4149. _face4Count = 0;
  4150. _lineCount = 0;
  4151. _particleCount = 0;
  4152. _renderData.elements.length = 0;
  4153. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4154. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4155. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4156. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4157. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4158. _frustum.setFromMatrix( _viewProjectionMatrix );
  4159. projectGraph( scene, sortObjects );
  4160. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4161. object = _renderData.objects[ o ].object;
  4162. _modelMatrix = object.matrixWorld;
  4163. _vertexCount = 0;
  4164. if ( object instanceof THREE.Mesh ) {
  4165. geometry = object.geometry;
  4166. vertices = geometry.vertices;
  4167. faces = geometry.faces;
  4168. faceVertexUvs = geometry.faceVertexUvs;
  4169. _normalMatrix.getNormalMatrix( _modelMatrix );
  4170. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4171. objectMaterials = isFaceMaterial === true ? object.material : null;
  4172. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4173. _vertex = getNextVertexInPool();
  4174. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4175. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4176. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  4177. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  4178. _vertex.positionScreen.z /= _vertex.positionScreen.w;
  4179. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4180. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4181. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4182. }
  4183. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4184. face = faces[ f ];
  4185. var material = isFaceMaterial === true
  4186. ? objectMaterials.materials[ face.materialIndex ]
  4187. : object.material;
  4188. if ( material === undefined ) continue;
  4189. var side = material.side;
  4190. if ( face instanceof THREE.Face3 ) {
  4191. v1 = _vertexPool[ face.a ];
  4192. v2 = _vertexPool[ face.b ];
  4193. v3 = _vertexPool[ face.c ];
  4194. _points3[ 0 ] = v1.positionScreen;
  4195. _points3[ 1 ] = v2.positionScreen;
  4196. _points3[ 2 ] = v3.positionScreen;
  4197. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4198. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4199. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4200. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4201. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4202. _face = getNextFace3InPool();
  4203. _face.v1.copy( v1 );
  4204. _face.v2.copy( v2 );
  4205. _face.v3.copy( v3 );
  4206. } else {
  4207. continue;
  4208. }
  4209. } else {
  4210. continue;
  4211. }
  4212. } else if ( face instanceof THREE.Face4 ) {
  4213. v1 = _vertexPool[ face.a ];
  4214. v2 = _vertexPool[ face.b ];
  4215. v3 = _vertexPool[ face.c ];
  4216. v4 = _vertexPool[ face.d ];
  4217. _points4[ 0 ] = v1.positionScreen;
  4218. _points4[ 1 ] = v2.positionScreen;
  4219. _points4[ 2 ] = v3.positionScreen;
  4220. _points4[ 3 ] = v4.positionScreen;
  4221. if ( v1.visible === true || v2.visible === true || v3.visible === true || v4.visible === true ||
  4222. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points4 ) ) ) {
  4223. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4224. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  4225. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  4226. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  4227. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4228. _face = getNextFace4InPool();
  4229. _face.v1.copy( v1 );
  4230. _face.v2.copy( v2 );
  4231. _face.v3.copy( v3 );
  4232. _face.v4.copy( v4 );
  4233. } else {
  4234. continue;
  4235. }
  4236. } else {
  4237. continue;
  4238. }
  4239. }
  4240. _face.normalModel.copy( face.normal );
  4241. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4242. _face.normalModel.negate();
  4243. }
  4244. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4245. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4246. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4247. faceVertexNormals = face.vertexNormals;
  4248. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  4249. var normalModel = _face.vertexNormalsModel[ n ];
  4250. normalModel.copy( faceVertexNormals[ n ] );
  4251. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4252. normalModel.negate();
  4253. }
  4254. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4255. var normalModelView = _face.vertexNormalsModelView[ n ];
  4256. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4257. }
  4258. _face.vertexNormalsLength = faceVertexNormals.length;
  4259. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  4260. uvs = faceVertexUvs[ c ][ f ];
  4261. if ( uvs === undefined ) continue;
  4262. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4263. _face.uvs[ c ][ u ] = uvs[ u ];
  4264. }
  4265. }
  4266. _face.color = face.color;
  4267. _face.material = material;
  4268. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4269. _face.z = _centroid.z;
  4270. _renderData.elements.push( _face );
  4271. }
  4272. } else if ( object instanceof THREE.Line ) {
  4273. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4274. vertices = object.geometry.vertices;
  4275. v1 = getNextVertexInPool();
  4276. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4277. // Handle LineStrip and LinePieces
  4278. var step = object.type === THREE.LinePieces ? 2 : 1;
  4279. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4280. v1 = getNextVertexInPool();
  4281. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4282. if ( ( v + 1 ) % step > 0 ) continue;
  4283. v2 = _vertexPool[ _vertexCount - 2 ];
  4284. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4285. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4286. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4287. // Perform the perspective divide
  4288. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4289. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4290. _line = getNextLineInPool();
  4291. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4292. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4293. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4294. _line.material = object.material;
  4295. if ( object.material.vertexColors === THREE.VertexColors ) {
  4296. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4297. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4298. }
  4299. _renderData.elements.push( _line );
  4300. }
  4301. }
  4302. }
  4303. }
  4304. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4305. object = _renderData.sprites[ o ].object;
  4306. _modelMatrix = object.matrixWorld;
  4307. if ( object instanceof THREE.Particle ) {
  4308. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4309. _vector4.applyMatrix4( _viewProjectionMatrix );
  4310. _vector4.z /= _vector4.w;
  4311. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  4312. _particle = getNextParticleInPool();
  4313. _particle.object = object;
  4314. _particle.x = _vector4.x / _vector4.w;
  4315. _particle.y = _vector4.y / _vector4.w;
  4316. _particle.z = _vector4.z;
  4317. _particle.rotation = object.rotation.z;
  4318. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4319. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4320. _particle.material = object.material;
  4321. _renderData.elements.push( _particle );
  4322. }
  4323. }
  4324. }
  4325. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4326. return _renderData;
  4327. };
  4328. // Pools
  4329. function getNextObjectInPool() {
  4330. if ( _objectCount === _objectPoolLength ) {
  4331. var object = new THREE.RenderableObject();
  4332. _objectPool.push( object );
  4333. _objectPoolLength ++;
  4334. _objectCount ++;
  4335. return object;
  4336. }
  4337. return _objectPool[ _objectCount ++ ];
  4338. }
  4339. function getNextVertexInPool() {
  4340. if ( _vertexCount === _vertexPoolLength ) {
  4341. var vertex = new THREE.RenderableVertex();
  4342. _vertexPool.push( vertex );
  4343. _vertexPoolLength ++;
  4344. _vertexCount ++;
  4345. return vertex;
  4346. }
  4347. return _vertexPool[ _vertexCount ++ ];
  4348. }
  4349. function getNextFace3InPool() {
  4350. if ( _face3Count === _face3PoolLength ) {
  4351. var face = new THREE.RenderableFace3();
  4352. _face3Pool.push( face );
  4353. _face3PoolLength ++;
  4354. _face3Count ++;
  4355. return face;
  4356. }
  4357. return _face3Pool[ _face3Count ++ ];
  4358. }
  4359. function getNextFace4InPool() {
  4360. if ( _face4Count === _face4PoolLength ) {
  4361. var face = new THREE.RenderableFace4();
  4362. _face4Pool.push( face );
  4363. _face4PoolLength ++;
  4364. _face4Count ++;
  4365. return face;
  4366. }
  4367. return _face4Pool[ _face4Count ++ ];
  4368. }
  4369. function getNextLineInPool() {
  4370. if ( _lineCount === _linePoolLength ) {
  4371. var line = new THREE.RenderableLine();
  4372. _linePool.push( line );
  4373. _linePoolLength ++;
  4374. _lineCount ++
  4375. return line;
  4376. }
  4377. return _linePool[ _lineCount ++ ];
  4378. }
  4379. function getNextParticleInPool() {
  4380. if ( _particleCount === _particlePoolLength ) {
  4381. var particle = new THREE.RenderableParticle();
  4382. _particlePool.push( particle );
  4383. _particlePoolLength ++;
  4384. _particleCount ++
  4385. return particle;
  4386. }
  4387. return _particlePool[ _particleCount ++ ];
  4388. }
  4389. //
  4390. function painterSort( a, b ) {
  4391. return b.z - a.z;
  4392. }
  4393. function clipLine( s1, s2 ) {
  4394. var alpha1 = 0, alpha2 = 1,
  4395. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4396. // Z = -1 and Z = +1, respectively.
  4397. bc1near = s1.z + s1.w,
  4398. bc2near = s2.z + s2.w,
  4399. bc1far = - s1.z + s1.w,
  4400. bc2far = - s2.z + s2.w;
  4401. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4402. // Both vertices lie entirely within all clip planes.
  4403. return true;
  4404. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4405. // Both vertices lie entirely outside one of the clip planes.
  4406. return false;
  4407. } else {
  4408. // The line segment spans at least one clip plane.
  4409. if ( bc1near < 0 ) {
  4410. // v1 lies outside the near plane, v2 inside
  4411. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4412. } else if ( bc2near < 0 ) {
  4413. // v2 lies outside the near plane, v1 inside
  4414. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4415. }
  4416. if ( bc1far < 0 ) {
  4417. // v1 lies outside the far plane, v2 inside
  4418. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4419. } else if ( bc2far < 0 ) {
  4420. // v2 lies outside the far plane, v2 inside
  4421. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4422. }
  4423. if ( alpha2 < alpha1 ) {
  4424. // The line segment spans two boundaries, but is outside both of them.
  4425. // (This can't happen when we're only clipping against just near/far but good
  4426. // to leave the check here for future usage if other clip planes are added.)
  4427. return false;
  4428. } else {
  4429. // Update the s1 and s2 vertices to match the clipped line segment.
  4430. s1.lerp( s2, alpha1 );
  4431. s2.lerp( s1, 1 - alpha2 );
  4432. return true;
  4433. }
  4434. }
  4435. }
  4436. };
  4437. /**
  4438. * @author mrdoob / http://mrdoob.com/
  4439. * @author alteredq / http://alteredqualia.com/
  4440. */
  4441. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4442. this.a = a;
  4443. this.b = b;
  4444. this.c = c;
  4445. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4446. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4447. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4448. this.vertexColors = color instanceof Array ? color : [];
  4449. this.vertexTangents = [];
  4450. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4451. this.centroid = new THREE.Vector3();
  4452. };
  4453. THREE.Face3.prototype = {
  4454. constructor: THREE.Face3,
  4455. clone: function () {
  4456. var face = new THREE.Face3( this.a, this.b, this.c );
  4457. face.normal.copy( this.normal );
  4458. face.color.copy( this.color );
  4459. face.centroid.copy( this.centroid );
  4460. face.materialIndex = this.materialIndex;
  4461. var i, il;
  4462. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4463. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4464. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4465. return face;
  4466. }
  4467. };
  4468. /**
  4469. * @author mrdoob / http://mrdoob.com/
  4470. * @author alteredq / http://alteredqualia.com/
  4471. */
  4472. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4473. this.a = a;
  4474. this.b = b;
  4475. this.c = c;
  4476. this.d = d;
  4477. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4478. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4479. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4480. this.vertexColors = color instanceof Array ? color : [];
  4481. this.vertexTangents = [];
  4482. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4483. this.centroid = new THREE.Vector3();
  4484. };
  4485. THREE.Face4.prototype = {
  4486. constructor: THREE.Face4,
  4487. clone: function () {
  4488. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4489. face.normal.copy( this.normal );
  4490. face.color.copy( this.color );
  4491. face.centroid.copy( this.centroid );
  4492. face.materialIndex = this.materialIndex;
  4493. var i, il;
  4494. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4495. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4496. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4497. return face;
  4498. }
  4499. };
  4500. /**
  4501. * @author mrdoob / http://mrdoob.com/
  4502. * @author kile / http://kile.stravaganza.org/
  4503. * @author alteredq / http://alteredqualia.com/
  4504. * @author mikael emtinger / http://gomo.se/
  4505. * @author zz85 / http://www.lab4games.net/zz85/blog
  4506. * @author bhouston / http://exocortex.com
  4507. */
  4508. THREE.Geometry = function () {
  4509. this.id = THREE.Math.generateUUID();
  4510. this.name = '';
  4511. this.vertices = [];
  4512. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4513. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4514. this.faces = [];
  4515. this.faceUvs = [[]];
  4516. this.faceVertexUvs = [[]];
  4517. this.morphTargets = [];
  4518. this.morphColors = [];
  4519. this.morphNormals = [];
  4520. this.skinWeights = [];
  4521. this.skinIndices = [];
  4522. this.lineDistances = [];
  4523. this.boundingBox = null;
  4524. this.boundingSphere = null;
  4525. this.hasTangents = false;
  4526. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4527. // update flags
  4528. this.verticesNeedUpdate = false;
  4529. this.elementsNeedUpdate = false;
  4530. this.uvsNeedUpdate = false;
  4531. this.normalsNeedUpdate = false;
  4532. this.tangentsNeedUpdate = false;
  4533. this.colorsNeedUpdate = false;
  4534. this.lineDistancesNeedUpdate = false;
  4535. this.buffersNeedUpdate = false;
  4536. };
  4537. THREE.Geometry.prototype = {
  4538. constructor: THREE.Geometry,
  4539. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  4540. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  4541. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  4542. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  4543. applyMatrix: function ( matrix ) {
  4544. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4545. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4546. var vertex = this.vertices[ i ];
  4547. vertex.applyMatrix4( matrix );
  4548. }
  4549. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4550. var face = this.faces[ i ];
  4551. face.normal.applyMatrix3( normalMatrix ).normalize();
  4552. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4553. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4554. }
  4555. face.centroid.applyMatrix4( matrix );
  4556. }
  4557. },
  4558. computeCentroids: function () {
  4559. var f, fl, face;
  4560. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4561. face = this.faces[ f ];
  4562. face.centroid.set( 0, 0, 0 );
  4563. if ( face instanceof THREE.Face3 ) {
  4564. face.centroid.add( this.vertices[ face.a ] );
  4565. face.centroid.add( this.vertices[ face.b ] );
  4566. face.centroid.add( this.vertices[ face.c ] );
  4567. face.centroid.divideScalar( 3 );
  4568. } else if ( face instanceof THREE.Face4 ) {
  4569. face.centroid.add( this.vertices[ face.a ] );
  4570. face.centroid.add( this.vertices[ face.b ] );
  4571. face.centroid.add( this.vertices[ face.c ] );
  4572. face.centroid.add( this.vertices[ face.d ] );
  4573. face.centroid.divideScalar( 4 );
  4574. }
  4575. }
  4576. },
  4577. computeFaceNormals: function () {
  4578. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4579. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4580. var face = this.faces[ f ];
  4581. var vA = this.vertices[ face.a ];
  4582. var vB = this.vertices[ face.b ];
  4583. var vC = this.vertices[ face.c ];
  4584. cb.subVectors( vC, vB );
  4585. ab.subVectors( vA, vB );
  4586. cb.cross( ab );
  4587. cb.normalize();
  4588. face.normal.copy( cb );
  4589. }
  4590. },
  4591. computeVertexNormals: function ( areaWeighted ) {
  4592. var v, vl, f, fl, face, vertices;
  4593. // create internal buffers for reuse when calling this method repeatedly
  4594. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4595. if ( this.__tmpVertices === undefined ) {
  4596. this.__tmpVertices = new Array( this.vertices.length );
  4597. vertices = this.__tmpVertices;
  4598. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4599. vertices[ v ] = new THREE.Vector3();
  4600. }
  4601. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4602. face = this.faces[ f ];
  4603. if ( face instanceof THREE.Face3 ) {
  4604. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4605. } else if ( face instanceof THREE.Face4 ) {
  4606. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4607. }
  4608. }
  4609. } else {
  4610. vertices = this.__tmpVertices;
  4611. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4612. vertices[ v ].set( 0, 0, 0 );
  4613. }
  4614. }
  4615. if ( areaWeighted ) {
  4616. // vertex normals weighted by triangle areas
  4617. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4618. var vA, vB, vC, vD;
  4619. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4620. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4621. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4622. face = this.faces[ f ];
  4623. if ( face instanceof THREE.Face3 ) {
  4624. vA = this.vertices[ face.a ];
  4625. vB = this.vertices[ face.b ];
  4626. vC = this.vertices[ face.c ];
  4627. cb.subVectors( vC, vB );
  4628. ab.subVectors( vA, vB );
  4629. cb.cross( ab );
  4630. vertices[ face.a ].add( cb );
  4631. vertices[ face.b ].add( cb );
  4632. vertices[ face.c ].add( cb );
  4633. } else if ( face instanceof THREE.Face4 ) {
  4634. vA = this.vertices[ face.a ];
  4635. vB = this.vertices[ face.b ];
  4636. vC = this.vertices[ face.c ];
  4637. vD = this.vertices[ face.d ];
  4638. // abd
  4639. db.subVectors( vD, vB );
  4640. ab.subVectors( vA, vB );
  4641. db.cross( ab );
  4642. vertices[ face.a ].add( db );
  4643. vertices[ face.b ].add( db );
  4644. vertices[ face.d ].add( db );
  4645. // bcd
  4646. dc.subVectors( vD, vC );
  4647. bc.subVectors( vB, vC );
  4648. dc.cross( bc );
  4649. vertices[ face.b ].add( dc );
  4650. vertices[ face.c ].add( dc );
  4651. vertices[ face.d ].add( dc );
  4652. }
  4653. }
  4654. } else {
  4655. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4656. face = this.faces[ f ];
  4657. if ( face instanceof THREE.Face3 ) {
  4658. vertices[ face.a ].add( face.normal );
  4659. vertices[ face.b ].add( face.normal );
  4660. vertices[ face.c ].add( face.normal );
  4661. } else if ( face instanceof THREE.Face4 ) {
  4662. vertices[ face.a ].add( face.normal );
  4663. vertices[ face.b ].add( face.normal );
  4664. vertices[ face.c ].add( face.normal );
  4665. vertices[ face.d ].add( face.normal );
  4666. }
  4667. }
  4668. }
  4669. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4670. vertices[ v ].normalize();
  4671. }
  4672. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4673. face = this.faces[ f ];
  4674. if ( face instanceof THREE.Face3 ) {
  4675. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4676. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4677. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4678. } else if ( face instanceof THREE.Face4 ) {
  4679. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4680. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4681. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4682. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4683. }
  4684. }
  4685. },
  4686. computeMorphNormals: function () {
  4687. var i, il, f, fl, face;
  4688. // save original normals
  4689. // - create temp variables on first access
  4690. // otherwise just copy (for faster repeated calls)
  4691. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4692. face = this.faces[ f ];
  4693. if ( ! face.__originalFaceNormal ) {
  4694. face.__originalFaceNormal = face.normal.clone();
  4695. } else {
  4696. face.__originalFaceNormal.copy( face.normal );
  4697. }
  4698. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4699. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4700. if ( ! face.__originalVertexNormals[ i ] ) {
  4701. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4702. } else {
  4703. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4704. }
  4705. }
  4706. }
  4707. // use temp geometry to compute face and vertex normals for each morph
  4708. var tmpGeo = new THREE.Geometry();
  4709. tmpGeo.faces = this.faces;
  4710. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4711. // create on first access
  4712. if ( ! this.morphNormals[ i ] ) {
  4713. this.morphNormals[ i ] = {};
  4714. this.morphNormals[ i ].faceNormals = [];
  4715. this.morphNormals[ i ].vertexNormals = [];
  4716. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4717. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4718. var faceNormal, vertexNormals;
  4719. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4720. face = this.faces[ f ];
  4721. faceNormal = new THREE.Vector3();
  4722. if ( face instanceof THREE.Face3 ) {
  4723. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4724. } else {
  4725. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4726. }
  4727. dstNormalsFace.push( faceNormal );
  4728. dstNormalsVertex.push( vertexNormals );
  4729. }
  4730. }
  4731. var morphNormals = this.morphNormals[ i ];
  4732. // set vertices to morph target
  4733. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4734. // compute morph normals
  4735. tmpGeo.computeFaceNormals();
  4736. tmpGeo.computeVertexNormals();
  4737. // store morph normals
  4738. var faceNormal, vertexNormals;
  4739. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4740. face = this.faces[ f ];
  4741. faceNormal = morphNormals.faceNormals[ f ];
  4742. vertexNormals = morphNormals.vertexNormals[ f ];
  4743. faceNormal.copy( face.normal );
  4744. if ( face instanceof THREE.Face3 ) {
  4745. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4746. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4747. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4748. } else {
  4749. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4750. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4751. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4752. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4753. }
  4754. }
  4755. }
  4756. // restore original normals
  4757. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4758. face = this.faces[ f ];
  4759. face.normal = face.__originalFaceNormal;
  4760. face.vertexNormals = face.__originalVertexNormals;
  4761. }
  4762. },
  4763. computeTangents: function () {
  4764. // based on http://www.terathon.com/code/tangent.html
  4765. // tangents go to vertices
  4766. var f, fl, v, vl, i, il, vertexIndex,
  4767. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4768. x1, x2, y1, y2, z1, z2,
  4769. s1, s2, t1, t2, r, t, test,
  4770. tan1 = [], tan2 = [],
  4771. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4772. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4773. n = new THREE.Vector3(), w;
  4774. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4775. tan1[ v ] = new THREE.Vector3();
  4776. tan2[ v ] = new THREE.Vector3();
  4777. }
  4778. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4779. vA = context.vertices[ a ];
  4780. vB = context.vertices[ b ];
  4781. vC = context.vertices[ c ];
  4782. uvA = uv[ ua ];
  4783. uvB = uv[ ub ];
  4784. uvC = uv[ uc ];
  4785. x1 = vB.x - vA.x;
  4786. x2 = vC.x - vA.x;
  4787. y1 = vB.y - vA.y;
  4788. y2 = vC.y - vA.y;
  4789. z1 = vB.z - vA.z;
  4790. z2 = vC.z - vA.z;
  4791. s1 = uvB.x - uvA.x;
  4792. s2 = uvC.x - uvA.x;
  4793. t1 = uvB.y - uvA.y;
  4794. t2 = uvC.y - uvA.y;
  4795. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4796. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4797. ( t2 * y1 - t1 * y2 ) * r,
  4798. ( t2 * z1 - t1 * z2 ) * r );
  4799. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4800. ( s1 * y2 - s2 * y1 ) * r,
  4801. ( s1 * z2 - s2 * z1 ) * r );
  4802. tan1[ a ].add( sdir );
  4803. tan1[ b ].add( sdir );
  4804. tan1[ c ].add( sdir );
  4805. tan2[ a ].add( tdir );
  4806. tan2[ b ].add( tdir );
  4807. tan2[ c ].add( tdir );
  4808. }
  4809. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4810. face = this.faces[ f ];
  4811. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4812. if ( face instanceof THREE.Face3 ) {
  4813. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4814. } else if ( face instanceof THREE.Face4 ) {
  4815. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4816. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4817. }
  4818. }
  4819. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4820. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4821. face = this.faces[ f ];
  4822. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4823. n.copy( face.vertexNormals[ i ] );
  4824. vertexIndex = face[ faceIndex[ i ] ];
  4825. t = tan1[ vertexIndex ];
  4826. // Gram-Schmidt orthogonalize
  4827. tmp.copy( t );
  4828. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4829. // Calculate handedness
  4830. tmp2.crossVectors( face.vertexNormals[ i ], t );
  4831. test = tmp2.dot( tan2[ vertexIndex ] );
  4832. w = (test < 0.0) ? -1.0 : 1.0;
  4833. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4834. }
  4835. }
  4836. this.hasTangents = true;
  4837. },
  4838. computeLineDistances: function ( ) {
  4839. var d = 0;
  4840. var vertices = this.vertices;
  4841. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4842. if ( i > 0 ) {
  4843. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4844. }
  4845. this.lineDistances[ i ] = d;
  4846. }
  4847. },
  4848. computeBoundingBox: function () {
  4849. if ( this.boundingBox === null ) {
  4850. this.boundingBox = new THREE.Box3();
  4851. }
  4852. this.boundingBox.setFromPoints( this.vertices );
  4853. },
  4854. computeBoundingSphere: function () {
  4855. if ( this.boundingSphere === null ) {
  4856. this.boundingSphere = new THREE.Sphere();
  4857. }
  4858. this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
  4859. },
  4860. /*
  4861. * Checks for duplicate vertices with hashmap.
  4862. * Duplicated vertices are removed
  4863. * and faces' vertices are updated.
  4864. */
  4865. mergeVertices: function () {
  4866. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4867. var unique = [], changes = [];
  4868. var v, key;
  4869. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4870. var precision = Math.pow( 10, precisionPoints );
  4871. var i,il, face;
  4872. var indices, k, j, jl, u;
  4873. // reset cache of vertices as it now will be changing.
  4874. this.__tmpVertices = undefined;
  4875. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4876. v = this.vertices[ i ];
  4877. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  4878. if ( verticesMap[ key ] === undefined ) {
  4879. verticesMap[ key ] = i;
  4880. unique.push( this.vertices[ i ] );
  4881. changes[ i ] = unique.length - 1;
  4882. } else {
  4883. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4884. changes[ i ] = changes[ verticesMap[ key ] ];
  4885. }
  4886. };
  4887. // if faces are completely degenerate after merging vertices, we
  4888. // have to remove them from the geometry.
  4889. var faceIndicesToRemove = [];
  4890. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4891. face = this.faces[ i ];
  4892. if ( face instanceof THREE.Face3 ) {
  4893. face.a = changes[ face.a ];
  4894. face.b = changes[ face.b ];
  4895. face.c = changes[ face.c ];
  4896. indices = [ face.a, face.b, face.c ];
  4897. var dupIndex = -1;
  4898. // if any duplicate vertices are found in a Face3
  4899. // we have to remove the face as nothing can be saved
  4900. for ( var n = 0; n < 3; n ++ ) {
  4901. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  4902. dupIndex = n;
  4903. faceIndicesToRemove.push( i );
  4904. break;
  4905. }
  4906. }
  4907. } else if ( face instanceof THREE.Face4 ) {
  4908. face.a = changes[ face.a ];
  4909. face.b = changes[ face.b ];
  4910. face.c = changes[ face.c ];
  4911. face.d = changes[ face.d ];
  4912. // check dups in (a, b, c, d) and convert to -> face3
  4913. indices = [ face.a, face.b, face.c, face.d ];
  4914. var dupIndex = -1;
  4915. for ( var n = 0; n < 4; n ++ ) {
  4916. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  4917. // if more than one duplicated vertex is found
  4918. // we can't generate any valid Face3's, thus
  4919. // we need to remove this face complete.
  4920. if ( dupIndex >= 0 ) {
  4921. faceIndicesToRemove.push( i );
  4922. }
  4923. dupIndex = n;
  4924. }
  4925. }
  4926. if ( dupIndex >= 0 ) {
  4927. indices.splice( dupIndex, 1 );
  4928. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  4929. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4930. u = this.faceVertexUvs[ j ][ i ];
  4931. if ( u ) {
  4932. u.splice( dupIndex, 1 );
  4933. }
  4934. }
  4935. if( face.vertexNormals && face.vertexNormals.length > 0) {
  4936. newFace.vertexNormals = face.vertexNormals;
  4937. newFace.vertexNormals.splice( dupIndex, 1 );
  4938. }
  4939. if( face.vertexColors && face.vertexColors.length > 0 ) {
  4940. newFace.vertexColors = face.vertexColors;
  4941. newFace.vertexColors.splice( dupIndex, 1 );
  4942. }
  4943. this.faces[ i ] = newFace;
  4944. }
  4945. }
  4946. }
  4947. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  4948. this.faces.splice( i, 1 );
  4949. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4950. this.faceVertexUvs[ j ].splice( i, 1 );
  4951. }
  4952. }
  4953. // Use unique set of vertices
  4954. var diff = this.vertices.length - unique.length;
  4955. this.vertices = unique;
  4956. return diff;
  4957. },
  4958. clone: function () {
  4959. var geometry = new THREE.Geometry();
  4960. var vertices = this.vertices;
  4961. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4962. geometry.vertices.push( vertices[ i ].clone() );
  4963. }
  4964. var faces = this.faces;
  4965. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4966. geometry.faces.push( faces[ i ].clone() );
  4967. }
  4968. var uvs = this.faceVertexUvs[ 0 ];
  4969. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4970. var uv = uvs[ i ], uvCopy = [];
  4971. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4972. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  4973. }
  4974. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4975. }
  4976. return geometry;
  4977. },
  4978. dispose: function () {
  4979. this.dispatchEvent( { type: 'dispose' } );
  4980. }
  4981. };
  4982. /**
  4983. * @author alteredq / http://alteredqualia.com/
  4984. */
  4985. THREE.BufferGeometry = function () {
  4986. this.id = THREE.Math.generateUUID();
  4987. // attributes
  4988. this.attributes = {};
  4989. // attributes typed arrays are kept only if dynamic flag is set
  4990. this.dynamic = false;
  4991. // offsets for chunks when using indexed elements
  4992. this.offsets = [];
  4993. // boundings
  4994. this.boundingBox = null;
  4995. this.boundingSphere = null;
  4996. this.hasTangents = false;
  4997. // for compatibility
  4998. this.morphTargets = [];
  4999. };
  5000. THREE.BufferGeometry.prototype = {
  5001. constructor: THREE.BufferGeometry,
  5002. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  5003. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  5004. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  5005. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  5006. applyMatrix: function ( matrix ) {
  5007. var positionArray;
  5008. var normalArray;
  5009. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  5010. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  5011. if ( positionArray !== undefined ) {
  5012. matrix.multiplyVector3Array( positionArray );
  5013. this.verticesNeedUpdate = true;
  5014. }
  5015. if ( normalArray !== undefined ) {
  5016. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5017. normalMatrix.multiplyVector3Array( normalArray );
  5018. this.normalizeNormals();
  5019. this.normalsNeedUpdate = true;
  5020. }
  5021. },
  5022. computeBoundingBox: function () {
  5023. if ( this.boundingBox === null ) {
  5024. this.boundingBox = new THREE.Box3();
  5025. }
  5026. var positions = this.attributes[ "position" ].array;
  5027. if ( positions ) {
  5028. var bb = this.boundingBox;
  5029. var x, y, z;
  5030. if( positions.length >= 3 ) {
  5031. bb.min.x = bb.max.x = positions[ 0 ];
  5032. bb.min.y = bb.max.y = positions[ 1 ];
  5033. bb.min.z = bb.max.z = positions[ 2 ];
  5034. }
  5035. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5036. x = positions[ i ];
  5037. y = positions[ i + 1 ];
  5038. z = positions[ i + 2 ];
  5039. // bounding box
  5040. if ( x < bb.min.x ) {
  5041. bb.min.x = x;
  5042. } else if ( x > bb.max.x ) {
  5043. bb.max.x = x;
  5044. }
  5045. if ( y < bb.min.y ) {
  5046. bb.min.y = y;
  5047. } else if ( y > bb.max.y ) {
  5048. bb.max.y = y;
  5049. }
  5050. if ( z < bb.min.z ) {
  5051. bb.min.z = z;
  5052. } else if ( z > bb.max.z ) {
  5053. bb.max.z = z;
  5054. }
  5055. }
  5056. }
  5057. if ( positions === undefined || positions.length === 0 ) {
  5058. this.boundingBox.min.set( 0, 0, 0 );
  5059. this.boundingBox.max.set( 0, 0, 0 );
  5060. }
  5061. },
  5062. computeBoundingSphere: function () {
  5063. if ( this.boundingSphere === null ) {
  5064. this.boundingSphere = new THREE.Sphere();
  5065. }
  5066. var positions = this.attributes[ "position" ].array;
  5067. if ( positions ) {
  5068. var radiusSq, maxRadiusSq = 0;
  5069. var x, y, z;
  5070. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5071. x = positions[ i ];
  5072. y = positions[ i + 1 ];
  5073. z = positions[ i + 2 ];
  5074. radiusSq = x * x + y * y + z * z;
  5075. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  5076. }
  5077. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5078. }
  5079. },
  5080. computeVertexNormals: function () {
  5081. if ( this.attributes[ "position" ] ) {
  5082. var i, il;
  5083. var j, jl;
  5084. var nVertexElements = this.attributes[ "position" ].array.length;
  5085. if ( this.attributes[ "normal" ] === undefined ) {
  5086. this.attributes[ "normal" ] = {
  5087. itemSize: 3,
  5088. array: new Float32Array( nVertexElements ),
  5089. numItems: nVertexElements
  5090. };
  5091. } else {
  5092. // reset existing normals to zero
  5093. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5094. this.attributes[ "normal" ].array[ i ] = 0;
  5095. }
  5096. }
  5097. var positions = this.attributes[ "position" ].array;
  5098. var normals = this.attributes[ "normal" ].array;
  5099. var vA, vB, vC, x, y, z,
  5100. pA = new THREE.Vector3(),
  5101. pB = new THREE.Vector3(),
  5102. pC = new THREE.Vector3(),
  5103. cb = new THREE.Vector3(),
  5104. ab = new THREE.Vector3();
  5105. // indexed elements
  5106. if ( this.attributes[ "index" ] ) {
  5107. var indices = this.attributes[ "index" ].array;
  5108. var offsets = this.offsets;
  5109. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5110. var start = offsets[ j ].start;
  5111. var count = offsets[ j ].count;
  5112. var index = offsets[ j ].index;
  5113. for ( i = start, il = start + count; i < il; i += 3 ) {
  5114. vA = index + indices[ i ];
  5115. vB = index + indices[ i + 1 ];
  5116. vC = index + indices[ i + 2 ];
  5117. x = positions[ vA * 3 ];
  5118. y = positions[ vA * 3 + 1 ];
  5119. z = positions[ vA * 3 + 2 ];
  5120. pA.set( x, y, z );
  5121. x = positions[ vB * 3 ];
  5122. y = positions[ vB * 3 + 1 ];
  5123. z = positions[ vB * 3 + 2 ];
  5124. pB.set( x, y, z );
  5125. x = positions[ vC * 3 ];
  5126. y = positions[ vC * 3 + 1 ];
  5127. z = positions[ vC * 3 + 2 ];
  5128. pC.set( x, y, z );
  5129. cb.subVectors( pC, pB );
  5130. ab.subVectors( pA, pB );
  5131. cb.cross( ab );
  5132. normals[ vA * 3 ] += cb.x;
  5133. normals[ vA * 3 + 1 ] += cb.y;
  5134. normals[ vA * 3 + 2 ] += cb.z;
  5135. normals[ vB * 3 ] += cb.x;
  5136. normals[ vB * 3 + 1 ] += cb.y;
  5137. normals[ vB * 3 + 2 ] += cb.z;
  5138. normals[ vC * 3 ] += cb.x;
  5139. normals[ vC * 3 + 1 ] += cb.y;
  5140. normals[ vC * 3 + 2 ] += cb.z;
  5141. }
  5142. }
  5143. // non-indexed elements (unconnected triangle soup)
  5144. } else {
  5145. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5146. x = positions[ i ];
  5147. y = positions[ i + 1 ];
  5148. z = positions[ i + 2 ];
  5149. pA.set( x, y, z );
  5150. x = positions[ i + 3 ];
  5151. y = positions[ i + 4 ];
  5152. z = positions[ i + 5 ];
  5153. pB.set( x, y, z );
  5154. x = positions[ i + 6 ];
  5155. y = positions[ i + 7 ];
  5156. z = positions[ i + 8 ];
  5157. pC.set( x, y, z );
  5158. cb.subVectors( pC, pB );
  5159. ab.subVectors( pA, pB );
  5160. cb.cross( ab );
  5161. normals[ i ] = cb.x;
  5162. normals[ i + 1 ] = cb.y;
  5163. normals[ i + 2 ] = cb.z;
  5164. normals[ i + 3 ] = cb.x;
  5165. normals[ i + 4 ] = cb.y;
  5166. normals[ i + 5 ] = cb.z;
  5167. normals[ i + 6 ] = cb.x;
  5168. normals[ i + 7 ] = cb.y;
  5169. normals[ i + 8 ] = cb.z;
  5170. }
  5171. }
  5172. this.normalizeNormals();
  5173. this.normalsNeedUpdate = true;
  5174. }
  5175. },
  5176. normalizeNormals: function () {
  5177. var normals = this.attributes[ "normal" ].array;
  5178. var x, y, z, n;
  5179. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5180. x = normals[ i ];
  5181. y = normals[ i + 1 ];
  5182. z = normals[ i + 2 ];
  5183. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5184. normals[ i ] *= n;
  5185. normals[ i + 1 ] *= n;
  5186. normals[ i + 2 ] *= n;
  5187. }
  5188. },
  5189. computeTangents: function () {
  5190. // based on http://www.terathon.com/code/tangent.html
  5191. // (per vertex tangents)
  5192. if ( this.attributes[ "index" ] === undefined ||
  5193. this.attributes[ "position" ] === undefined ||
  5194. this.attributes[ "normal" ] === undefined ||
  5195. this.attributes[ "uv" ] === undefined ) {
  5196. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5197. return;
  5198. }
  5199. var indices = this.attributes[ "index" ].array;
  5200. var positions = this.attributes[ "position" ].array;
  5201. var normals = this.attributes[ "normal" ].array;
  5202. var uvs = this.attributes[ "uv" ].array;
  5203. var nVertices = positions.length / 3;
  5204. if ( this.attributes[ "tangent" ] === undefined ) {
  5205. var nTangentElements = 4 * nVertices;
  5206. this.attributes[ "tangent" ] = {
  5207. itemSize: 4,
  5208. array: new Float32Array( nTangentElements ),
  5209. numItems: nTangentElements
  5210. };
  5211. }
  5212. var tangents = this.attributes[ "tangent" ].array;
  5213. var tan1 = [], tan2 = [];
  5214. for ( var k = 0; k < nVertices; k ++ ) {
  5215. tan1[ k ] = new THREE.Vector3();
  5216. tan2[ k ] = new THREE.Vector3();
  5217. }
  5218. var xA, yA, zA,
  5219. xB, yB, zB,
  5220. xC, yC, zC,
  5221. uA, vA,
  5222. uB, vB,
  5223. uC, vC,
  5224. x1, x2, y1, y2, z1, z2,
  5225. s1, s2, t1, t2, r;
  5226. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5227. function handleTriangle( a, b, c ) {
  5228. xA = positions[ a * 3 ];
  5229. yA = positions[ a * 3 + 1 ];
  5230. zA = positions[ a * 3 + 2 ];
  5231. xB = positions[ b * 3 ];
  5232. yB = positions[ b * 3 + 1 ];
  5233. zB = positions[ b * 3 + 2 ];
  5234. xC = positions[ c * 3 ];
  5235. yC = positions[ c * 3 + 1 ];
  5236. zC = positions[ c * 3 + 2 ];
  5237. uA = uvs[ a * 2 ];
  5238. vA = uvs[ a * 2 + 1 ];
  5239. uB = uvs[ b * 2 ];
  5240. vB = uvs[ b * 2 + 1 ];
  5241. uC = uvs[ c * 2 ];
  5242. vC = uvs[ c * 2 + 1 ];
  5243. x1 = xB - xA;
  5244. x2 = xC - xA;
  5245. y1 = yB - yA;
  5246. y2 = yC - yA;
  5247. z1 = zB - zA;
  5248. z2 = zC - zA;
  5249. s1 = uB - uA;
  5250. s2 = uC - uA;
  5251. t1 = vB - vA;
  5252. t2 = vC - vA;
  5253. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5254. sdir.set(
  5255. ( t2 * x1 - t1 * x2 ) * r,
  5256. ( t2 * y1 - t1 * y2 ) * r,
  5257. ( t2 * z1 - t1 * z2 ) * r
  5258. );
  5259. tdir.set(
  5260. ( s1 * x2 - s2 * x1 ) * r,
  5261. ( s1 * y2 - s2 * y1 ) * r,
  5262. ( s1 * z2 - s2 * z1 ) * r
  5263. );
  5264. tan1[ a ].add( sdir );
  5265. tan1[ b ].add( sdir );
  5266. tan1[ c ].add( sdir );
  5267. tan2[ a ].add( tdir );
  5268. tan2[ b ].add( tdir );
  5269. tan2[ c ].add( tdir );
  5270. }
  5271. var i, il;
  5272. var j, jl;
  5273. var iA, iB, iC;
  5274. var offsets = this.offsets;
  5275. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5276. var start = offsets[ j ].start;
  5277. var count = offsets[ j ].count;
  5278. var index = offsets[ j ].index;
  5279. for ( i = start, il = start + count; i < il; i += 3 ) {
  5280. iA = index + indices[ i ];
  5281. iB = index + indices[ i + 1 ];
  5282. iC = index + indices[ i + 2 ];
  5283. handleTriangle( iA, iB, iC );
  5284. }
  5285. }
  5286. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5287. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5288. var w, t, test;
  5289. function handleVertex( v ) {
  5290. n.x = normals[ v * 3 ];
  5291. n.y = normals[ v * 3 + 1 ];
  5292. n.z = normals[ v * 3 + 2 ];
  5293. n2.copy( n );
  5294. t = tan1[ v ];
  5295. // Gram-Schmidt orthogonalize
  5296. tmp.copy( t );
  5297. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5298. // Calculate handedness
  5299. tmp2.crossVectors( n2, t );
  5300. test = tmp2.dot( tan2[ v ] );
  5301. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5302. tangents[ v * 4 ] = tmp.x;
  5303. tangents[ v * 4 + 1 ] = tmp.y;
  5304. tangents[ v * 4 + 2 ] = tmp.z;
  5305. tangents[ v * 4 + 3 ] = w;
  5306. }
  5307. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5308. var start = offsets[ j ].start;
  5309. var count = offsets[ j ].count;
  5310. var index = offsets[ j ].index;
  5311. for ( i = start, il = start + count; i < il; i += 3 ) {
  5312. iA = index + indices[ i ];
  5313. iB = index + indices[ i + 1 ];
  5314. iC = index + indices[ i + 2 ];
  5315. handleVertex( iA );
  5316. handleVertex( iB );
  5317. handleVertex( iC );
  5318. }
  5319. }
  5320. this.hasTangents = true;
  5321. this.tangentsNeedUpdate = true;
  5322. },
  5323. dispose: function () {
  5324. this.dispatchEvent( { type: 'dispose' } );
  5325. }
  5326. };
  5327. /**
  5328. * @author mrdoob / http://mrdoob.com/
  5329. * @author mikael emtinger / http://gomo.se/
  5330. * @author WestLangley / http://github.com/WestLangley
  5331. */
  5332. THREE.Camera = function () {
  5333. THREE.Object3D.call( this );
  5334. this.matrixWorldInverse = new THREE.Matrix4();
  5335. this.projectionMatrix = new THREE.Matrix4();
  5336. this.projectionMatrixInverse = new THREE.Matrix4();
  5337. };
  5338. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5339. THREE.Camera.prototype.lookAt = function () {
  5340. // This routine does not support cameras with rotated and/or translated parent(s)
  5341. var m1 = new THREE.Matrix4();
  5342. return function ( vector ) {
  5343. m1.lookAt( this.position, vector, this.up );
  5344. if ( this.useQuaternion === true ) {
  5345. this.quaternion.setFromRotationMatrix( m1 );
  5346. } else {
  5347. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  5348. }
  5349. };
  5350. }();
  5351. /**
  5352. * @author alteredq / http://alteredqualia.com/
  5353. */
  5354. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5355. THREE.Camera.call( this );
  5356. this.left = left;
  5357. this.right = right;
  5358. this.top = top;
  5359. this.bottom = bottom;
  5360. this.near = ( near !== undefined ) ? near : 0.1;
  5361. this.far = ( far !== undefined ) ? far : 2000;
  5362. this.updateProjectionMatrix();
  5363. };
  5364. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5365. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5366. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5367. };
  5368. /**
  5369. * @author mrdoob / http://mrdoob.com/
  5370. * @author greggman / http://games.greggman.com/
  5371. * @author zz85 / http://www.lab4games.net/zz85/blog
  5372. */
  5373. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5374. THREE.Camera.call( this );
  5375. this.fov = fov !== undefined ? fov : 50;
  5376. this.aspect = aspect !== undefined ? aspect : 1;
  5377. this.near = near !== undefined ? near : 0.1;
  5378. this.far = far !== undefined ? far : 2000;
  5379. this.updateProjectionMatrix();
  5380. };
  5381. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5382. /**
  5383. * Uses Focal Length (in mm) to estimate and set FOV
  5384. * 35mm (fullframe) camera is used if frame size is not specified;
  5385. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5386. */
  5387. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5388. if ( frameHeight === undefined ) frameHeight = 24;
  5389. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5390. this.updateProjectionMatrix();
  5391. }
  5392. /**
  5393. * Sets an offset in a larger frustum. This is useful for multi-window or
  5394. * multi-monitor/multi-machine setups.
  5395. *
  5396. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5397. * the monitors are in grid like this
  5398. *
  5399. * +---+---+---+
  5400. * | A | B | C |
  5401. * +---+---+---+
  5402. * | D | E | F |
  5403. * +---+---+---+
  5404. *
  5405. * then for each monitor you would call it like this
  5406. *
  5407. * var w = 1920;
  5408. * var h = 1080;
  5409. * var fullWidth = w * 3;
  5410. * var fullHeight = h * 2;
  5411. *
  5412. * --A--
  5413. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5414. * --B--
  5415. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5416. * --C--
  5417. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5418. * --D--
  5419. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5420. * --E--
  5421. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5422. * --F--
  5423. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5424. *
  5425. * Note there is no reason monitors have to be the same size or in a grid.
  5426. */
  5427. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5428. this.fullWidth = fullWidth;
  5429. this.fullHeight = fullHeight;
  5430. this.x = x;
  5431. this.y = y;
  5432. this.width = width;
  5433. this.height = height;
  5434. this.updateProjectionMatrix();
  5435. };
  5436. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5437. if ( this.fullWidth ) {
  5438. var aspect = this.fullWidth / this.fullHeight;
  5439. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5440. var bottom = -top;
  5441. var left = aspect * bottom;
  5442. var right = aspect * top;
  5443. var width = Math.abs( right - left );
  5444. var height = Math.abs( top - bottom );
  5445. this.projectionMatrix.makeFrustum(
  5446. left + this.x * width / this.fullWidth,
  5447. left + ( this.x + this.width ) * width / this.fullWidth,
  5448. top - ( this.y + this.height ) * height / this.fullHeight,
  5449. top - this.y * height / this.fullHeight,
  5450. this.near,
  5451. this.far
  5452. );
  5453. } else {
  5454. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5455. }
  5456. };
  5457. /**
  5458. * @author mrdoob / http://mrdoob.com/
  5459. * @author alteredq / http://alteredqualia.com/
  5460. */
  5461. THREE.Light = function ( hex ) {
  5462. THREE.Object3D.call( this );
  5463. this.color = new THREE.Color( hex );
  5464. };
  5465. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5466. THREE.Light.prototype.clone = function ( light ) {
  5467. if ( light === undefined ) light = new THREE.Light();
  5468. THREE.Object3D.prototype.clone.call( this, light );
  5469. light.color.copy( this.color );
  5470. return light;
  5471. };
  5472. /**
  5473. * @author mrdoob / http://mrdoob.com/
  5474. */
  5475. THREE.AmbientLight = function ( hex ) {
  5476. THREE.Light.call( this, hex );
  5477. };
  5478. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5479. THREE.AmbientLight.prototype.clone = function () {
  5480. var light = new THREE.AmbientLight();
  5481. THREE.Light.prototype.clone.call( this, light );
  5482. return light;
  5483. };
  5484. /**
  5485. * @author MPanknin / http://www.redplant.de/
  5486. * @author alteredq / http://alteredqualia.com/
  5487. */
  5488. THREE.AreaLight = function ( hex, intensity ) {
  5489. THREE.Light.call( this, hex );
  5490. this.normal = new THREE.Vector3( 0, -1, 0 );
  5491. this.right = new THREE.Vector3( 1, 0, 0 );
  5492. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5493. this.width = 1.0;
  5494. this.height = 1.0;
  5495. this.constantAttenuation = 1.5;
  5496. this.linearAttenuation = 0.5;
  5497. this.quadraticAttenuation = 0.1;
  5498. };
  5499. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5500. /**
  5501. * @author mrdoob / http://mrdoob.com/
  5502. * @author alteredq / http://alteredqualia.com/
  5503. */
  5504. THREE.DirectionalLight = function ( hex, intensity ) {
  5505. THREE.Light.call( this, hex );
  5506. this.position.set( 0, 1, 0 );
  5507. this.target = new THREE.Object3D();
  5508. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5509. this.castShadow = false;
  5510. this.onlyShadow = false;
  5511. //
  5512. this.shadowCameraNear = 50;
  5513. this.shadowCameraFar = 5000;
  5514. this.shadowCameraLeft = -500;
  5515. this.shadowCameraRight = 500;
  5516. this.shadowCameraTop = 500;
  5517. this.shadowCameraBottom = -500;
  5518. this.shadowCameraVisible = false;
  5519. this.shadowBias = 0;
  5520. this.shadowDarkness = 0.5;
  5521. this.shadowMapWidth = 512;
  5522. this.shadowMapHeight = 512;
  5523. //
  5524. this.shadowCascade = false;
  5525. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5526. this.shadowCascadeCount = 2;
  5527. this.shadowCascadeBias = [ 0, 0, 0 ];
  5528. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5529. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5530. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5531. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5532. this.shadowCascadeArray = [];
  5533. //
  5534. this.shadowMap = null;
  5535. this.shadowMapSize = null;
  5536. this.shadowCamera = null;
  5537. this.shadowMatrix = null;
  5538. };
  5539. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5540. THREE.DirectionalLight.prototype.clone = function () {
  5541. var light = new THREE.DirectionalLight();
  5542. THREE.Light.prototype.clone.call( this, light );
  5543. light.target = this.target.clone();
  5544. light.intensity = this.intensity;
  5545. light.castShadow = this.castShadow;
  5546. light.onlyShadow = this.onlyShadow;
  5547. return light;
  5548. };
  5549. /**
  5550. * @author alteredq / http://alteredqualia.com/
  5551. */
  5552. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5553. THREE.Light.call( this, skyColorHex );
  5554. this.position.set( 0, 100, 0 );
  5555. this.groundColor = new THREE.Color( groundColorHex );
  5556. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5557. };
  5558. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5559. THREE.HemisphereLight.prototype.clone = function () {
  5560. var light = new THREE.PointLight();
  5561. THREE.Light.prototype.clone.call( this, light );
  5562. light.groundColor.copy( this.groundColor );
  5563. light.intensity = this.intensity;
  5564. return light;
  5565. };
  5566. /**
  5567. * @author mrdoob / http://mrdoob.com/
  5568. */
  5569. THREE.PointLight = function ( hex, intensity, distance ) {
  5570. THREE.Light.call( this, hex );
  5571. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5572. this.distance = ( distance !== undefined ) ? distance : 0;
  5573. };
  5574. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5575. THREE.PointLight.prototype.clone = function () {
  5576. var light = new THREE.PointLight();
  5577. THREE.Light.prototype.clone.call( this, light );
  5578. light.intensity = this.intensity;
  5579. light.distance = this.distance;
  5580. return light;
  5581. };
  5582. /**
  5583. * @author alteredq / http://alteredqualia.com/
  5584. */
  5585. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5586. THREE.Light.call( this, hex );
  5587. this.position.set( 0, 1, 0 );
  5588. this.target = new THREE.Object3D();
  5589. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5590. this.distance = ( distance !== undefined ) ? distance : 0;
  5591. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  5592. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5593. this.castShadow = false;
  5594. this.onlyShadow = false;
  5595. //
  5596. this.shadowCameraNear = 50;
  5597. this.shadowCameraFar = 5000;
  5598. this.shadowCameraFov = 50;
  5599. this.shadowCameraVisible = false;
  5600. this.shadowBias = 0;
  5601. this.shadowDarkness = 0.5;
  5602. this.shadowMapWidth = 512;
  5603. this.shadowMapHeight = 512;
  5604. //
  5605. this.shadowMap = null;
  5606. this.shadowMapSize = null;
  5607. this.shadowCamera = null;
  5608. this.shadowMatrix = null;
  5609. };
  5610. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5611. THREE.SpotLight.prototype.clone = function () {
  5612. var light = new THREE.SpotLight();
  5613. THREE.Light.prototype.clone.call( this, light );
  5614. light.target = this.target.clone();
  5615. light.intensity = this.intensity;
  5616. light.distance = this.distance;
  5617. light.angle = this.angle;
  5618. light.exponent = this.exponent;
  5619. light.castShadow = this.castShadow;
  5620. light.onlyShadow = this.onlyShadow;
  5621. return light;
  5622. };
  5623. /**
  5624. * @author alteredq / http://alteredqualia.com/
  5625. */
  5626. THREE.Loader = function ( showStatus ) {
  5627. this.showStatus = showStatus;
  5628. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5629. this.onLoadStart = function () {};
  5630. this.onLoadProgress = function () {};
  5631. this.onLoadComplete = function () {};
  5632. };
  5633. THREE.Loader.prototype = {
  5634. constructor: THREE.Loader,
  5635. crossOrigin: 'anonymous',
  5636. addStatusElement: function () {
  5637. var e = document.createElement( "div" );
  5638. e.style.position = "absolute";
  5639. e.style.right = "0px";
  5640. e.style.top = "0px";
  5641. e.style.fontSize = "0.8em";
  5642. e.style.textAlign = "left";
  5643. e.style.background = "rgba(0,0,0,0.25)";
  5644. e.style.color = "#fff";
  5645. e.style.width = "120px";
  5646. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5647. e.style.zIndex = 1000;
  5648. e.innerHTML = "Loading ...";
  5649. return e;
  5650. },
  5651. updateProgress: function ( progress ) {
  5652. var message = "Loaded ";
  5653. if ( progress.total ) {
  5654. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5655. } else {
  5656. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5657. }
  5658. this.statusDomElement.innerHTML = message;
  5659. },
  5660. extractUrlBase: function ( url ) {
  5661. var parts = url.split( '/' );
  5662. parts.pop();
  5663. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5664. },
  5665. initMaterials: function ( materials, texturePath ) {
  5666. var array = [];
  5667. for ( var i = 0; i < materials.length; ++ i ) {
  5668. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5669. }
  5670. return array;
  5671. },
  5672. needsTangents: function ( materials ) {
  5673. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5674. var m = materials[ i ];
  5675. if ( m instanceof THREE.ShaderMaterial ) return true;
  5676. }
  5677. return false;
  5678. },
  5679. createMaterial: function ( m, texturePath ) {
  5680. var _this = this;
  5681. function is_pow2( n ) {
  5682. var l = Math.log( n ) / Math.LN2;
  5683. return Math.floor( l ) == l;
  5684. }
  5685. function nearest_pow2( n ) {
  5686. var l = Math.log( n ) / Math.LN2;
  5687. return Math.pow( 2, Math.round( l ) );
  5688. }
  5689. function load_image( where, url ) {
  5690. var image = new Image();
  5691. image.onload = function () {
  5692. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5693. var width = nearest_pow2( this.width );
  5694. var height = nearest_pow2( this.height );
  5695. where.image.width = width;
  5696. where.image.height = height;
  5697. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5698. } else {
  5699. where.image = this;
  5700. }
  5701. where.needsUpdate = true;
  5702. };
  5703. image.crossOrigin = _this.crossOrigin;
  5704. image.src = url;
  5705. }
  5706. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5707. var isCompressed = /\.dds$/i.test( sourceFile );
  5708. var fullPath = texturePath + "/" + sourceFile;
  5709. if ( isCompressed ) {
  5710. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5711. where[ name ] = texture;
  5712. } else {
  5713. var texture = document.createElement( 'canvas' );
  5714. where[ name ] = new THREE.Texture( texture );
  5715. }
  5716. where[ name ].sourceFile = sourceFile;
  5717. if( repeat ) {
  5718. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5719. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5720. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5721. }
  5722. if ( offset ) {
  5723. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5724. }
  5725. if ( wrap ) {
  5726. var wrapMap = {
  5727. "repeat": THREE.RepeatWrapping,
  5728. "mirror": THREE.MirroredRepeatWrapping
  5729. }
  5730. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5731. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5732. }
  5733. if ( anisotropy ) {
  5734. where[ name ].anisotropy = anisotropy;
  5735. }
  5736. if ( ! isCompressed ) {
  5737. load_image( where[ name ], fullPath );
  5738. }
  5739. }
  5740. function rgb2hex( rgb ) {
  5741. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5742. }
  5743. // defaults
  5744. var mtype = "MeshLambertMaterial";
  5745. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5746. // parameters from model file
  5747. if ( m.shading ) {
  5748. var shading = m.shading.toLowerCase();
  5749. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5750. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5751. }
  5752. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5753. mpars.blending = THREE[ m.blending ];
  5754. }
  5755. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5756. mpars.transparent = m.transparent;
  5757. }
  5758. if ( m.depthTest !== undefined ) {
  5759. mpars.depthTest = m.depthTest;
  5760. }
  5761. if ( m.depthWrite !== undefined ) {
  5762. mpars.depthWrite = m.depthWrite;
  5763. }
  5764. if ( m.visible !== undefined ) {
  5765. mpars.visible = m.visible;
  5766. }
  5767. if ( m.flipSided !== undefined ) {
  5768. mpars.side = THREE.BackSide;
  5769. }
  5770. if ( m.doubleSided !== undefined ) {
  5771. mpars.side = THREE.DoubleSide;
  5772. }
  5773. if ( m.wireframe !== undefined ) {
  5774. mpars.wireframe = m.wireframe;
  5775. }
  5776. if ( m.vertexColors !== undefined ) {
  5777. if ( m.vertexColors === "face" ) {
  5778. mpars.vertexColors = THREE.FaceColors;
  5779. } else if ( m.vertexColors ) {
  5780. mpars.vertexColors = THREE.VertexColors;
  5781. }
  5782. }
  5783. // colors
  5784. if ( m.colorDiffuse ) {
  5785. mpars.color = rgb2hex( m.colorDiffuse );
  5786. } else if ( m.DbgColor ) {
  5787. mpars.color = m.DbgColor;
  5788. }
  5789. if ( m.colorSpecular ) {
  5790. mpars.specular = rgb2hex( m.colorSpecular );
  5791. }
  5792. if ( m.colorAmbient ) {
  5793. mpars.ambient = rgb2hex( m.colorAmbient );
  5794. }
  5795. // modifiers
  5796. if ( m.transparency ) {
  5797. mpars.opacity = m.transparency;
  5798. }
  5799. if ( m.specularCoef ) {
  5800. mpars.shininess = m.specularCoef;
  5801. }
  5802. // textures
  5803. if ( m.mapDiffuse && texturePath ) {
  5804. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5805. }
  5806. if ( m.mapLight && texturePath ) {
  5807. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5808. }
  5809. if ( m.mapBump && texturePath ) {
  5810. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5811. }
  5812. if ( m.mapNormal && texturePath ) {
  5813. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5814. }
  5815. if ( m.mapSpecular && texturePath ) {
  5816. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5817. }
  5818. //
  5819. if ( m.mapBumpScale ) {
  5820. mpars.bumpScale = m.mapBumpScale;
  5821. }
  5822. // special case for normal mapped material
  5823. if ( m.mapNormal ) {
  5824. var shader = THREE.ShaderLib[ "normalmap" ];
  5825. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5826. uniforms[ "tNormal" ].value = mpars.normalMap;
  5827. if ( m.mapNormalFactor ) {
  5828. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5829. }
  5830. if ( mpars.map ) {
  5831. uniforms[ "tDiffuse" ].value = mpars.map;
  5832. uniforms[ "enableDiffuse" ].value = true;
  5833. }
  5834. if ( mpars.specularMap ) {
  5835. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5836. uniforms[ "enableSpecular" ].value = true;
  5837. }
  5838. if ( mpars.lightMap ) {
  5839. uniforms[ "tAO" ].value = mpars.lightMap;
  5840. uniforms[ "enableAO" ].value = true;
  5841. }
  5842. // for the moment don't handle displacement texture
  5843. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5844. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5845. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5846. uniforms[ "uShininess" ].value = mpars.shininess;
  5847. if ( mpars.opacity !== undefined ) {
  5848. uniforms[ "uOpacity" ].value = mpars.opacity;
  5849. }
  5850. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5851. var material = new THREE.ShaderMaterial( parameters );
  5852. if ( mpars.transparent ) {
  5853. material.transparent = true;
  5854. }
  5855. } else {
  5856. var material = new THREE[ mtype ]( mpars );
  5857. }
  5858. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5859. return material;
  5860. }
  5861. };
  5862. /**
  5863. * @author mrdoob / http://mrdoob.com/
  5864. */
  5865. THREE.ImageLoader = function () {
  5866. this.crossOrigin = null;
  5867. };
  5868. THREE.ImageLoader.prototype = {
  5869. constructor: THREE.ImageLoader,
  5870. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  5871. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  5872. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  5873. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  5874. load: function ( url, image ) {
  5875. var scope = this;
  5876. if ( image === undefined ) image = new Image();
  5877. image.addEventListener( 'load', function () {
  5878. scope.dispatchEvent( { type: 'load', content: image } );
  5879. }, false );
  5880. image.addEventListener( 'error', function () {
  5881. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5882. }, false );
  5883. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5884. image.src = url;
  5885. }
  5886. }
  5887. /**
  5888. * @author mrdoob / http://mrdoob.com/
  5889. * @author alteredq / http://alteredqualia.com/
  5890. */
  5891. THREE.JSONLoader = function ( showStatus ) {
  5892. THREE.Loader.call( this, showStatus );
  5893. this.withCredentials = false;
  5894. };
  5895. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5896. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5897. var scope = this;
  5898. // todo: unify load API to for easier SceneLoader use
  5899. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5900. this.onLoadStart();
  5901. this.loadAjaxJSON( this, url, callback, texturePath );
  5902. };
  5903. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5904. var xhr = new XMLHttpRequest();
  5905. var length = 0;
  5906. xhr.onreadystatechange = function () {
  5907. if ( xhr.readyState === xhr.DONE ) {
  5908. if ( xhr.status === 200 || xhr.status === 0 ) {
  5909. if ( xhr.responseText ) {
  5910. var json = JSON.parse( xhr.responseText );
  5911. var result = context.parse( json, texturePath );
  5912. callback( result.geometry, result.materials );
  5913. } else {
  5914. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5915. }
  5916. // in context of more complex asset initialization
  5917. // do not block on single failed file
  5918. // maybe should go even one more level up
  5919. context.onLoadComplete();
  5920. } else {
  5921. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5922. }
  5923. } else if ( xhr.readyState === xhr.LOADING ) {
  5924. if ( callbackProgress ) {
  5925. if ( length === 0 ) {
  5926. length = xhr.getResponseHeader( "Content-Length" );
  5927. }
  5928. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5929. }
  5930. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5931. if ( callbackProgress !== undefined ) {
  5932. length = xhr.getResponseHeader( "Content-Length" );
  5933. }
  5934. }
  5935. };
  5936. xhr.open( "GET", url, true );
  5937. xhr.withCredentials = this.withCredentials;
  5938. xhr.send( null );
  5939. };
  5940. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  5941. var scope = this,
  5942. geometry = new THREE.Geometry(),
  5943. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5944. parseModel( scale );
  5945. parseSkin();
  5946. parseMorphing( scale );
  5947. geometry.computeCentroids();
  5948. geometry.computeFaceNormals();
  5949. function parseModel( scale ) {
  5950. function isBitSet( value, position ) {
  5951. return value & ( 1 << position );
  5952. }
  5953. var i, j, fi,
  5954. offset, zLength, nVertices,
  5955. colorIndex, normalIndex, uvIndex, materialIndex,
  5956. type,
  5957. isQuad,
  5958. hasMaterial,
  5959. hasFaceUv, hasFaceVertexUv,
  5960. hasFaceNormal, hasFaceVertexNormal,
  5961. hasFaceColor, hasFaceVertexColor,
  5962. vertex, face, color, normal,
  5963. uvLayer, uvs, u, v,
  5964. faces = json.faces,
  5965. vertices = json.vertices,
  5966. normals = json.normals,
  5967. colors = json.colors,
  5968. nUvLayers = 0;
  5969. // disregard empty arrays
  5970. for ( i = 0; i < json.uvs.length; i++ ) {
  5971. if ( json.uvs[ i ].length ) nUvLayers ++;
  5972. }
  5973. for ( i = 0; i < nUvLayers; i++ ) {
  5974. geometry.faceUvs[ i ] = [];
  5975. geometry.faceVertexUvs[ i ] = [];
  5976. }
  5977. offset = 0;
  5978. zLength = vertices.length;
  5979. while ( offset < zLength ) {
  5980. vertex = new THREE.Vector3();
  5981. vertex.x = vertices[ offset ++ ] * scale;
  5982. vertex.y = vertices[ offset ++ ] * scale;
  5983. vertex.z = vertices[ offset ++ ] * scale;
  5984. geometry.vertices.push( vertex );
  5985. }
  5986. offset = 0;
  5987. zLength = faces.length;
  5988. while ( offset < zLength ) {
  5989. type = faces[ offset ++ ];
  5990. isQuad = isBitSet( type, 0 );
  5991. hasMaterial = isBitSet( type, 1 );
  5992. hasFaceUv = isBitSet( type, 2 );
  5993. hasFaceVertexUv = isBitSet( type, 3 );
  5994. hasFaceNormal = isBitSet( type, 4 );
  5995. hasFaceVertexNormal = isBitSet( type, 5 );
  5996. hasFaceColor = isBitSet( type, 6 );
  5997. hasFaceVertexColor = isBitSet( type, 7 );
  5998. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5999. if ( isQuad ) {
  6000. face = new THREE.Face4();
  6001. face.a = faces[ offset ++ ];
  6002. face.b = faces[ offset ++ ];
  6003. face.c = faces[ offset ++ ];
  6004. face.d = faces[ offset ++ ];
  6005. nVertices = 4;
  6006. } else {
  6007. face = new THREE.Face3();
  6008. face.a = faces[ offset ++ ];
  6009. face.b = faces[ offset ++ ];
  6010. face.c = faces[ offset ++ ];
  6011. nVertices = 3;
  6012. }
  6013. if ( hasMaterial ) {
  6014. materialIndex = faces[ offset ++ ];
  6015. face.materialIndex = materialIndex;
  6016. }
  6017. // to get face <=> uv index correspondence
  6018. fi = geometry.faces.length;
  6019. if ( hasFaceUv ) {
  6020. for ( i = 0; i < nUvLayers; i++ ) {
  6021. uvLayer = json.uvs[ i ];
  6022. uvIndex = faces[ offset ++ ];
  6023. u = uvLayer[ uvIndex * 2 ];
  6024. v = uvLayer[ uvIndex * 2 + 1 ];
  6025. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  6026. }
  6027. }
  6028. if ( hasFaceVertexUv ) {
  6029. for ( i = 0; i < nUvLayers; i++ ) {
  6030. uvLayer = json.uvs[ i ];
  6031. uvs = [];
  6032. for ( j = 0; j < nVertices; j ++ ) {
  6033. uvIndex = faces[ offset ++ ];
  6034. u = uvLayer[ uvIndex * 2 ];
  6035. v = uvLayer[ uvIndex * 2 + 1 ];
  6036. uvs[ j ] = new THREE.Vector2( u, v );
  6037. }
  6038. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  6039. }
  6040. }
  6041. if ( hasFaceNormal ) {
  6042. normalIndex = faces[ offset ++ ] * 3;
  6043. normal = new THREE.Vector3();
  6044. normal.x = normals[ normalIndex ++ ];
  6045. normal.y = normals[ normalIndex ++ ];
  6046. normal.z = normals[ normalIndex ];
  6047. face.normal = normal;
  6048. }
  6049. if ( hasFaceVertexNormal ) {
  6050. for ( i = 0; i < nVertices; i++ ) {
  6051. normalIndex = faces[ offset ++ ] * 3;
  6052. normal = new THREE.Vector3();
  6053. normal.x = normals[ normalIndex ++ ];
  6054. normal.y = normals[ normalIndex ++ ];
  6055. normal.z = normals[ normalIndex ];
  6056. face.vertexNormals.push( normal );
  6057. }
  6058. }
  6059. if ( hasFaceColor ) {
  6060. colorIndex = faces[ offset ++ ];
  6061. color = new THREE.Color( colors[ colorIndex ] );
  6062. face.color = color;
  6063. }
  6064. if ( hasFaceVertexColor ) {
  6065. for ( i = 0; i < nVertices; i++ ) {
  6066. colorIndex = faces[ offset ++ ];
  6067. color = new THREE.Color( colors[ colorIndex ] );
  6068. face.vertexColors.push( color );
  6069. }
  6070. }
  6071. geometry.faces.push( face );
  6072. }
  6073. };
  6074. function parseSkin() {
  6075. var i, l, x, y, z, w, a, b, c, d;
  6076. if ( json.skinWeights ) {
  6077. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6078. x = json.skinWeights[ i ];
  6079. y = json.skinWeights[ i + 1 ];
  6080. z = 0;
  6081. w = 0;
  6082. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6083. }
  6084. }
  6085. if ( json.skinIndices ) {
  6086. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6087. a = json.skinIndices[ i ];
  6088. b = json.skinIndices[ i + 1 ];
  6089. c = 0;
  6090. d = 0;
  6091. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6092. }
  6093. }
  6094. geometry.bones = json.bones;
  6095. geometry.animation = json.animation;
  6096. };
  6097. function parseMorphing( scale ) {
  6098. if ( json.morphTargets !== undefined ) {
  6099. var i, l, v, vl, dstVertices, srcVertices;
  6100. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6101. geometry.morphTargets[ i ] = {};
  6102. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6103. geometry.morphTargets[ i ].vertices = [];
  6104. dstVertices = geometry.morphTargets[ i ].vertices;
  6105. srcVertices = json.morphTargets [ i ].vertices;
  6106. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6107. var vertex = new THREE.Vector3();
  6108. vertex.x = srcVertices[ v ] * scale;
  6109. vertex.y = srcVertices[ v + 1 ] * scale;
  6110. vertex.z = srcVertices[ v + 2 ] * scale;
  6111. dstVertices.push( vertex );
  6112. }
  6113. }
  6114. }
  6115. if ( json.morphColors !== undefined ) {
  6116. var i, l, c, cl, dstColors, srcColors, color;
  6117. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6118. geometry.morphColors[ i ] = {};
  6119. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6120. geometry.morphColors[ i ].colors = [];
  6121. dstColors = geometry.morphColors[ i ].colors;
  6122. srcColors = json.morphColors [ i ].colors;
  6123. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6124. color = new THREE.Color( 0xffaa00 );
  6125. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6126. dstColors.push( color );
  6127. }
  6128. }
  6129. }
  6130. };
  6131. if ( json.materials === undefined ) {
  6132. return { geometry: geometry };
  6133. } else {
  6134. var materials = this.initMaterials( json.materials, texturePath );
  6135. if ( this.needsTangents( materials ) ) {
  6136. geometry.computeTangents();
  6137. }
  6138. return { geometry: geometry, materials: materials };
  6139. }
  6140. };
  6141. /**
  6142. * @author mrdoob / http://mrdoob.com/
  6143. */
  6144. THREE.LoadingMonitor = function () {
  6145. var scope = this;
  6146. var loaded = 0;
  6147. var total = 0;
  6148. var onLoad = function ( event ) {
  6149. loaded ++;
  6150. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  6151. if ( loaded === total ) {
  6152. scope.dispatchEvent( { type: 'load' } );
  6153. }
  6154. };
  6155. this.add = function ( loader ) {
  6156. total ++;
  6157. loader.addEventListener( 'load', onLoad, false );
  6158. };
  6159. };
  6160. THREE.LoadingMonitor.prototype = {
  6161. constructor: THREE.LoadingMonitor,
  6162. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  6163. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  6164. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  6165. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent
  6166. };
  6167. /**
  6168. * @author mrdoob / http://mrdoob.com/
  6169. */
  6170. THREE.GeometryLoader = function () {};
  6171. THREE.GeometryLoader.prototype = {
  6172. constructor: THREE.GeometryLoader,
  6173. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  6174. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  6175. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  6176. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  6177. load: function ( url ) {
  6178. var scope = this;
  6179. var request = new XMLHttpRequest();
  6180. request.addEventListener( 'load', function ( event ) {
  6181. var response = scope.parse( JSON.parse( event.target.responseText ) );
  6182. scope.dispatchEvent( { type: 'load', content: response } );
  6183. }, false );
  6184. request.addEventListener( 'progress', function ( event ) {
  6185. scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
  6186. }, false );
  6187. request.addEventListener( 'error', function () {
  6188. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6189. }, false );
  6190. request.open( 'GET', url, true );
  6191. request.send( null );
  6192. },
  6193. parse: function ( json ) {
  6194. }
  6195. };
  6196. /**
  6197. * @author mrdoob / http://mrdoob.com/
  6198. */
  6199. THREE.MaterialLoader = function () {};
  6200. THREE.MaterialLoader.prototype = {
  6201. constructor: THREE.MaterialLoader,
  6202. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  6203. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  6204. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  6205. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  6206. load: function ( url ) {
  6207. var scope = this;
  6208. var request = new XMLHttpRequest();
  6209. request.addEventListener( 'load', function ( event ) {
  6210. var response = scope.parse( JSON.parse( event.target.responseText ) );
  6211. scope.dispatchEvent( { type: 'load', content: response } );
  6212. }, false );
  6213. request.addEventListener( 'progress', function ( event ) {
  6214. scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
  6215. }, false );
  6216. request.addEventListener( 'error', function () {
  6217. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6218. }, false );
  6219. request.open( 'GET', url, true );
  6220. request.send( null );
  6221. },
  6222. parse: function ( json ) {
  6223. var material;
  6224. switch ( json.type ) {
  6225. case 'MeshBasicMaterial':
  6226. material = new THREE.MeshBasicMaterial( {
  6227. color: json.color,
  6228. opacity: json.opacity,
  6229. transparent: json.transparent,
  6230. wireframe: json.wireframe
  6231. } );
  6232. break;
  6233. case 'MeshLambertMaterial':
  6234. material = new THREE.MeshLambertMaterial( {
  6235. color: json.color,
  6236. ambient: json.ambient,
  6237. emissive: json.emissive,
  6238. opacity: json.opacity,
  6239. transparent: json.transparent,
  6240. wireframe: json.wireframe
  6241. } );
  6242. break;
  6243. case 'MeshPhongMaterial':
  6244. material = new THREE.MeshPhongMaterial( {
  6245. color: json.color,
  6246. ambient: json.ambient,
  6247. emissive: json.emissive,
  6248. specular: json.specular,
  6249. shininess: json.shininess,
  6250. opacity: json.opacity,
  6251. transparent: json.transparent,
  6252. wireframe: json.wireframe
  6253. } );
  6254. break;
  6255. case 'MeshNormalMaterial':
  6256. material = new THREE.MeshNormalMaterial( {
  6257. opacity: json.opacity,
  6258. transparent: json.transparent,
  6259. wireframe: json.wireframe
  6260. } );
  6261. break;
  6262. case 'MeshDepthMaterial':
  6263. material = new THREE.MeshDepthMaterial( {
  6264. opacity: json.opacity,
  6265. transparent: json.transparent,
  6266. wireframe: json.wireframe
  6267. } );
  6268. break;
  6269. }
  6270. return material;
  6271. }
  6272. };
  6273. /**
  6274. * @author alteredq / http://alteredqualia.com/
  6275. */
  6276. THREE.SceneLoader = function () {
  6277. this.onLoadStart = function () {};
  6278. this.onLoadProgress = function() {};
  6279. this.onLoadComplete = function () {};
  6280. this.callbackSync = function () {};
  6281. this.callbackProgress = function () {};
  6282. this.geometryHandlerMap = {};
  6283. this.hierarchyHandlerMap = {};
  6284. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6285. };
  6286. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  6287. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  6288. var scope = this;
  6289. var xhr = new XMLHttpRequest();
  6290. xhr.onreadystatechange = function () {
  6291. if ( xhr.readyState === 4 ) {
  6292. if ( xhr.status === 200 || xhr.status === 0 ) {
  6293. var json = JSON.parse( xhr.responseText );
  6294. scope.parse( json, callbackFinished, url );
  6295. } else {
  6296. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6297. }
  6298. }
  6299. };
  6300. xhr.open( "GET", url, true );
  6301. xhr.send( null );
  6302. };
  6303. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  6304. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  6305. };
  6306. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  6307. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  6308. };
  6309. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  6310. var scope = this;
  6311. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  6312. var geometry, material, camera, fog,
  6313. texture, images, color,
  6314. light, hex, intensity,
  6315. counter_models, counter_textures,
  6316. total_models, total_textures,
  6317. result;
  6318. var target_array = [];
  6319. var data = json;
  6320. // async geometry loaders
  6321. for ( var typeID in this.geometryHandlerMap ) {
  6322. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  6323. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  6324. }
  6325. // async hierachy loaders
  6326. for ( var typeID in this.hierarchyHandlerMap ) {
  6327. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  6328. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  6329. }
  6330. counter_models = 0;
  6331. counter_textures = 0;
  6332. result = {
  6333. scene: new THREE.Scene(),
  6334. geometries: {},
  6335. face_materials: {},
  6336. materials: {},
  6337. textures: {},
  6338. objects: {},
  6339. cameras: {},
  6340. lights: {},
  6341. fogs: {},
  6342. empties: {},
  6343. groups: {}
  6344. };
  6345. if ( data.transform ) {
  6346. var position = data.transform.position,
  6347. rotation = data.transform.rotation,
  6348. scale = data.transform.scale;
  6349. if ( position ) {
  6350. result.scene.position.fromArray( position );
  6351. }
  6352. if ( rotation ) {
  6353. result.scene.rotation.fromArray( rotation );
  6354. }
  6355. if ( scale ) {
  6356. result.scene.scale.fromArray( scale );
  6357. }
  6358. if ( position || rotation || scale ) {
  6359. result.scene.updateMatrix();
  6360. result.scene.updateMatrixWorld();
  6361. }
  6362. }
  6363. function get_url( source_url, url_type ) {
  6364. if ( url_type == "relativeToHTML" ) {
  6365. return source_url;
  6366. } else {
  6367. return urlBase + "/" + source_url;
  6368. }
  6369. };
  6370. // toplevel loader function, delegates to handle_children
  6371. function handle_objects() {
  6372. handle_children( result.scene, data.objects );
  6373. }
  6374. // handle all the children from the loaded json and attach them to given parent
  6375. function handle_children( parent, children ) {
  6376. var mat, dst, pos, rot, scl, quat;
  6377. for ( var objID in children ) {
  6378. // check by id if child has already been handled,
  6379. // if not, create new object
  6380. var object = result.objects[ objID ];
  6381. var objJSON = children[ objID ];
  6382. if ( object === undefined ) {
  6383. // meshes
  6384. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {
  6385. if ( objJSON.loading === undefined ) {
  6386. var reservedTypes = {
  6387. "type": 1, "url": 1, "material": 1,
  6388. "position": 1, "rotation": 1, "scale" : 1,
  6389. "visible": 1, "children": 1, "userData": 1,
  6390. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  6391. };
  6392. var loaderParameters = {};
  6393. for ( var parType in objJSON ) {
  6394. if ( ! ( parType in reservedTypes ) ) {
  6395. loaderParameters[ parType ] = objJSON[ parType ];
  6396. }
  6397. }
  6398. material = result.materials[ objJSON.material ];
  6399. objJSON.loading = true;
  6400. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  6401. // ColladaLoader
  6402. if ( loader.options ) {
  6403. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6404. // UTF8Loader
  6405. // OBJLoader
  6406. } else {
  6407. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6408. }
  6409. }
  6410. } else if ( objJSON.geometry !== undefined ) {
  6411. geometry = result.geometries[ objJSON.geometry ];
  6412. // geometry already loaded
  6413. if ( geometry ) {
  6414. var needsTangents = false;
  6415. material = result.materials[ objJSON.material ];
  6416. needsTangents = material instanceof THREE.ShaderMaterial;
  6417. pos = objJSON.position;
  6418. rot = objJSON.rotation;
  6419. scl = objJSON.scale;
  6420. mat = objJSON.matrix;
  6421. quat = objJSON.quaternion;
  6422. // use materials from the model file
  6423. // if there is no material specified in the object
  6424. if ( ! objJSON.material ) {
  6425. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6426. }
  6427. // use materials from the model file
  6428. // if there is just empty face material
  6429. // (must create new material as each model has its own face material)
  6430. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6431. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6432. }
  6433. if ( material instanceof THREE.MeshFaceMaterial ) {
  6434. for ( var i = 0; i < material.materials.length; i ++ ) {
  6435. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6436. }
  6437. }
  6438. if ( needsTangents ) {
  6439. geometry.computeTangents();
  6440. }
  6441. if ( objJSON.skin ) {
  6442. object = new THREE.SkinnedMesh( geometry, material );
  6443. } else if ( objJSON.morph ) {
  6444. object = new THREE.MorphAnimMesh( geometry, material );
  6445. if ( objJSON.duration !== undefined ) {
  6446. object.duration = objJSON.duration;
  6447. }
  6448. if ( objJSON.time !== undefined ) {
  6449. object.time = objJSON.time;
  6450. }
  6451. if ( objJSON.mirroredLoop !== undefined ) {
  6452. object.mirroredLoop = objJSON.mirroredLoop;
  6453. }
  6454. if ( material.morphNormals ) {
  6455. geometry.computeMorphNormals();
  6456. }
  6457. } else {
  6458. object = new THREE.Mesh( geometry, material );
  6459. }
  6460. object.name = objID;
  6461. if ( mat ) {
  6462. object.matrixAutoUpdate = false;
  6463. object.matrix.set(
  6464. mat[0], mat[1], mat[2], mat[3],
  6465. mat[4], mat[5], mat[6], mat[7],
  6466. mat[8], mat[9], mat[10], mat[11],
  6467. mat[12], mat[13], mat[14], mat[15]
  6468. );
  6469. } else {
  6470. object.position.fromArray( pos );
  6471. if ( quat ) {
  6472. object.quaternion.fromArray( quat );
  6473. object.useQuaternion = true;
  6474. } else {
  6475. object.rotation.fromArray( rot );
  6476. }
  6477. object.scale.fromArray( scl );
  6478. }
  6479. object.visible = objJSON.visible;
  6480. object.castShadow = objJSON.castShadow;
  6481. object.receiveShadow = objJSON.receiveShadow;
  6482. parent.add( object );
  6483. result.objects[ objID ] = object;
  6484. }
  6485. // lights
  6486. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6487. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6488. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6489. if ( objJSON.type === "DirectionalLight" ) {
  6490. pos = objJSON.direction;
  6491. light = new THREE.DirectionalLight( hex, intensity );
  6492. light.position.fromArray( pos );
  6493. if ( objJSON.target ) {
  6494. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6495. // kill existing default target
  6496. // otherwise it gets added to scene when parent gets added
  6497. light.target = null;
  6498. }
  6499. } else if ( objJSON.type === "PointLight" ) {
  6500. pos = objJSON.position;
  6501. dst = objJSON.distance;
  6502. light = new THREE.PointLight( hex, intensity, dst );
  6503. light.position.fromArray( pos );
  6504. } else if ( objJSON.type === "AmbientLight" ) {
  6505. light = new THREE.AmbientLight( hex );
  6506. }
  6507. parent.add( light );
  6508. light.name = objID;
  6509. result.lights[ objID ] = light;
  6510. result.objects[ objID ] = light;
  6511. // cameras
  6512. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6513. pos = objJSON.position;
  6514. rot = objJSON.rotation;
  6515. quat = objJSON.quaternion;
  6516. if ( objJSON.type === "PerspectiveCamera" ) {
  6517. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6518. } else if ( objJSON.type === "OrthographicCamera" ) {
  6519. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6520. }
  6521. camera.name = objID;
  6522. camera.position.fromArray( pos );
  6523. if ( quat !== undefined ) {
  6524. camera.quaternion.fromArray( quat );
  6525. camera.useQuaternion = true;
  6526. } else if ( rot !== undefined ) {
  6527. camera.rotation.fromArray( rot );
  6528. }
  6529. parent.add( camera );
  6530. result.cameras[ objID ] = camera;
  6531. result.objects[ objID ] = camera;
  6532. // pure Object3D
  6533. } else {
  6534. pos = objJSON.position;
  6535. rot = objJSON.rotation;
  6536. scl = objJSON.scale;
  6537. quat = objJSON.quaternion;
  6538. object = new THREE.Object3D();
  6539. object.name = objID;
  6540. object.position.fromArray( pos );
  6541. if ( quat ) {
  6542. object.quaternion.fromArray( quat );
  6543. object.useQuaternion = true;
  6544. } else {
  6545. object.rotation.fromArray( rot );
  6546. }
  6547. object.scale.fromArray( scl );
  6548. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6549. parent.add( object );
  6550. result.objects[ objID ] = object;
  6551. result.empties[ objID ] = object;
  6552. }
  6553. if ( object ) {
  6554. if ( objJSON.userData !== undefined ) {
  6555. for ( var key in objJSON.userData ) {
  6556. var value = objJSON.userData[ key ];
  6557. object.userData[ key ] = value;
  6558. }
  6559. }
  6560. if ( objJSON.groups !== undefined ) {
  6561. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  6562. var groupID = objJSON.groups[ i ];
  6563. if ( result.groups[ groupID ] === undefined ) {
  6564. result.groups[ groupID ] = [];
  6565. }
  6566. result.groups[ groupID ].push( objID );
  6567. }
  6568. }
  6569. }
  6570. }
  6571. if ( object !== undefined && objJSON.children !== undefined ) {
  6572. handle_children( object, objJSON.children );
  6573. }
  6574. }
  6575. };
  6576. function handle_mesh( geo, mat, id ) {
  6577. result.geometries[ id ] = geo;
  6578. result.face_materials[ id ] = mat;
  6579. handle_objects();
  6580. };
  6581. function handle_hierarchy( node, id, parent, material, obj ) {
  6582. var p = obj.position;
  6583. var r = obj.rotation;
  6584. var q = obj.quaternion;
  6585. var s = obj.scale;
  6586. node.position.fromArray( p );
  6587. if ( q ) {
  6588. node.quaternion.fromArray( q );
  6589. node.useQuaternion = true;
  6590. } else {
  6591. node.rotation.fromArray( r );
  6592. }
  6593. node.scale.fromArray( s );
  6594. // override children materials
  6595. // if object material was specified in JSON explicitly
  6596. if ( material ) {
  6597. node.traverse( function ( child ) {
  6598. child.material = material;
  6599. } );
  6600. }
  6601. // override children visibility
  6602. // with root node visibility as specified in JSON
  6603. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6604. node.traverse( function ( child ) {
  6605. child.visible = visible;
  6606. } );
  6607. parent.add( node );
  6608. node.name = id;
  6609. result.objects[ id ] = node;
  6610. handle_objects();
  6611. };
  6612. function create_callback_geometry( id ) {
  6613. return function ( geo, mat ) {
  6614. geo.name = id;
  6615. handle_mesh( geo, mat, id );
  6616. counter_models -= 1;
  6617. scope.onLoadComplete();
  6618. async_callback_gate();
  6619. }
  6620. };
  6621. function create_callback_hierachy( id, parent, material, obj ) {
  6622. return function ( event ) {
  6623. var result;
  6624. // loaders which use EventDispatcher
  6625. if ( event.content ) {
  6626. result = event.content;
  6627. // ColladaLoader
  6628. } else if ( event.dae ) {
  6629. result = event.scene;
  6630. // UTF8Loader
  6631. } else {
  6632. result = event;
  6633. }
  6634. handle_hierarchy( result, id, parent, material, obj );
  6635. counter_models -= 1;
  6636. scope.onLoadComplete();
  6637. async_callback_gate();
  6638. }
  6639. };
  6640. function create_callback_embed( id ) {
  6641. return function ( geo, mat ) {
  6642. geo.name = id;
  6643. result.geometries[ id ] = geo;
  6644. result.face_materials[ id ] = mat;
  6645. }
  6646. };
  6647. function async_callback_gate() {
  6648. var progress = {
  6649. totalModels : total_models,
  6650. totalTextures : total_textures,
  6651. loadedModels : total_models - counter_models,
  6652. loadedTextures : total_textures - counter_textures
  6653. };
  6654. scope.callbackProgress( progress, result );
  6655. scope.onLoadProgress();
  6656. if ( counter_models === 0 && counter_textures === 0 ) {
  6657. finalize();
  6658. callbackFinished( result );
  6659. }
  6660. };
  6661. function finalize() {
  6662. // take care of targets which could be asynchronously loaded objects
  6663. for ( var i = 0; i < target_array.length; i ++ ) {
  6664. var ta = target_array[ i ];
  6665. var target = result.objects[ ta.targetName ];
  6666. if ( target ) {
  6667. ta.object.target = target;
  6668. } else {
  6669. // if there was error and target of specified name doesn't exist in the scene file
  6670. // create instead dummy target
  6671. // (target must be added to scene explicitly as parent is already added)
  6672. ta.object.target = new THREE.Object3D();
  6673. result.scene.add( ta.object.target );
  6674. }
  6675. ta.object.target.userData.targetInverse = ta.object;
  6676. }
  6677. };
  6678. var callbackTexture = function ( count ) {
  6679. counter_textures -= count;
  6680. async_callback_gate();
  6681. scope.onLoadComplete();
  6682. };
  6683. // must use this instead of just directly calling callbackTexture
  6684. // because of closure in the calling context loop
  6685. var generateTextureCallback = function ( count ) {
  6686. return function () {
  6687. callbackTexture( count );
  6688. };
  6689. };
  6690. function traverse_json_hierarchy( objJSON, callback ) {
  6691. callback( objJSON );
  6692. if ( objJSON.children !== undefined ) {
  6693. for ( var objChildID in objJSON.children ) {
  6694. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  6695. }
  6696. }
  6697. };
  6698. // first go synchronous elements
  6699. // fogs
  6700. var fogID, fogJSON;
  6701. for ( fogID in data.fogs ) {
  6702. fogJSON = data.fogs[ fogID ];
  6703. if ( fogJSON.type === "linear" ) {
  6704. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6705. } else if ( fogJSON.type === "exp2" ) {
  6706. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6707. }
  6708. color = fogJSON.color;
  6709. fog.color.setRGB( color[0], color[1], color[2] );
  6710. result.fogs[ fogID ] = fog;
  6711. }
  6712. // now come potentially asynchronous elements
  6713. // geometries
  6714. // count how many geometries will be loaded asynchronously
  6715. var geoID, geoJSON;
  6716. for ( geoID in data.geometries ) {
  6717. geoJSON = data.geometries[ geoID ];
  6718. if ( geoJSON.type in this.geometryHandlerMap ) {
  6719. counter_models += 1;
  6720. scope.onLoadStart();
  6721. }
  6722. }
  6723. // count how many hierarchies will be loaded asynchronously
  6724. for ( var objID in data.objects ) {
  6725. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  6726. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {
  6727. counter_models += 1;
  6728. scope.onLoadStart();
  6729. }
  6730. });
  6731. }
  6732. total_models = counter_models;
  6733. for ( geoID in data.geometries ) {
  6734. geoJSON = data.geometries[ geoID ];
  6735. if ( geoJSON.type === "cube" ) {
  6736. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6737. geometry.name = geoID;
  6738. result.geometries[ geoID ] = geometry;
  6739. } else if ( geoJSON.type === "plane" ) {
  6740. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6741. geometry.name = geoID;
  6742. result.geometries[ geoID ] = geometry;
  6743. } else if ( geoJSON.type === "sphere" ) {
  6744. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6745. geometry.name = geoID;
  6746. result.geometries[ geoID ] = geometry;
  6747. } else if ( geoJSON.type === "cylinder" ) {
  6748. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6749. geometry.name = geoID;
  6750. result.geometries[ geoID ] = geometry;
  6751. } else if ( geoJSON.type === "torus" ) {
  6752. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6753. geometry.name = geoID;
  6754. result.geometries[ geoID ] = geometry;
  6755. } else if ( geoJSON.type === "icosahedron" ) {
  6756. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6757. geometry.name = geoID;
  6758. result.geometries[ geoID ] = geometry;
  6759. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6760. var loaderParameters = {};
  6761. for ( var parType in geoJSON ) {
  6762. if ( parType !== "type" && parType !== "url" ) {
  6763. loaderParameters[ parType ] = geoJSON[ parType ];
  6764. }
  6765. }
  6766. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6767. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6768. } else if ( geoJSON.type === "embedded" ) {
  6769. var modelJson = data.embeds[ geoJSON.id ],
  6770. texture_path = "";
  6771. // pass metadata along to jsonLoader so it knows the format version
  6772. modelJson.metadata = data.metadata;
  6773. if ( modelJson ) {
  6774. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6775. var model = jsonLoader.parse( modelJson, texture_path );
  6776. create_callback_embed( geoID )( model.geometry, model.materials );
  6777. }
  6778. }
  6779. }
  6780. // textures
  6781. // count how many textures will be loaded asynchronously
  6782. var textureID, textureJSON;
  6783. for ( textureID in data.textures ) {
  6784. textureJSON = data.textures[ textureID ];
  6785. if ( textureJSON.url instanceof Array ) {
  6786. counter_textures += textureJSON.url.length;
  6787. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6788. scope.onLoadStart();
  6789. }
  6790. } else {
  6791. counter_textures += 1;
  6792. scope.onLoadStart();
  6793. }
  6794. }
  6795. total_textures = counter_textures;
  6796. for ( textureID in data.textures ) {
  6797. textureJSON = data.textures[ textureID ];
  6798. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6799. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6800. }
  6801. if ( textureJSON.url instanceof Array ) {
  6802. var count = textureJSON.url.length;
  6803. var url_array = [];
  6804. for( var i = 0; i < count; i ++ ) {
  6805. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6806. }
  6807. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  6808. if ( isCompressed ) {
  6809. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6810. } else {
  6811. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6812. }
  6813. } else {
  6814. var isCompressed = /\.dds$/i.test( textureJSON.url );
  6815. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6816. var textureCallback = generateTextureCallback( 1 );
  6817. if ( isCompressed ) {
  6818. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6819. } else {
  6820. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6821. }
  6822. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6823. texture.minFilter = THREE[ textureJSON.minFilter ];
  6824. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6825. texture.magFilter = THREE[ textureJSON.magFilter ];
  6826. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6827. if ( textureJSON.repeat ) {
  6828. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6829. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6830. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6831. }
  6832. if ( textureJSON.offset ) {
  6833. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6834. }
  6835. // handle wrap after repeat so that default repeat can be overriden
  6836. if ( textureJSON.wrap ) {
  6837. var wrapMap = {
  6838. "repeat": THREE.RepeatWrapping,
  6839. "mirror": THREE.MirroredRepeatWrapping
  6840. }
  6841. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6842. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6843. }
  6844. }
  6845. result.textures[ textureID ] = texture;
  6846. }
  6847. // materials
  6848. var matID, matJSON;
  6849. var parID;
  6850. for ( matID in data.materials ) {
  6851. matJSON = data.materials[ matID ];
  6852. for ( parID in matJSON.parameters ) {
  6853. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6854. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6855. } else if ( parID === "shading" ) {
  6856. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6857. } else if ( parID === "side" ) {
  6858. if ( matJSON.parameters[ parID ] == "double" ) {
  6859. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6860. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6861. matJSON.parameters[ parID ] = THREE.BackSide;
  6862. } else {
  6863. matJSON.parameters[ parID ] = THREE.FrontSide;
  6864. }
  6865. } else if ( parID === "blending" ) {
  6866. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6867. } else if ( parID === "combine" ) {
  6868. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  6869. } else if ( parID === "vertexColors" ) {
  6870. if ( matJSON.parameters[ parID ] == "face" ) {
  6871. matJSON.parameters[ parID ] = THREE.FaceColors;
  6872. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6873. } else if ( matJSON.parameters[ parID ] ) {
  6874. matJSON.parameters[ parID ] = THREE.VertexColors;
  6875. }
  6876. } else if ( parID === "wrapRGB" ) {
  6877. var v3 = matJSON.parameters[ parID ];
  6878. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6879. }
  6880. }
  6881. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6882. matJSON.parameters.transparent = true;
  6883. }
  6884. if ( matJSON.parameters.normalMap ) {
  6885. var shader = THREE.ShaderLib[ "normalmap" ];
  6886. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6887. var diffuse = matJSON.parameters.color;
  6888. var specular = matJSON.parameters.specular;
  6889. var ambient = matJSON.parameters.ambient;
  6890. var shininess = matJSON.parameters.shininess;
  6891. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6892. if ( matJSON.parameters.normalScale ) {
  6893. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6894. }
  6895. if ( matJSON.parameters.map ) {
  6896. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6897. uniforms[ "enableDiffuse" ].value = true;
  6898. }
  6899. if ( matJSON.parameters.envMap ) {
  6900. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6901. uniforms[ "enableReflection" ].value = true;
  6902. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6903. }
  6904. if ( matJSON.parameters.lightMap ) {
  6905. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6906. uniforms[ "enableAO" ].value = true;
  6907. }
  6908. if ( matJSON.parameters.specularMap ) {
  6909. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6910. uniforms[ "enableSpecular" ].value = true;
  6911. }
  6912. if ( matJSON.parameters.displacementMap ) {
  6913. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6914. uniforms[ "enableDisplacement" ].value = true;
  6915. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6916. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6917. }
  6918. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6919. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6920. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6921. uniforms[ "uShininess" ].value = shininess;
  6922. if ( matJSON.parameters.opacity ) {
  6923. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6924. }
  6925. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6926. material = new THREE.ShaderMaterial( parameters );
  6927. } else {
  6928. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6929. }
  6930. material.name = matID;
  6931. result.materials[ matID ] = material;
  6932. }
  6933. // second pass through all materials to initialize MeshFaceMaterials
  6934. // that could be referring to other materials out of order
  6935. for ( matID in data.materials ) {
  6936. matJSON = data.materials[ matID ];
  6937. if ( matJSON.parameters.materials ) {
  6938. var materialArray = [];
  6939. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6940. var label = matJSON.parameters.materials[ i ];
  6941. materialArray.push( result.materials[ label ] );
  6942. }
  6943. result.materials[ matID ].materials = materialArray;
  6944. }
  6945. }
  6946. // objects ( synchronous init of procedural primitives )
  6947. handle_objects();
  6948. // defaults
  6949. if ( result.cameras && data.defaults.camera ) {
  6950. result.currentCamera = result.cameras[ data.defaults.camera ];
  6951. }
  6952. if ( result.fogs && data.defaults.fog ) {
  6953. result.scene.fog = result.fogs[ data.defaults.fog ];
  6954. }
  6955. // synchronous callback
  6956. scope.callbackSync( result );
  6957. // just in case there are no async elements
  6958. async_callback_gate();
  6959. };
  6960. /**
  6961. * @author mrdoob / http://mrdoob.com/
  6962. */
  6963. THREE.TextureLoader = function () {
  6964. this.crossOrigin = null;
  6965. };
  6966. THREE.TextureLoader.prototype = {
  6967. constructor: THREE.TextureLoader,
  6968. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  6969. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  6970. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  6971. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  6972. load: function ( url ) {
  6973. var scope = this;
  6974. var image = new Image();
  6975. image.addEventListener( 'load', function () {
  6976. var texture = new THREE.Texture( image );
  6977. texture.needsUpdate = true;
  6978. scope.dispatchEvent( { type: 'load', content: texture } );
  6979. }, false );
  6980. image.addEventListener( 'error', function () {
  6981. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6982. }, false );
  6983. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6984. image.src = url;
  6985. }
  6986. };
  6987. /**
  6988. * @author mrdoob / http://mrdoob.com/
  6989. * @author alteredq / http://alteredqualia.com/
  6990. */
  6991. THREE.Material = function () {
  6992. this.id = THREE.Math.generateUUID();
  6993. this.name = '';
  6994. this.side = THREE.FrontSide;
  6995. this.opacity = 1;
  6996. this.transparent = false;
  6997. this.blending = THREE.NormalBlending;
  6998. this.blendSrc = THREE.SrcAlphaFactor;
  6999. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7000. this.blendEquation = THREE.AddEquation;
  7001. this.depthTest = true;
  7002. this.depthWrite = true;
  7003. this.polygonOffset = false;
  7004. this.polygonOffsetFactor = 0;
  7005. this.polygonOffsetUnits = 0;
  7006. this.alphaTest = 0;
  7007. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7008. this.visible = true;
  7009. this.needsUpdate = true;
  7010. };
  7011. THREE.Material.prototype = {
  7012. constructor: THREE.Material,
  7013. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  7014. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  7015. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  7016. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  7017. setValues: function ( values ) {
  7018. if ( values === undefined ) return;
  7019. for ( var key in values ) {
  7020. var newValue = values[ key ];
  7021. if ( newValue === undefined ) {
  7022. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7023. continue;
  7024. }
  7025. if ( key in this ) {
  7026. var currentValue = this[ key ];
  7027. if ( currentValue instanceof THREE.Color ) {
  7028. currentValue.set( newValue );
  7029. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7030. currentValue.copy( newValue );
  7031. } else if ( key == 'overdraw') {
  7032. // ensure overdraw is backwards-compatable with legacy boolean type
  7033. this[ key ] = Number(newValue);
  7034. } else {
  7035. this[ key ] = newValue;
  7036. }
  7037. }
  7038. }
  7039. },
  7040. clone: function ( material ) {
  7041. if ( material === undefined ) material = new THREE.Material();
  7042. material.name = this.name;
  7043. material.side = this.side;
  7044. material.opacity = this.opacity;
  7045. material.transparent = this.transparent;
  7046. material.blending = this.blending;
  7047. material.blendSrc = this.blendSrc;
  7048. material.blendDst = this.blendDst;
  7049. material.blendEquation = this.blendEquation;
  7050. material.depthTest = this.depthTest;
  7051. material.depthWrite = this.depthWrite;
  7052. material.polygonOffset = this.polygonOffset;
  7053. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7054. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7055. material.alphaTest = this.alphaTest;
  7056. material.overdraw = this.overdraw;
  7057. material.visible = this.visible;
  7058. return material;
  7059. },
  7060. dispose: function () {
  7061. this.dispatchEvent( { type: 'dispose' } );
  7062. }
  7063. };
  7064. /**
  7065. * @author mrdoob / http://mrdoob.com/
  7066. * @author alteredq / http://alteredqualia.com/
  7067. *
  7068. * parameters = {
  7069. * color: <hex>,
  7070. * opacity: <float>,
  7071. *
  7072. * blending: THREE.NormalBlending,
  7073. * depthTest: <bool>,
  7074. * depthWrite: <bool>,
  7075. *
  7076. * linewidth: <float>,
  7077. * linecap: "round",
  7078. * linejoin: "round",
  7079. *
  7080. * vertexColors: <bool>
  7081. *
  7082. * fog: <bool>
  7083. * }
  7084. */
  7085. THREE.LineBasicMaterial = function ( parameters ) {
  7086. THREE.Material.call( this );
  7087. this.color = new THREE.Color( 0xffffff );
  7088. this.linewidth = 1;
  7089. this.linecap = 'round';
  7090. this.linejoin = 'round';
  7091. this.vertexColors = false;
  7092. this.fog = true;
  7093. this.setValues( parameters );
  7094. };
  7095. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7096. THREE.LineBasicMaterial.prototype.clone = function () {
  7097. var material = new THREE.LineBasicMaterial();
  7098. THREE.Material.prototype.clone.call( this, material );
  7099. material.color.copy( this.color );
  7100. material.linewidth = this.linewidth;
  7101. material.linecap = this.linecap;
  7102. material.linejoin = this.linejoin;
  7103. material.vertexColors = this.vertexColors;
  7104. material.fog = this.fog;
  7105. return material;
  7106. };
  7107. /**
  7108. * @author alteredq / http://alteredqualia.com/
  7109. *
  7110. * parameters = {
  7111. * color: <hex>,
  7112. * opacity: <float>,
  7113. *
  7114. * blending: THREE.NormalBlending,
  7115. * depthTest: <bool>,
  7116. * depthWrite: <bool>,
  7117. *
  7118. * linewidth: <float>,
  7119. *
  7120. * scale: <float>,
  7121. * dashSize: <float>,
  7122. * gapSize: <float>,
  7123. *
  7124. * vertexColors: <bool>
  7125. *
  7126. * fog: <bool>
  7127. * }
  7128. */
  7129. THREE.LineDashedMaterial = function ( parameters ) {
  7130. THREE.Material.call( this );
  7131. this.color = new THREE.Color( 0xffffff );
  7132. this.linewidth = 1;
  7133. this.scale = 1;
  7134. this.dashSize = 3;
  7135. this.gapSize = 1;
  7136. this.vertexColors = false;
  7137. this.fog = true;
  7138. this.setValues( parameters );
  7139. };
  7140. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7141. THREE.LineDashedMaterial.prototype.clone = function () {
  7142. var material = new THREE.LineDashedMaterial();
  7143. THREE.Material.prototype.clone.call( this, material );
  7144. material.color.copy( this.color );
  7145. material.linewidth = this.linewidth;
  7146. material.scale = this.scale;
  7147. material.dashSize = this.dashSize;
  7148. material.gapSize = this.gapSize;
  7149. material.vertexColors = this.vertexColors;
  7150. material.fog = this.fog;
  7151. return material;
  7152. };
  7153. /**
  7154. * @author mrdoob / http://mrdoob.com/
  7155. * @author alteredq / http://alteredqualia.com/
  7156. *
  7157. * parameters = {
  7158. * color: <hex>,
  7159. * opacity: <float>,
  7160. * map: new THREE.Texture( <Image> ),
  7161. *
  7162. * lightMap: new THREE.Texture( <Image> ),
  7163. *
  7164. * specularMap: new THREE.Texture( <Image> ),
  7165. *
  7166. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7167. * combine: THREE.Multiply,
  7168. * reflectivity: <float>,
  7169. * refractionRatio: <float>,
  7170. *
  7171. * shading: THREE.SmoothShading,
  7172. * blending: THREE.NormalBlending,
  7173. * depthTest: <bool>,
  7174. * depthWrite: <bool>,
  7175. *
  7176. * wireframe: <boolean>,
  7177. * wireframeLinewidth: <float>,
  7178. *
  7179. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7180. *
  7181. * skinning: <bool>,
  7182. * morphTargets: <bool>,
  7183. *
  7184. * fog: <bool>
  7185. * }
  7186. */
  7187. THREE.MeshBasicMaterial = function ( parameters ) {
  7188. THREE.Material.call( this );
  7189. this.color = new THREE.Color( 0xffffff ); // emissive
  7190. this.map = null;
  7191. this.lightMap = null;
  7192. this.specularMap = null;
  7193. this.envMap = null;
  7194. this.combine = THREE.MultiplyOperation;
  7195. this.reflectivity = 1;
  7196. this.refractionRatio = 0.98;
  7197. this.fog = true;
  7198. this.shading = THREE.SmoothShading;
  7199. this.wireframe = false;
  7200. this.wireframeLinewidth = 1;
  7201. this.wireframeLinecap = 'round';
  7202. this.wireframeLinejoin = 'round';
  7203. this.vertexColors = THREE.NoColors;
  7204. this.skinning = false;
  7205. this.morphTargets = false;
  7206. this.setValues( parameters );
  7207. };
  7208. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7209. THREE.MeshBasicMaterial.prototype.clone = function () {
  7210. var material = new THREE.MeshBasicMaterial();
  7211. THREE.Material.prototype.clone.call( this, material );
  7212. material.color.copy( this.color );
  7213. material.map = this.map;
  7214. material.lightMap = this.lightMap;
  7215. material.specularMap = this.specularMap;
  7216. material.envMap = this.envMap;
  7217. material.combine = this.combine;
  7218. material.reflectivity = this.reflectivity;
  7219. material.refractionRatio = this.refractionRatio;
  7220. material.fog = this.fog;
  7221. material.shading = this.shading;
  7222. material.wireframe = this.wireframe;
  7223. material.wireframeLinewidth = this.wireframeLinewidth;
  7224. material.wireframeLinecap = this.wireframeLinecap;
  7225. material.wireframeLinejoin = this.wireframeLinejoin;
  7226. material.vertexColors = this.vertexColors;
  7227. material.skinning = this.skinning;
  7228. material.morphTargets = this.morphTargets;
  7229. return material;
  7230. };
  7231. /**
  7232. * @author mrdoob / http://mrdoob.com/
  7233. * @author alteredq / http://alteredqualia.com/
  7234. *
  7235. * parameters = {
  7236. * color: <hex>,
  7237. * ambient: <hex>,
  7238. * emissive: <hex>,
  7239. * opacity: <float>,
  7240. *
  7241. * map: new THREE.Texture( <Image> ),
  7242. *
  7243. * lightMap: new THREE.Texture( <Image> ),
  7244. *
  7245. * specularMap: new THREE.Texture( <Image> ),
  7246. *
  7247. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7248. * combine: THREE.Multiply,
  7249. * reflectivity: <float>,
  7250. * refractionRatio: <float>,
  7251. *
  7252. * shading: THREE.SmoothShading,
  7253. * blending: THREE.NormalBlending,
  7254. * depthTest: <bool>,
  7255. * depthWrite: <bool>,
  7256. *
  7257. * wireframe: <boolean>,
  7258. * wireframeLinewidth: <float>,
  7259. *
  7260. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7261. *
  7262. * skinning: <bool>,
  7263. * morphTargets: <bool>,
  7264. * morphNormals: <bool>,
  7265. *
  7266. * fog: <bool>
  7267. * }
  7268. */
  7269. THREE.MeshLambertMaterial = function ( parameters ) {
  7270. THREE.Material.call( this );
  7271. this.color = new THREE.Color( 0xffffff ); // diffuse
  7272. this.ambient = new THREE.Color( 0xffffff );
  7273. this.emissive = new THREE.Color( 0x000000 );
  7274. this.wrapAround = false;
  7275. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7276. this.map = null;
  7277. this.lightMap = null;
  7278. this.specularMap = null;
  7279. this.envMap = null;
  7280. this.combine = THREE.MultiplyOperation;
  7281. this.reflectivity = 1;
  7282. this.refractionRatio = 0.98;
  7283. this.fog = true;
  7284. this.shading = THREE.SmoothShading;
  7285. this.wireframe = false;
  7286. this.wireframeLinewidth = 1;
  7287. this.wireframeLinecap = 'round';
  7288. this.wireframeLinejoin = 'round';
  7289. this.vertexColors = THREE.NoColors;
  7290. this.skinning = false;
  7291. this.morphTargets = false;
  7292. this.morphNormals = false;
  7293. this.setValues( parameters );
  7294. };
  7295. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7296. THREE.MeshLambertMaterial.prototype.clone = function () {
  7297. var material = new THREE.MeshLambertMaterial();
  7298. THREE.Material.prototype.clone.call( this, material );
  7299. material.color.copy( this.color );
  7300. material.ambient.copy( this.ambient );
  7301. material.emissive.copy( this.emissive );
  7302. material.wrapAround = this.wrapAround;
  7303. material.wrapRGB.copy( this.wrapRGB );
  7304. material.map = this.map;
  7305. material.lightMap = this.lightMap;
  7306. material.specularMap = this.specularMap;
  7307. material.envMap = this.envMap;
  7308. material.combine = this.combine;
  7309. material.reflectivity = this.reflectivity;
  7310. material.refractionRatio = this.refractionRatio;
  7311. material.fog = this.fog;
  7312. material.shading = this.shading;
  7313. material.wireframe = this.wireframe;
  7314. material.wireframeLinewidth = this.wireframeLinewidth;
  7315. material.wireframeLinecap = this.wireframeLinecap;
  7316. material.wireframeLinejoin = this.wireframeLinejoin;
  7317. material.vertexColors = this.vertexColors;
  7318. material.skinning = this.skinning;
  7319. material.morphTargets = this.morphTargets;
  7320. material.morphNormals = this.morphNormals;
  7321. return material;
  7322. };
  7323. /**
  7324. * @author mrdoob / http://mrdoob.com/
  7325. * @author alteredq / http://alteredqualia.com/
  7326. *
  7327. * parameters = {
  7328. * color: <hex>,
  7329. * ambient: <hex>,
  7330. * emissive: <hex>,
  7331. * specular: <hex>,
  7332. * shininess: <float>,
  7333. * opacity: <float>,
  7334. *
  7335. * map: new THREE.Texture( <Image> ),
  7336. *
  7337. * lightMap: new THREE.Texture( <Image> ),
  7338. *
  7339. * bumpMap: new THREE.Texture( <Image> ),
  7340. * bumpScale: <float>,
  7341. *
  7342. * normalMap: new THREE.Texture( <Image> ),
  7343. * normalScale: <Vector2>,
  7344. *
  7345. * specularMap: new THREE.Texture( <Image> ),
  7346. *
  7347. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7348. * combine: THREE.Multiply,
  7349. * reflectivity: <float>,
  7350. * refractionRatio: <float>,
  7351. *
  7352. * shading: THREE.SmoothShading,
  7353. * blending: THREE.NormalBlending,
  7354. * depthTest: <bool>,
  7355. * depthWrite: <bool>,
  7356. *
  7357. * wireframe: <boolean>,
  7358. * wireframeLinewidth: <float>,
  7359. *
  7360. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7361. *
  7362. * skinning: <bool>,
  7363. * morphTargets: <bool>,
  7364. * morphNormals: <bool>,
  7365. *
  7366. * fog: <bool>
  7367. * }
  7368. */
  7369. THREE.MeshPhongMaterial = function ( parameters ) {
  7370. THREE.Material.call( this );
  7371. this.color = new THREE.Color( 0xffffff ); // diffuse
  7372. this.ambient = new THREE.Color( 0xffffff );
  7373. this.emissive = new THREE.Color( 0x000000 );
  7374. this.specular = new THREE.Color( 0x111111 );
  7375. this.shininess = 30;
  7376. this.metal = false;
  7377. this.perPixel = true;
  7378. this.wrapAround = false;
  7379. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7380. this.map = null;
  7381. this.lightMap = null;
  7382. this.bumpMap = null;
  7383. this.bumpScale = 1;
  7384. this.normalMap = null;
  7385. this.normalScale = new THREE.Vector2( 1, 1 );
  7386. this.specularMap = null;
  7387. this.envMap = null;
  7388. this.combine = THREE.MultiplyOperation;
  7389. this.reflectivity = 1;
  7390. this.refractionRatio = 0.98;
  7391. this.fog = true;
  7392. this.shading = THREE.SmoothShading;
  7393. this.wireframe = false;
  7394. this.wireframeLinewidth = 1;
  7395. this.wireframeLinecap = 'round';
  7396. this.wireframeLinejoin = 'round';
  7397. this.vertexColors = THREE.NoColors;
  7398. this.skinning = false;
  7399. this.morphTargets = false;
  7400. this.morphNormals = false;
  7401. this.setValues( parameters );
  7402. };
  7403. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7404. THREE.MeshPhongMaterial.prototype.clone = function () {
  7405. var material = new THREE.MeshPhongMaterial();
  7406. THREE.Material.prototype.clone.call( this, material );
  7407. material.color.copy( this.color );
  7408. material.ambient.copy( this.ambient );
  7409. material.emissive.copy( this.emissive );
  7410. material.specular.copy( this.specular );
  7411. material.shininess = this.shininess;
  7412. material.metal = this.metal;
  7413. material.perPixel = this.perPixel;
  7414. material.wrapAround = this.wrapAround;
  7415. material.wrapRGB.copy( this.wrapRGB );
  7416. material.map = this.map;
  7417. material.lightMap = this.lightMap;
  7418. material.bumpMap = this.bumpMap;
  7419. material.bumpScale = this.bumpScale;
  7420. material.normalMap = this.normalMap;
  7421. material.normalScale.copy( this.normalScale );
  7422. material.specularMap = this.specularMap;
  7423. material.envMap = this.envMap;
  7424. material.combine = this.combine;
  7425. material.reflectivity = this.reflectivity;
  7426. material.refractionRatio = this.refractionRatio;
  7427. material.fog = this.fog;
  7428. material.shading = this.shading;
  7429. material.wireframe = this.wireframe;
  7430. material.wireframeLinewidth = this.wireframeLinewidth;
  7431. material.wireframeLinecap = this.wireframeLinecap;
  7432. material.wireframeLinejoin = this.wireframeLinejoin;
  7433. material.vertexColors = this.vertexColors;
  7434. material.skinning = this.skinning;
  7435. material.morphTargets = this.morphTargets;
  7436. material.morphNormals = this.morphNormals;
  7437. return material;
  7438. };
  7439. /**
  7440. * @author mrdoob / http://mrdoob.com/
  7441. * @author alteredq / http://alteredqualia.com/
  7442. *
  7443. * parameters = {
  7444. * opacity: <float>,
  7445. *
  7446. * blending: THREE.NormalBlending,
  7447. * depthTest: <bool>,
  7448. * depthWrite: <bool>,
  7449. *
  7450. * wireframe: <boolean>,
  7451. * wireframeLinewidth: <float>
  7452. * }
  7453. */
  7454. THREE.MeshDepthMaterial = function ( parameters ) {
  7455. THREE.Material.call( this );
  7456. this.wireframe = false;
  7457. this.wireframeLinewidth = 1;
  7458. this.setValues( parameters );
  7459. };
  7460. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7461. THREE.MeshDepthMaterial.prototype.clone = function () {
  7462. var material = new THREE.MeshDepthMaterial();
  7463. THREE.Material.prototype.clone.call( this, material );
  7464. material.wireframe = this.wireframe;
  7465. material.wireframeLinewidth = this.wireframeLinewidth;
  7466. return material;
  7467. };
  7468. /**
  7469. * @author mrdoob / http://mrdoob.com/
  7470. *
  7471. * parameters = {
  7472. * opacity: <float>,
  7473. *
  7474. * shading: THREE.FlatShading,
  7475. * blending: THREE.NormalBlending,
  7476. * depthTest: <bool>,
  7477. * depthWrite: <bool>,
  7478. *
  7479. * wireframe: <boolean>,
  7480. * wireframeLinewidth: <float>
  7481. * }
  7482. */
  7483. THREE.MeshNormalMaterial = function ( parameters ) {
  7484. THREE.Material.call( this, parameters );
  7485. this.shading = THREE.FlatShading;
  7486. this.wireframe = false;
  7487. this.wireframeLinewidth = 1;
  7488. this.morphTargets = false;
  7489. this.setValues( parameters );
  7490. };
  7491. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7492. THREE.MeshNormalMaterial.prototype.clone = function () {
  7493. var material = new THREE.MeshNormalMaterial();
  7494. THREE.Material.prototype.clone.call( this, material );
  7495. material.shading = this.shading;
  7496. material.wireframe = this.wireframe;
  7497. material.wireframeLinewidth = this.wireframeLinewidth;
  7498. return material;
  7499. };
  7500. /**
  7501. * @author mrdoob / http://mrdoob.com/
  7502. */
  7503. THREE.MeshFaceMaterial = function ( materials ) {
  7504. this.materials = materials instanceof Array ? materials : [];
  7505. };
  7506. THREE.MeshFaceMaterial.prototype.clone = function () {
  7507. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7508. };
  7509. /**
  7510. * @author mrdoob / http://mrdoob.com/
  7511. * @author alteredq / http://alteredqualia.com/
  7512. *
  7513. * parameters = {
  7514. * color: <hex>,
  7515. * opacity: <float>,
  7516. * map: new THREE.Texture( <Image> ),
  7517. *
  7518. * size: <float>,
  7519. *
  7520. * blending: THREE.NormalBlending,
  7521. * depthTest: <bool>,
  7522. * depthWrite: <bool>,
  7523. *
  7524. * vertexColors: <bool>,
  7525. *
  7526. * fog: <bool>
  7527. * }
  7528. */
  7529. THREE.ParticleBasicMaterial = function ( parameters ) {
  7530. THREE.Material.call( this );
  7531. this.color = new THREE.Color( 0xffffff );
  7532. this.map = null;
  7533. this.size = 1;
  7534. this.sizeAttenuation = true;
  7535. this.vertexColors = false;
  7536. this.fog = true;
  7537. this.setValues( parameters );
  7538. };
  7539. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7540. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7541. var material = new THREE.ParticleBasicMaterial();
  7542. THREE.Material.prototype.clone.call( this, material );
  7543. material.color.copy( this.color );
  7544. material.map = this.map;
  7545. material.size = this.size;
  7546. material.sizeAttenuation = this.sizeAttenuation;
  7547. material.vertexColors = this.vertexColors;
  7548. material.fog = this.fog;
  7549. return material;
  7550. };
  7551. /**
  7552. * @author mrdoob / http://mrdoob.com/
  7553. *
  7554. * parameters = {
  7555. * color: <hex>,
  7556. * program: <function>,
  7557. * opacity: <float>,
  7558. * blending: THREE.NormalBlending
  7559. * }
  7560. */
  7561. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7562. THREE.Material.call( this );
  7563. this.color = new THREE.Color( 0xffffff );
  7564. this.program = function ( context, color ) {};
  7565. this.setValues( parameters );
  7566. };
  7567. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7568. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7569. var material = new THREE.ParticleCanvasMaterial();
  7570. THREE.Material.prototype.clone.call( this, material );
  7571. material.color.copy( this.color );
  7572. material.program = this.program;
  7573. return material;
  7574. };
  7575. /**
  7576. * @author alteredq / http://alteredqualia.com/
  7577. *
  7578. * parameters = {
  7579. * fragmentShader: <string>,
  7580. * vertexShader: <string>,
  7581. *
  7582. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7583. *
  7584. * defines: { "label" : "value" },
  7585. *
  7586. * shading: THREE.SmoothShading,
  7587. * blending: THREE.NormalBlending,
  7588. * depthTest: <bool>,
  7589. * depthWrite: <bool>,
  7590. *
  7591. * wireframe: <boolean>,
  7592. * wireframeLinewidth: <float>,
  7593. *
  7594. * lights: <bool>,
  7595. *
  7596. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7597. *
  7598. * skinning: <bool>,
  7599. * morphTargets: <bool>,
  7600. * morphNormals: <bool>,
  7601. *
  7602. * fog: <bool>
  7603. * }
  7604. */
  7605. THREE.ShaderMaterial = function ( parameters ) {
  7606. THREE.Material.call( this );
  7607. this.fragmentShader = "void main() {}";
  7608. this.vertexShader = "void main() {}";
  7609. this.uniforms = {};
  7610. this.defines = {};
  7611. this.attributes = null;
  7612. this.shading = THREE.SmoothShading;
  7613. this.linewidth = 1;
  7614. this.wireframe = false;
  7615. this.wireframeLinewidth = 1;
  7616. this.fog = false; // set to use scene fog
  7617. this.lights = false; // set to use scene lights
  7618. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7619. this.skinning = false; // set to use skinning attribute streams
  7620. this.morphTargets = false; // set to use morph targets
  7621. this.morphNormals = false; // set to use morph normals
  7622. this.setValues( parameters );
  7623. };
  7624. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7625. THREE.ShaderMaterial.prototype.clone = function () {
  7626. var material = new THREE.ShaderMaterial();
  7627. THREE.Material.prototype.clone.call( this, material );
  7628. material.fragmentShader = this.fragmentShader;
  7629. material.vertexShader = this.vertexShader;
  7630. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7631. material.attributes = this.attributes;
  7632. material.defines = this.defines;
  7633. material.shading = this.shading;
  7634. material.wireframe = this.wireframe;
  7635. material.wireframeLinewidth = this.wireframeLinewidth;
  7636. material.fog = this.fog;
  7637. material.lights = this.lights;
  7638. material.vertexColors = this.vertexColors;
  7639. material.skinning = this.skinning;
  7640. material.morphTargets = this.morphTargets;
  7641. material.morphNormals = this.morphNormals;
  7642. return material;
  7643. };
  7644. /**
  7645. * @author alteredq / http://alteredqualia.com/
  7646. *
  7647. * parameters = {
  7648. * color: <hex>,
  7649. * opacity: <float>,
  7650. * map: new THREE.Texture( <Image> ),
  7651. *
  7652. * blending: THREE.NormalBlending,
  7653. * depthTest: <bool>,
  7654. * depthWrite: <bool>,
  7655. *
  7656. * useScreenCoordinates: <bool>,
  7657. * sizeAttenuation: <bool>,
  7658. * scaleByViewport: <bool>,
  7659. * alignment: THREE.SpriteAlignment.center,
  7660. *
  7661. * uvOffset: new THREE.Vector2(),
  7662. * uvScale: new THREE.Vector2(),
  7663. *
  7664. * fog: <bool>
  7665. * }
  7666. */
  7667. THREE.SpriteMaterial = function ( parameters ) {
  7668. THREE.Material.call( this );
  7669. // defaults
  7670. this.color = new THREE.Color( 0xffffff );
  7671. this.map = new THREE.Texture();
  7672. this.useScreenCoordinates = true;
  7673. this.depthTest = !this.useScreenCoordinates;
  7674. this.sizeAttenuation = !this.useScreenCoordinates;
  7675. this.scaleByViewport = !this.sizeAttenuation;
  7676. this.alignment = THREE.SpriteAlignment.center.clone();
  7677. this.fog = false;
  7678. this.uvOffset = new THREE.Vector2( 0, 0 );
  7679. this.uvScale = new THREE.Vector2( 1, 1 );
  7680. // set parameters
  7681. this.setValues( parameters );
  7682. // override coupled defaults if not specified explicitly by parameters
  7683. parameters = parameters || {};
  7684. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7685. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7686. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7687. };
  7688. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7689. THREE.SpriteMaterial.prototype.clone = function () {
  7690. var material = new THREE.SpriteMaterial();
  7691. THREE.Material.prototype.clone.call( this, material );
  7692. material.color.copy( this.color );
  7693. material.map = this.map;
  7694. material.useScreenCoordinates = this.useScreenCoordinates;
  7695. material.sizeAttenuation = this.sizeAttenuation;
  7696. material.scaleByViewport = this.scaleByViewport;
  7697. material.alignment.copy( this.alignment );
  7698. material.uvOffset.copy( this.uvOffset );
  7699. material.uvScale.copy( this.uvScale );
  7700. material.fog = this.fog;
  7701. return material;
  7702. };
  7703. // Alignment enums
  7704. THREE.SpriteAlignment = {};
  7705. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7706. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7707. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7708. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7709. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7710. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7711. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7712. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7713. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7714. /**
  7715. * @author mrdoob / http://mrdoob.com/
  7716. * @author alteredq / http://alteredqualia.com/
  7717. * @author szimek / https://github.com/szimek/
  7718. */
  7719. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7720. this.id = THREE.Math.generateUUID();
  7721. this.name = '';
  7722. this.image = image;
  7723. this.mipmaps = [];
  7724. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7725. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7726. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7727. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7728. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7729. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7730. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7731. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7732. this.offset = new THREE.Vector2( 0, 0 );
  7733. this.repeat = new THREE.Vector2( 1, 1 );
  7734. this.generateMipmaps = true;
  7735. this.premultiplyAlpha = false;
  7736. this.flipY = true;
  7737. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7738. this.needsUpdate = false;
  7739. this.onUpdate = null;
  7740. };
  7741. THREE.Texture.prototype = {
  7742. constructor: THREE.Texture,
  7743. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  7744. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  7745. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  7746. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  7747. clone: function ( texture ) {
  7748. if ( texture === undefined ) texture = new THREE.Texture();
  7749. texture.image = this.image;
  7750. texture.mipmaps = this.mipmaps.slice(0);
  7751. texture.mapping = this.mapping;
  7752. texture.wrapS = this.wrapS;
  7753. texture.wrapT = this.wrapT;
  7754. texture.magFilter = this.magFilter;
  7755. texture.minFilter = this.minFilter;
  7756. texture.anisotropy = this.anisotropy;
  7757. texture.format = this.format;
  7758. texture.type = this.type;
  7759. texture.offset.copy( this.offset );
  7760. texture.repeat.copy( this.repeat );
  7761. texture.generateMipmaps = this.generateMipmaps;
  7762. texture.premultiplyAlpha = this.premultiplyAlpha;
  7763. texture.flipY = this.flipY;
  7764. texture.unpackAlignment = this.unpackAlignment;
  7765. return texture;
  7766. },
  7767. dispose: function () {
  7768. this.dispatchEvent( { type: 'dispose' } );
  7769. }
  7770. };
  7771. /**
  7772. * @author alteredq / http://alteredqualia.com/
  7773. */
  7774. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7775. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7776. this.image = { width: width, height: height };
  7777. this.mipmaps = mipmaps;
  7778. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7779. };
  7780. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7781. THREE.CompressedTexture.prototype.clone = function () {
  7782. var texture = new THREE.CompressedTexture();
  7783. THREE.Texture.prototype.clone.call( this, texture );
  7784. return texture;
  7785. };
  7786. /**
  7787. * @author alteredq / http://alteredqualia.com/
  7788. */
  7789. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7790. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7791. this.image = { data: data, width: width, height: height };
  7792. };
  7793. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7794. THREE.DataTexture.prototype.clone = function () {
  7795. var texture = new THREE.DataTexture();
  7796. THREE.Texture.prototype.clone.call( this, texture );
  7797. return texture;
  7798. };
  7799. /**
  7800. * @author mrdoob / http://mrdoob.com/
  7801. */
  7802. THREE.Particle = function ( material ) {
  7803. THREE.Object3D.call( this );
  7804. this.material = material;
  7805. };
  7806. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7807. THREE.Particle.prototype.clone = function ( object ) {
  7808. if ( object === undefined ) object = new THREE.Particle( this.material );
  7809. THREE.Object3D.prototype.clone.call( this, object );
  7810. return object;
  7811. };
  7812. /**
  7813. * @author alteredq / http://alteredqualia.com/
  7814. */
  7815. THREE.ParticleSystem = function ( geometry, material ) {
  7816. THREE.Object3D.call( this );
  7817. this.geometry = geometry;
  7818. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7819. this.sortParticles = false;
  7820. if ( this.geometry ) {
  7821. // calc bound radius
  7822. if( this.geometry.boundingSphere === null ) {
  7823. this.geometry.computeBoundingSphere();
  7824. }
  7825. }
  7826. this.frustumCulled = false;
  7827. };
  7828. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7829. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7830. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7831. object.sortParticles = this.sortParticles;
  7832. THREE.Object3D.prototype.clone.call( this, object );
  7833. return object;
  7834. };
  7835. /**
  7836. * @author mrdoob / http://mrdoob.com/
  7837. */
  7838. THREE.Line = function ( geometry, material, type ) {
  7839. THREE.Object3D.call( this );
  7840. this.geometry = geometry;
  7841. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7842. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7843. if ( this.geometry ) {
  7844. if ( ! this.geometry.boundingSphere ) {
  7845. this.geometry.computeBoundingSphere();
  7846. }
  7847. }
  7848. };
  7849. THREE.LineStrip = 0;
  7850. THREE.LinePieces = 1;
  7851. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7852. THREE.Line.prototype.clone = function ( object ) {
  7853. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7854. THREE.Object3D.prototype.clone.call( this, object );
  7855. return object;
  7856. };
  7857. /**
  7858. * @author mrdoob / http://mrdoob.com/
  7859. * @author alteredq / http://alteredqualia.com/
  7860. * @author mikael emtinger / http://gomo.se/
  7861. * @author jonobr1 / http://jonobr1.com/
  7862. */
  7863. THREE.Mesh = function ( geometry, material ) {
  7864. THREE.Object3D.call( this );
  7865. this.geometry = null;
  7866. this.material = null;
  7867. this.setGeometry( geometry );
  7868. this.setMaterial( material );
  7869. };
  7870. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7871. THREE.Mesh.prototype.setGeometry = function ( geometry ) {
  7872. if ( geometry !== undefined ) {
  7873. this.geometry = geometry;
  7874. if ( this.geometry.boundingSphere === null ) {
  7875. this.geometry.computeBoundingSphere();
  7876. }
  7877. this.updateMorphTargets();
  7878. }
  7879. };
  7880. THREE.Mesh.prototype.setMaterial = function ( material ) {
  7881. if ( material !== undefined ) {
  7882. this.material = material;
  7883. } else {
  7884. this.material = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7885. }
  7886. };
  7887. THREE.Mesh.prototype.updateMorphTargets = function () {
  7888. if ( this.geometry.morphTargets.length > 0 ) {
  7889. this.morphTargetBase = -1;
  7890. this.morphTargetForcedOrder = [];
  7891. this.morphTargetInfluences = [];
  7892. this.morphTargetDictionary = {};
  7893. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  7894. this.morphTargetInfluences.push( 0 );
  7895. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7896. }
  7897. }
  7898. };
  7899. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7900. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7901. return this.morphTargetDictionary[ name ];
  7902. }
  7903. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7904. return 0;
  7905. };
  7906. THREE.Mesh.prototype.clone = function ( object ) {
  7907. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7908. THREE.Object3D.prototype.clone.call( this, object );
  7909. return object;
  7910. };
  7911. /**
  7912. * @author mikael emtinger / http://gomo.se/
  7913. * @author alteredq / http://alteredqualia.com/
  7914. */
  7915. THREE.Bone = function( belongsToSkin ) {
  7916. THREE.Object3D.call( this );
  7917. this.skin = belongsToSkin;
  7918. this.skinMatrix = new THREE.Matrix4();
  7919. };
  7920. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7921. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  7922. // update local
  7923. if ( this.matrixAutoUpdate ) {
  7924. forceUpdate |= this.updateMatrix();
  7925. }
  7926. // update skin matrix
  7927. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7928. if( parentSkinMatrix ) {
  7929. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  7930. } else {
  7931. this.skinMatrix.copy( this.matrix );
  7932. }
  7933. this.matrixWorldNeedsUpdate = false;
  7934. forceUpdate = true;
  7935. }
  7936. // update children
  7937. var child, i, l = this.children.length;
  7938. for ( i = 0; i < l; i ++ ) {
  7939. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7940. }
  7941. };
  7942. /**
  7943. * @author mikael emtinger / http://gomo.se/
  7944. * @author alteredq / http://alteredqualia.com/
  7945. */
  7946. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7947. THREE.Mesh.call( this, geometry, material );
  7948. //
  7949. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7950. // init bones
  7951. this.identityMatrix = new THREE.Matrix4();
  7952. this.bones = [];
  7953. this.boneMatrices = [];
  7954. var b, bone, gbone, p, q, s;
  7955. if ( this.geometry && this.geometry.bones !== undefined ) {
  7956. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7957. gbone = this.geometry.bones[ b ];
  7958. p = gbone.pos;
  7959. q = gbone.rotq;
  7960. s = gbone.scl;
  7961. bone = this.addBone();
  7962. bone.name = gbone.name;
  7963. bone.position.set( p[0], p[1], p[2] );
  7964. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7965. bone.useQuaternion = true;
  7966. if ( s !== undefined ) {
  7967. bone.scale.set( s[0], s[1], s[2] );
  7968. } else {
  7969. bone.scale.set( 1, 1, 1 );
  7970. }
  7971. }
  7972. for ( b = 0; b < this.bones.length; b ++ ) {
  7973. gbone = this.geometry.bones[ b ];
  7974. bone = this.bones[ b ];
  7975. if ( gbone.parent === -1 ) {
  7976. this.add( bone );
  7977. } else {
  7978. this.bones[ gbone.parent ].add( bone );
  7979. }
  7980. }
  7981. //
  7982. var nBones = this.bones.length;
  7983. if ( this.useVertexTexture ) {
  7984. // layout (1 matrix = 4 pixels)
  7985. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7986. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7987. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7988. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7989. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7990. var size;
  7991. if ( nBones > 256 )
  7992. size = 64;
  7993. else if ( nBones > 64 )
  7994. size = 32;
  7995. else if ( nBones > 16 )
  7996. size = 16;
  7997. else
  7998. size = 8;
  7999. this.boneTextureWidth = size;
  8000. this.boneTextureHeight = size;
  8001. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8002. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8003. this.boneTexture.minFilter = THREE.NearestFilter;
  8004. this.boneTexture.magFilter = THREE.NearestFilter;
  8005. this.boneTexture.generateMipmaps = false;
  8006. this.boneTexture.flipY = false;
  8007. } else {
  8008. this.boneMatrices = new Float32Array( 16 * nBones );
  8009. }
  8010. this.pose();
  8011. }
  8012. };
  8013. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8014. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  8015. if ( bone === undefined ) {
  8016. bone = new THREE.Bone( this );
  8017. }
  8018. this.bones.push( bone );
  8019. return bone;
  8020. };
  8021. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  8022. this.matrixAutoUpdate && this.updateMatrix();
  8023. // update matrixWorld
  8024. if ( this.matrixWorldNeedsUpdate || force ) {
  8025. if ( this.parent ) {
  8026. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8027. } else {
  8028. this.matrixWorld.copy( this.matrix );
  8029. }
  8030. this.matrixWorldNeedsUpdate = false;
  8031. force = true;
  8032. }
  8033. // update children
  8034. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8035. var child = this.children[ i ];
  8036. if ( child instanceof THREE.Bone ) {
  8037. child.update( this.identityMatrix, false );
  8038. } else {
  8039. child.updateMatrixWorld( true );
  8040. }
  8041. }
  8042. // make a snapshot of the bones' rest position
  8043. if ( this.boneInverses == undefined ) {
  8044. this.boneInverses = [];
  8045. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8046. var inverse = new THREE.Matrix4();
  8047. inverse.getInverse( this.bones[ b ].skinMatrix );
  8048. this.boneInverses.push( inverse );
  8049. }
  8050. }
  8051. // flatten bone matrices to array
  8052. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8053. // compute the offset between the current and the original transform;
  8054. //TODO: we could get rid of this multiplication step if the skinMatrix
  8055. // was already representing the offset; however, this requires some
  8056. // major changes to the animation system
  8057. THREE.SkinnedMesh.offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  8058. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  8059. }
  8060. if ( this.useVertexTexture ) {
  8061. this.boneTexture.needsUpdate = true;
  8062. }
  8063. };
  8064. THREE.SkinnedMesh.prototype.pose = function () {
  8065. this.updateMatrixWorld( true );
  8066. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8067. // normalize weights
  8068. var sw = this.geometry.skinWeights[ i ];
  8069. var scale = 1.0 / sw.lengthManhattan();
  8070. if ( scale !== Infinity ) {
  8071. sw.multiplyScalar( scale );
  8072. } else {
  8073. sw.set( 1 ); // this will be normalized by the shader anyway
  8074. }
  8075. }
  8076. };
  8077. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8078. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8079. THREE.Mesh.prototype.clone.call( this, object );
  8080. return object;
  8081. };
  8082. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  8083. /**
  8084. * @author alteredq / http://alteredqualia.com/
  8085. */
  8086. THREE.MorphAnimMesh = function ( geometry, material ) {
  8087. THREE.Mesh.call( this, geometry, material );
  8088. // API
  8089. this.duration = 1000; // milliseconds
  8090. this.mirroredLoop = false;
  8091. this.time = 0;
  8092. // internals
  8093. this.lastKeyframe = 0;
  8094. this.currentKeyframe = 0;
  8095. this.direction = 1;
  8096. this.directionBackwards = false;
  8097. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8098. };
  8099. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8100. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8101. this.startKeyframe = start;
  8102. this.endKeyframe = end;
  8103. this.length = this.endKeyframe - this.startKeyframe + 1;
  8104. };
  8105. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8106. this.direction = 1;
  8107. this.directionBackwards = false;
  8108. };
  8109. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8110. this.direction = -1;
  8111. this.directionBackwards = true;
  8112. };
  8113. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8114. var geometry = this.geometry;
  8115. if ( ! geometry.animations ) geometry.animations = {};
  8116. var firstAnimation, animations = geometry.animations;
  8117. var pattern = /([a-z]+)(\d+)/;
  8118. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8119. var morph = geometry.morphTargets[ i ];
  8120. var parts = morph.name.match( pattern );
  8121. if ( parts && parts.length > 1 ) {
  8122. var label = parts[ 1 ];
  8123. var num = parts[ 2 ];
  8124. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8125. var animation = animations[ label ];
  8126. if ( i < animation.start ) animation.start = i;
  8127. if ( i > animation.end ) animation.end = i;
  8128. if ( ! firstAnimation ) firstAnimation = label;
  8129. }
  8130. }
  8131. geometry.firstAnimation = firstAnimation;
  8132. };
  8133. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8134. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8135. this.geometry.animations[ label ] = { start: start, end: end };
  8136. };
  8137. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8138. var animation = this.geometry.animations[ label ];
  8139. if ( animation ) {
  8140. this.setFrameRange( animation.start, animation.end );
  8141. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8142. this.time = 0;
  8143. } else {
  8144. console.warn( "animation[" + label + "] undefined" );
  8145. }
  8146. };
  8147. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8148. var frameTime = this.duration / this.length;
  8149. this.time += this.direction * delta;
  8150. if ( this.mirroredLoop ) {
  8151. if ( this.time > this.duration || this.time < 0 ) {
  8152. this.direction *= -1;
  8153. if ( this.time > this.duration ) {
  8154. this.time = this.duration;
  8155. this.directionBackwards = true;
  8156. }
  8157. if ( this.time < 0 ) {
  8158. this.time = 0;
  8159. this.directionBackwards = false;
  8160. }
  8161. }
  8162. } else {
  8163. this.time = this.time % this.duration;
  8164. if ( this.time < 0 ) this.time += this.duration;
  8165. }
  8166. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8167. if ( keyframe !== this.currentKeyframe ) {
  8168. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8169. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8170. this.morphTargetInfluences[ keyframe ] = 0;
  8171. this.lastKeyframe = this.currentKeyframe;
  8172. this.currentKeyframe = keyframe;
  8173. }
  8174. var mix = ( this.time % frameTime ) / frameTime;
  8175. if ( this.directionBackwards ) {
  8176. mix = 1 - mix;
  8177. }
  8178. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8179. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8180. };
  8181. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8182. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8183. object.duration = this.duration;
  8184. object.mirroredLoop = this.mirroredLoop;
  8185. object.time = this.time;
  8186. object.lastKeyframe = this.lastKeyframe;
  8187. object.currentKeyframe = this.currentKeyframe;
  8188. object.direction = this.direction;
  8189. object.directionBackwards = this.directionBackwards;
  8190. THREE.Mesh.prototype.clone.call( this, object );
  8191. return object;
  8192. };
  8193. /**
  8194. * @author alteredq / http://alteredqualia.com/
  8195. */
  8196. THREE.Ribbon = function ( geometry, material ) {
  8197. THREE.Object3D.call( this );
  8198. this.geometry = geometry;
  8199. this.material = material;
  8200. };
  8201. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  8202. THREE.Ribbon.prototype.clone = function ( object ) {
  8203. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  8204. THREE.Object3D.prototype.clone.call( this, object );
  8205. return object;
  8206. };
  8207. /**
  8208. * @author mikael emtinger / http://gomo.se/
  8209. * @author alteredq / http://alteredqualia.com/
  8210. * @author mrdoob / http://mrdoob.com/
  8211. */
  8212. THREE.LOD = function () {
  8213. THREE.Object3D.call( this );
  8214. this.objects = [];
  8215. };
  8216. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8217. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8218. if ( distance === undefined ) distance = 0;
  8219. distance = Math.abs( distance );
  8220. for ( var l = 0; l < this.objects.length; l ++ ) {
  8221. if ( distance < this.objects[ l ].distance ) {
  8222. break;
  8223. }
  8224. }
  8225. this.objects.splice( l, 0, { distance: distance, object: object } );
  8226. this.add( object );
  8227. };
  8228. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8229. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8230. if ( distance < this.objects[ i ].distance ) {
  8231. break;
  8232. }
  8233. }
  8234. return this.objects[ i - 1 ].object;
  8235. };
  8236. THREE.LOD.prototype.update = function () {
  8237. var v1 = new THREE.Vector3();
  8238. var v2 = new THREE.Vector3();
  8239. return function ( camera ) {
  8240. if ( this.objects.length > 1 ) {
  8241. v1.getPositionFromMatrix( camera.matrixWorld );
  8242. v2.getPositionFromMatrix( this.matrixWorld );
  8243. var distance = v1.distanceTo( v2 );
  8244. this.objects[ 0 ].object.visible = true;
  8245. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8246. if ( distance >= this.objects[ i ].distance ) {
  8247. this.objects[ i - 1 ].object.visible = false;
  8248. this.objects[ i ].object.visible = true;
  8249. } else {
  8250. break;
  8251. }
  8252. }
  8253. for( ; i < l; i ++ ) {
  8254. this.objects[ i ].object.visible = false;
  8255. }
  8256. }
  8257. };
  8258. }();
  8259. THREE.LOD.prototype.clone = function () {
  8260. // TODO
  8261. };
  8262. /**
  8263. * @author mikael emtinger / http://gomo.se/
  8264. * @author alteredq / http://alteredqualia.com/
  8265. */
  8266. THREE.Sprite = function ( material ) {
  8267. THREE.Object3D.call( this );
  8268. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8269. this.rotation3d = this.rotation;
  8270. this.rotation = 0;
  8271. };
  8272. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8273. /*
  8274. * Custom update matrix
  8275. */
  8276. THREE.Sprite.prototype.updateMatrix = function () {
  8277. this.rotation3d.set( 0, 0, this.rotation );
  8278. this.quaternion.setFromEuler( this.rotation3d, this.eulerOrder );
  8279. this.matrix.makeFromPositionQuaternionScale( this.position, this.quaternion, this.scale );
  8280. this.matrixWorldNeedsUpdate = true;
  8281. };
  8282. THREE.Sprite.prototype.clone = function ( object ) {
  8283. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8284. THREE.Object3D.prototype.clone.call( this, object );
  8285. return object;
  8286. };
  8287. /**
  8288. * @author mrdoob / http://mrdoob.com/
  8289. */
  8290. THREE.Scene = function () {
  8291. THREE.Object3D.call( this );
  8292. this.fog = null;
  8293. this.overrideMaterial = null;
  8294. this.autoUpdate = true; // checked by the renderer
  8295. this.matrixAutoUpdate = false;
  8296. this.__objects = [];
  8297. this.__lights = [];
  8298. this.__objectsAdded = [];
  8299. this.__objectsRemoved = [];
  8300. };
  8301. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8302. THREE.Scene.prototype.__addObject = function ( object ) {
  8303. if ( object instanceof THREE.Light ) {
  8304. if ( this.__lights.indexOf( object ) === - 1 ) {
  8305. this.__lights.push( object );
  8306. }
  8307. if ( object.target && object.target.parent === undefined ) {
  8308. this.add( object.target );
  8309. }
  8310. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8311. if ( this.__objects.indexOf( object ) === - 1 ) {
  8312. this.__objects.push( object );
  8313. this.__objectsAdded.push( object );
  8314. // check if previously removed
  8315. var i = this.__objectsRemoved.indexOf( object );
  8316. if ( i !== -1 ) {
  8317. this.__objectsRemoved.splice( i, 1 );
  8318. }
  8319. }
  8320. }
  8321. for ( var c = 0; c < object.children.length; c ++ ) {
  8322. this.__addObject( object.children[ c ] );
  8323. }
  8324. };
  8325. THREE.Scene.prototype.__removeObject = function ( object ) {
  8326. if ( object instanceof THREE.Light ) {
  8327. var i = this.__lights.indexOf( object );
  8328. if ( i !== -1 ) {
  8329. this.__lights.splice( i, 1 );
  8330. }
  8331. } else if ( !( object instanceof THREE.Camera ) ) {
  8332. var i = this.__objects.indexOf( object );
  8333. if( i !== -1 ) {
  8334. this.__objects.splice( i, 1 );
  8335. this.__objectsRemoved.push( object );
  8336. // check if previously added
  8337. var ai = this.__objectsAdded.indexOf( object );
  8338. if ( ai !== -1 ) {
  8339. this.__objectsAdded.splice( ai, 1 );
  8340. }
  8341. }
  8342. }
  8343. for ( var c = 0; c < object.children.length; c ++ ) {
  8344. this.__removeObject( object.children[ c ] );
  8345. }
  8346. };
  8347. /**
  8348. * @author mrdoob / http://mrdoob.com/
  8349. * @author alteredq / http://alteredqualia.com/
  8350. */
  8351. THREE.Fog = function ( hex, near, far ) {
  8352. this.name = '';
  8353. this.color = new THREE.Color( hex );
  8354. this.near = ( near !== undefined ) ? near : 1;
  8355. this.far = ( far !== undefined ) ? far : 1000;
  8356. };
  8357. THREE.Fog.prototype.clone = function () {
  8358. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  8359. };
  8360. /**
  8361. * @author mrdoob / http://mrdoob.com/
  8362. * @author alteredq / http://alteredqualia.com/
  8363. */
  8364. THREE.FogExp2 = function ( hex, density ) {
  8365. this.name = '';
  8366. this.color = new THREE.Color( hex );
  8367. this.density = ( density !== undefined ) ? density : 0.00025;
  8368. };
  8369. THREE.FogExp2.prototype.clone = function () {
  8370. return new THREE.FogExp2( this.color.getHex(), this.density );
  8371. };
  8372. /**
  8373. * @author mrdoob / http://mrdoob.com/
  8374. */
  8375. THREE.CanvasRenderer = function ( parameters ) {
  8376. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  8377. var smoothstep = THREE.Math.smoothstep;
  8378. parameters = parameters || {};
  8379. var _this = this,
  8380. _renderData, _elements, _lights,
  8381. _projector = new THREE.Projector(),
  8382. _canvas = parameters.canvas !== undefined
  8383. ? parameters.canvas
  8384. : document.createElement( 'canvas' ),
  8385. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  8386. _context = _canvas.getContext( '2d' ),
  8387. _clearColor = new THREE.Color( 0x000000 ),
  8388. _clearAlpha = 0,
  8389. _contextGlobalAlpha = 1,
  8390. _contextGlobalCompositeOperation = 0,
  8391. _contextStrokeStyle = null,
  8392. _contextFillStyle = null,
  8393. _contextLineWidth = null,
  8394. _contextLineCap = null,
  8395. _contextLineJoin = null,
  8396. _contextDashSize = null,
  8397. _contextGapSize = 0,
  8398. _camera,
  8399. _v1, _v2, _v3, _v4,
  8400. _v5 = new THREE.RenderableVertex(),
  8401. _v6 = new THREE.RenderableVertex(),
  8402. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  8403. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  8404. _color = new THREE.Color(),
  8405. _color1 = new THREE.Color(),
  8406. _color2 = new THREE.Color(),
  8407. _color3 = new THREE.Color(),
  8408. _color4 = new THREE.Color(),
  8409. _diffuseColor = new THREE.Color(),
  8410. _emissiveColor = new THREE.Color(),
  8411. _lightColor = new THREE.Color(),
  8412. _patterns = {}, _imagedatas = {},
  8413. _near, _far,
  8414. _image, _uvs,
  8415. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  8416. _clipBox = new THREE.Box2(),
  8417. _clearBox = new THREE.Box2(),
  8418. _elemBox = new THREE.Box2(),
  8419. _ambientLight = new THREE.Color(),
  8420. _directionalLights = new THREE.Color(),
  8421. _pointLights = new THREE.Color(),
  8422. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8423. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8424. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8425. _pixelMap = document.createElement( 'canvas' );
  8426. _pixelMap.width = _pixelMap.height = 2;
  8427. _pixelMapContext = _pixelMap.getContext( '2d' );
  8428. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8429. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8430. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8431. _pixelMapData = _pixelMapImage.data;
  8432. _gradientMap = document.createElement( 'canvas' );
  8433. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8434. _gradientMapContext = _gradientMap.getContext( '2d' );
  8435. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8436. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8437. _gradientMapQuality --; // Fix UVs
  8438. // dash+gap fallbacks for Firefox and everything else
  8439. if ( _context.setLineDash === undefined ) {
  8440. if ( _context.mozDash !== undefined ) {
  8441. _context.setLineDash = function ( values ) {
  8442. _context.mozDash = values[ 0 ] !== null ? values : null;
  8443. }
  8444. } else {
  8445. _context.setLineDash = function () {}
  8446. }
  8447. }
  8448. this.domElement = _canvas;
  8449. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  8450. ? parameters.devicePixelRatio
  8451. : window.devicePixelRatio !== undefined
  8452. ? window.devicePixelRatio
  8453. : 1;
  8454. this.autoClear = true;
  8455. this.sortObjects = true;
  8456. this.sortElements = true;
  8457. this.info = {
  8458. render: {
  8459. vertices: 0,
  8460. faces: 0
  8461. }
  8462. }
  8463. // WebGLRenderer compatibility
  8464. this.supportsVertexTextures = function () {};
  8465. this.setFaceCulling = function () {};
  8466. this.setSize = function ( width, height, updateStyle ) {
  8467. _canvasWidth = width * this.devicePixelRatio;
  8468. _canvasHeight = height * this.devicePixelRatio;
  8469. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8470. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8471. _canvas.width = _canvasWidth;
  8472. _canvas.height = _canvasHeight;
  8473. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  8474. _canvas.style.width = width + 'px';
  8475. _canvas.style.height = height + 'px';
  8476. }
  8477. _clipBox.set(
  8478. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8479. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8480. );
  8481. _clearBox.set(
  8482. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8483. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8484. );
  8485. _contextGlobalAlpha = 1;
  8486. _contextGlobalCompositeOperation = 0;
  8487. _contextStrokeStyle = null;
  8488. _contextFillStyle = null;
  8489. _contextLineWidth = null;
  8490. _contextLineCap = null;
  8491. _contextLineJoin = null;
  8492. };
  8493. this.setClearColor = function ( color, alpha ) {
  8494. _clearColor.set( color );
  8495. _clearAlpha = alpha !== undefined ? alpha : 1;
  8496. _clearBox.set(
  8497. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8498. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8499. );
  8500. };
  8501. this.setClearColorHex = function ( hex, alpha ) {
  8502. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  8503. this.setClearColor( hex, alpha );
  8504. };
  8505. this.getMaxAnisotropy = function () {
  8506. return 0;
  8507. };
  8508. this.clear = function () {
  8509. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8510. if ( _clearBox.empty() === false ) {
  8511. _clearBox.intersect( _clipBox );
  8512. _clearBox.expandByScalar( 2 );
  8513. if ( _clearAlpha < 1 ) {
  8514. _context.clearRect(
  8515. _clearBox.min.x | 0,
  8516. _clearBox.min.y | 0,
  8517. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8518. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8519. );
  8520. }
  8521. if ( _clearAlpha > 0 ) {
  8522. setBlending( THREE.NormalBlending );
  8523. setOpacity( 1 );
  8524. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  8525. _context.fillRect(
  8526. _clearBox.min.x | 0,
  8527. _clearBox.min.y | 0,
  8528. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8529. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8530. );
  8531. }
  8532. _clearBox.makeEmpty();
  8533. }
  8534. };
  8535. this.render = function ( scene, camera ) {
  8536. if ( camera instanceof THREE.Camera === false ) {
  8537. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8538. return;
  8539. }
  8540. if ( this.autoClear === true ) this.clear();
  8541. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8542. _this.info.render.vertices = 0;
  8543. _this.info.render.faces = 0;
  8544. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8545. _elements = _renderData.elements;
  8546. _lights = _renderData.lights;
  8547. _camera = camera;
  8548. /* DEBUG
  8549. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  8550. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8551. */
  8552. calculateLights();
  8553. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  8554. var element = _elements[ e ];
  8555. var material = element.material;
  8556. if ( material === undefined || material.visible === false ) continue;
  8557. _elemBox.makeEmpty();
  8558. if ( element instanceof THREE.RenderableParticle ) {
  8559. _v1 = element;
  8560. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8561. renderParticle( _v1, element, material );
  8562. } else if ( element instanceof THREE.RenderableLine ) {
  8563. _v1 = element.v1; _v2 = element.v2;
  8564. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8565. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8566. _elemBox.setFromPoints( [
  8567. _v1.positionScreen,
  8568. _v2.positionScreen
  8569. ] );
  8570. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8571. renderLine( _v1, _v2, element, material );
  8572. }
  8573. } else if ( element instanceof THREE.RenderableFace3 ) {
  8574. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8575. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8576. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8577. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8578. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8579. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8580. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8581. if ( material.overdraw > 0 ) {
  8582. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  8583. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  8584. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  8585. }
  8586. _elemBox.setFromPoints( [
  8587. _v1.positionScreen,
  8588. _v2.positionScreen,
  8589. _v3.positionScreen
  8590. ] );
  8591. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8592. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  8593. }
  8594. } else if ( element instanceof THREE.RenderableFace4 ) {
  8595. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8596. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8597. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8598. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8599. if ( _v4.positionScreen.z < -1 || _v4.positionScreen.z > 1 ) continue;
  8600. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8601. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8602. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8603. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8604. _v5.positionScreen.copy( _v2.positionScreen );
  8605. _v6.positionScreen.copy( _v4.positionScreen );
  8606. if ( material.overdraw > 0 ) {
  8607. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  8608. expand( _v2.positionScreen, _v4.positionScreen, material.overdraw );
  8609. expand( _v4.positionScreen, _v1.positionScreen, material.overdraw );
  8610. expand( _v3.positionScreen, _v5.positionScreen, material.overdraw );
  8611. expand( _v3.positionScreen, _v6.positionScreen, material.overdraw );
  8612. }
  8613. _elemBox.setFromPoints( [
  8614. _v1.positionScreen,
  8615. _v2.positionScreen,
  8616. _v3.positionScreen,
  8617. _v4.positionScreen
  8618. ] );
  8619. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8620. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material );
  8621. }
  8622. }
  8623. /* DEBUG
  8624. setLineWidth( 1 );
  8625. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  8626. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8627. */
  8628. _clearBox.union( _elemBox );
  8629. }
  8630. /* DEBUG
  8631. setLineWidth( 1 );
  8632. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  8633. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8634. */
  8635. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8636. };
  8637. //
  8638. function calculateLights() {
  8639. _ambientLight.setRGB( 0, 0, 0 );
  8640. _directionalLights.setRGB( 0, 0, 0 );
  8641. _pointLights.setRGB( 0, 0, 0 );
  8642. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8643. var light = _lights[ l ];
  8644. var lightColor = light.color;
  8645. if ( light instanceof THREE.AmbientLight ) {
  8646. _ambientLight.add( lightColor );
  8647. } else if ( light instanceof THREE.DirectionalLight ) {
  8648. // for particles
  8649. _directionalLights.add( lightColor );
  8650. } else if ( light instanceof THREE.PointLight ) {
  8651. // for particles
  8652. _pointLights.add( lightColor );
  8653. }
  8654. }
  8655. }
  8656. function calculateLight( position, normal, color ) {
  8657. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8658. var light = _lights[ l ];
  8659. _lightColor.copy( light.color );
  8660. if ( light instanceof THREE.DirectionalLight ) {
  8661. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  8662. var amount = normal.dot( lightPosition );
  8663. if ( amount <= 0 ) continue;
  8664. amount *= light.intensity;
  8665. color.add( _lightColor.multiplyScalar( amount ) );
  8666. } else if ( light instanceof THREE.PointLight ) {
  8667. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  8668. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  8669. if ( amount <= 0 ) continue;
  8670. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8671. if ( amount == 0 ) continue;
  8672. amount *= light.intensity;
  8673. color.add( _lightColor.multiplyScalar( amount ) );
  8674. }
  8675. }
  8676. }
  8677. function renderParticle( v1, element, material ) {
  8678. setOpacity( material.opacity );
  8679. setBlending( material.blending );
  8680. var width, height, scaleX, scaleY,
  8681. bitmap, bitmapWidth, bitmapHeight;
  8682. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8683. if ( material.map === null ) {
  8684. scaleX = element.object.scale.x;
  8685. scaleY = element.object.scale.y;
  8686. // TODO: Be able to disable this
  8687. scaleX *= element.scale.x * _canvasWidthHalf;
  8688. scaleY *= element.scale.y * _canvasHeightHalf;
  8689. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8690. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8691. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8692. _elemBox.makeEmpty();
  8693. return;
  8694. }
  8695. setFillStyle( material.color.getStyle() );
  8696. _context.save();
  8697. _context.translate( v1.x, v1.y );
  8698. _context.rotate( - element.rotation );
  8699. _context.scale( scaleX, scaleY );
  8700. _context.fillRect( -1, -1, 2, 2 );
  8701. _context.restore();
  8702. } else {
  8703. bitmap = material.map.image;
  8704. bitmapWidth = bitmap.width >> 1;
  8705. bitmapHeight = bitmap.height >> 1;
  8706. scaleX = element.scale.x * _canvasWidthHalf;
  8707. scaleY = element.scale.y * _canvasHeightHalf;
  8708. width = scaleX * bitmapWidth;
  8709. height = scaleY * bitmapHeight;
  8710. // TODO: Rotations break this...
  8711. _elemBox.min.set( v1.x - width, v1.y - height );
  8712. _elemBox.max.set( v1.x + width, v1.y + height );
  8713. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8714. _elemBox.makeEmpty();
  8715. return;
  8716. }
  8717. _context.save();
  8718. _context.translate( v1.x, v1.y );
  8719. _context.rotate( - element.rotation );
  8720. _context.scale( scaleX, - scaleY );
  8721. _context.translate( - bitmapWidth, - bitmapHeight );
  8722. _context.drawImage( bitmap, 0, 0 );
  8723. _context.restore();
  8724. }
  8725. /* DEBUG
  8726. setStrokeStyle( 'rgb(255,255,0)' );
  8727. _context.beginPath();
  8728. _context.moveTo( v1.x - 10, v1.y );
  8729. _context.lineTo( v1.x + 10, v1.y );
  8730. _context.moveTo( v1.x, v1.y - 10 );
  8731. _context.lineTo( v1.x, v1.y + 10 );
  8732. _context.stroke();
  8733. */
  8734. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8735. width = element.scale.x * _canvasWidthHalf;
  8736. height = element.scale.y * _canvasHeightHalf;
  8737. _elemBox.min.set( v1.x - width, v1.y - height );
  8738. _elemBox.max.set( v1.x + width, v1.y + height );
  8739. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8740. _elemBox.makeEmpty();
  8741. return;
  8742. }
  8743. setStrokeStyle( material.color.getStyle() );
  8744. setFillStyle( material.color.getStyle() );
  8745. _context.save();
  8746. _context.translate( v1.x, v1.y );
  8747. _context.rotate( - element.rotation );
  8748. _context.scale( width, height );
  8749. material.program( _context );
  8750. _context.restore();
  8751. }
  8752. }
  8753. function renderLine( v1, v2, element, material ) {
  8754. setOpacity( material.opacity );
  8755. setBlending( material.blending );
  8756. _context.beginPath();
  8757. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8758. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8759. if ( material instanceof THREE.LineBasicMaterial ) {
  8760. setLineWidth( material.linewidth );
  8761. setLineCap( material.linecap );
  8762. setLineJoin( material.linejoin );
  8763. if ( material.vertexColors !== THREE.VertexColors ) {
  8764. setStrokeStyle( material.color.getStyle() );
  8765. } else {
  8766. var colorStyle1 = element.vertexColors[0].getStyle();
  8767. var colorStyle2 = element.vertexColors[1].getStyle();
  8768. if ( colorStyle1 === colorStyle2 ) {
  8769. setStrokeStyle( colorStyle1 );
  8770. } else {
  8771. try {
  8772. var grad = _context.createLinearGradient(
  8773. v1.positionScreen.x,
  8774. v1.positionScreen.y,
  8775. v2.positionScreen.x,
  8776. v2.positionScreen.y
  8777. );
  8778. grad.addColorStop( 0, colorStyle1 );
  8779. grad.addColorStop( 1, colorStyle2 );
  8780. } catch ( exception ) {
  8781. grad = colorStyle1;
  8782. }
  8783. setStrokeStyle( grad );
  8784. }
  8785. }
  8786. _context.stroke();
  8787. _elemBox.expandByScalar( material.linewidth * 2 );
  8788. } else if ( material instanceof THREE.LineDashedMaterial ) {
  8789. setLineWidth( material.linewidth );
  8790. setLineCap( material.linecap );
  8791. setLineJoin( material.linejoin );
  8792. setStrokeStyle( material.color.getStyle() );
  8793. setDashAndGap( material.dashSize, material.gapSize );
  8794. _context.stroke();
  8795. _elemBox.expandByScalar( material.linewidth * 2 );
  8796. setDashAndGap( null, null );
  8797. }
  8798. }
  8799. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  8800. _this.info.render.vertices += 3;
  8801. _this.info.render.faces ++;
  8802. setOpacity( material.opacity );
  8803. setBlending( material.blending );
  8804. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8805. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8806. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8807. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8808. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  8809. _diffuseColor.copy( material.color );
  8810. _emissiveColor.copy( material.emissive );
  8811. if ( material.vertexColors === THREE.FaceColors ) {
  8812. _diffuseColor.multiply( element.color );
  8813. }
  8814. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8815. _color1.copy( _ambientLight );
  8816. _color2.copy( _ambientLight );
  8817. _color3.copy( _ambientLight );
  8818. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8819. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8820. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  8821. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8822. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8823. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8824. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8825. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8826. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8827. } else {
  8828. _color.copy( _ambientLight );
  8829. calculateLight( element.centroidModel, element.normalModel, _color );
  8830. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8831. material.wireframe === true
  8832. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8833. : fillPath( _color );
  8834. }
  8835. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8836. if ( material.map !== null ) {
  8837. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8838. _uvs = element.uvs[ 0 ];
  8839. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].x, _uvs[ uv1 ].y, _uvs[ uv2 ].x, _uvs[ uv2 ].y, _uvs[ uv3 ].x, _uvs[ uv3 ].y, material.map );
  8840. }
  8841. } else if ( material.envMap !== null ) {
  8842. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8843. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  8844. _uv1x = 0.5 * _vector3.x + 0.5;
  8845. _uv1y = 0.5 * _vector3.y + 0.5;
  8846. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  8847. _uv2x = 0.5 * _vector3.x + 0.5;
  8848. _uv2y = 0.5 * _vector3.y + 0.5;
  8849. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  8850. _uv3x = 0.5 * _vector3.x + 0.5;
  8851. _uv3y = 0.5 * _vector3.y + 0.5;
  8852. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8853. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8854. }*/
  8855. } else {
  8856. _color.copy( material.color );
  8857. if ( material.vertexColors === THREE.FaceColors ) {
  8858. _color.multiply( element.color );
  8859. }
  8860. material.wireframe === true
  8861. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8862. : fillPath( _color );
  8863. }
  8864. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8865. _near = _camera.near;
  8866. _far = _camera.far;
  8867. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8868. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8869. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8870. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8871. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8872. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8873. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8874. var normal;
  8875. if ( material.shading == THREE.FlatShading ) {
  8876. normal = element.normalModelView;
  8877. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8878. material.wireframe === true
  8879. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8880. : fillPath( _color );
  8881. } else if ( material.shading == THREE.SmoothShading ) {
  8882. normal = element.vertexNormalsModelView[ uv1 ];
  8883. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8884. normal = element.vertexNormalsModelView[ uv2 ];
  8885. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8886. normal = element.vertexNormalsModelView[ uv3 ];
  8887. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8888. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8889. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8890. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8891. }
  8892. }
  8893. }
  8894. function renderFace4( v1, v2, v3, v4, v5, v6, element, material ) {
  8895. _this.info.render.vertices += 4;
  8896. _this.info.render.faces ++;
  8897. setOpacity( material.opacity );
  8898. setBlending( material.blending );
  8899. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8900. // Let renderFace3() handle this
  8901. renderFace3( v1, v2, v4, 0, 1, 3, element, material );
  8902. renderFace3( v5, v3, v6, 1, 2, 3, element, material );
  8903. return;
  8904. }
  8905. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8906. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8907. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8908. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8909. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8910. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8911. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8912. _diffuseColor.copy( material.color );
  8913. _emissiveColor.copy( material.emissive );
  8914. if ( material.vertexColors === THREE.FaceColors ) {
  8915. _diffuseColor.multiply( element.color );
  8916. }
  8917. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8918. _color1.copy( _ambientLight );
  8919. _color2.copy( _ambientLight );
  8920. _color3.copy( _ambientLight );
  8921. _color4.copy( _ambientLight );
  8922. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8923. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8924. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  8925. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  8926. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8927. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8928. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8929. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  8930. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8931. // TODO: UVs are incorrect, v4->v3?
  8932. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8933. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8934. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8935. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8936. } else {
  8937. _color.copy( _ambientLight );
  8938. calculateLight( element.centroidModel, element.normalModel, _color );
  8939. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8940. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8941. material.wireframe === true
  8942. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8943. : fillPath( _color );
  8944. }
  8945. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8946. _color.copy( material.color );
  8947. if ( material.vertexColors === THREE.FaceColors ) {
  8948. _color.multiply( element.color );
  8949. }
  8950. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8951. material.wireframe === true
  8952. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8953. : fillPath( _color );
  8954. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8955. var normal;
  8956. if ( material.shading == THREE.FlatShading ) {
  8957. normal = element.normalModelView;
  8958. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8959. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8960. material.wireframe === true
  8961. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8962. : fillPath( _color );
  8963. } else if ( material.shading == THREE.SmoothShading ) {
  8964. normal = element.vertexNormalsModelView[ 0 ];
  8965. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8966. normal = element.vertexNormalsModelView[ 1 ];
  8967. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8968. normal = element.vertexNormalsModelView[ 3 ];
  8969. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8970. normal = element.vertexNormalsModelView[ 2 ];
  8971. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8972. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8973. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8974. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8975. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8976. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8977. }
  8978. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8979. _near = _camera.near;
  8980. _far = _camera.far;
  8981. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8982. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8983. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z * v4.positionScreen.w, _near, _far );
  8984. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8985. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8986. // TODO: UVs are incorrect, v4->v3?
  8987. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8988. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8989. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8990. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8991. }
  8992. }
  8993. //
  8994. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8995. _context.beginPath();
  8996. _context.moveTo( x0, y0 );
  8997. _context.lineTo( x1, y1 );
  8998. _context.lineTo( x2, y2 );
  8999. _context.closePath();
  9000. }
  9001. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  9002. _context.beginPath();
  9003. _context.moveTo( x0, y0 );
  9004. _context.lineTo( x1, y1 );
  9005. _context.lineTo( x2, y2 );
  9006. _context.lineTo( x3, y3 );
  9007. _context.closePath();
  9008. }
  9009. function strokePath( color, linewidth, linecap, linejoin ) {
  9010. setLineWidth( linewidth );
  9011. setLineCap( linecap );
  9012. setLineJoin( linejoin );
  9013. setStrokeStyle( color.getStyle() );
  9014. _context.stroke();
  9015. _elemBox.expandByScalar( linewidth * 2 );
  9016. }
  9017. function fillPath( color ) {
  9018. setFillStyle( color.getStyle() );
  9019. _context.fill();
  9020. }
  9021. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9022. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  9023. if ( texture.needsUpdate === true ) {
  9024. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  9025. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  9026. _patterns[ texture.id ] = _context.createPattern(
  9027. texture.image, repeatX === true && repeatY === true
  9028. ? 'repeat'
  9029. : repeatX === true && repeatY === false
  9030. ? 'repeat-x'
  9031. : repeatX === false && repeatY === true
  9032. ? 'repeat-y'
  9033. : 'no-repeat'
  9034. );
  9035. texture.needsUpdate = false;
  9036. }
  9037. _patterns[ texture.id ] === undefined
  9038. ? setFillStyle( 'rgba(0,0,0,1)' )
  9039. : setFillStyle( _patterns[ texture.id ] );
  9040. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9041. var a, b, c, d, e, f, det, idet,
  9042. offsetX = texture.offset.x / texture.repeat.x,
  9043. offsetY = texture.offset.y / texture.repeat.y,
  9044. width = texture.image.width * texture.repeat.x,
  9045. height = texture.image.height * texture.repeat.y;
  9046. u0 = ( u0 + offsetX ) * width;
  9047. v0 = ( 1.0 - v0 + offsetY ) * height;
  9048. u1 = ( u1 + offsetX ) * width;
  9049. v1 = ( 1.0 - v1 + offsetY ) * height;
  9050. u2 = ( u2 + offsetX ) * width;
  9051. v2 = ( 1.0 - v2 + offsetY ) * height;
  9052. x1 -= x0; y1 -= y0;
  9053. x2 -= x0; y2 -= y0;
  9054. u1 -= u0; v1 -= v0;
  9055. u2 -= u0; v2 -= v0;
  9056. det = u1 * v2 - u2 * v1;
  9057. if ( det === 0 ) {
  9058. if ( _imagedatas[ texture.id ] === undefined ) {
  9059. var canvas = document.createElement( 'canvas' )
  9060. canvas.width = texture.image.width;
  9061. canvas.height = texture.image.height;
  9062. var context = canvas.getContext( '2d' );
  9063. context.drawImage( texture.image, 0, 0 );
  9064. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  9065. }
  9066. var data = _imagedatas[ texture.id ];
  9067. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  9068. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  9069. fillPath( _color );
  9070. return;
  9071. }
  9072. idet = 1 / det;
  9073. a = ( v2 * x1 - v1 * x2 ) * idet;
  9074. b = ( v2 * y1 - v1 * y2 ) * idet;
  9075. c = ( u1 * x2 - u2 * x1 ) * idet;
  9076. d = ( u1 * y2 - u2 * y1 ) * idet;
  9077. e = x0 - a * u0 - c * v0;
  9078. f = y0 - b * u0 - d * v0;
  9079. _context.save();
  9080. _context.transform( a, b, c, d, e, f );
  9081. _context.fill();
  9082. _context.restore();
  9083. }
  9084. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9085. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9086. var a, b, c, d, e, f, det, idet,
  9087. width = image.width - 1,
  9088. height = image.height - 1;
  9089. u0 *= width; v0 *= height;
  9090. u1 *= width; v1 *= height;
  9091. u2 *= width; v2 *= height;
  9092. x1 -= x0; y1 -= y0;
  9093. x2 -= x0; y2 -= y0;
  9094. u1 -= u0; v1 -= v0;
  9095. u2 -= u0; v2 -= v0;
  9096. det = u1 * v2 - u2 * v1;
  9097. idet = 1 / det;
  9098. a = ( v2 * x1 - v1 * x2 ) * idet;
  9099. b = ( v2 * y1 - v1 * y2 ) * idet;
  9100. c = ( u1 * x2 - u2 * x1 ) * idet;
  9101. d = ( u1 * y2 - u2 * y1 ) * idet;
  9102. e = x0 - a * u0 - c * v0;
  9103. f = y0 - b * u0 - d * v0;
  9104. _context.save();
  9105. _context.transform( a, b, c, d, e, f );
  9106. _context.clip();
  9107. _context.drawImage( image, 0, 0 );
  9108. _context.restore();
  9109. }
  9110. function getGradientTexture( color1, color2, color3, color4 ) {
  9111. // http://mrdoob.com/blog/post/710
  9112. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9113. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9114. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9115. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9116. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9117. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9118. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9119. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9120. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9121. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9122. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9123. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9124. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9125. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9126. return _gradientMap;
  9127. }
  9128. // Hide anti-alias gaps
  9129. function expand( v1, v2, pixels ) {
  9130. var x = v2.x - v1.x, y = v2.y - v1.y,
  9131. det = x * x + y * y, idet;
  9132. if ( det === 0 ) return;
  9133. idet = pixels / Math.sqrt( det );
  9134. x *= idet; y *= idet;
  9135. v2.x += x; v2.y += y;
  9136. v1.x -= x; v1.y -= y;
  9137. }
  9138. // Context cached methods.
  9139. function setOpacity( value ) {
  9140. if ( _contextGlobalAlpha !== value ) {
  9141. _context.globalAlpha = value;
  9142. _contextGlobalAlpha = value;
  9143. }
  9144. }
  9145. function setBlending( value ) {
  9146. if ( _contextGlobalCompositeOperation !== value ) {
  9147. if ( value === THREE.NormalBlending ) {
  9148. _context.globalCompositeOperation = 'source-over';
  9149. } else if ( value === THREE.AdditiveBlending ) {
  9150. _context.globalCompositeOperation = 'lighter';
  9151. } else if ( value === THREE.SubtractiveBlending ) {
  9152. _context.globalCompositeOperation = 'darker';
  9153. }
  9154. _contextGlobalCompositeOperation = value;
  9155. }
  9156. }
  9157. function setLineWidth( value ) {
  9158. if ( _contextLineWidth !== value ) {
  9159. _context.lineWidth = value;
  9160. _contextLineWidth = value;
  9161. }
  9162. }
  9163. function setLineCap( value ) {
  9164. // "butt", "round", "square"
  9165. if ( _contextLineCap !== value ) {
  9166. _context.lineCap = value;
  9167. _contextLineCap = value;
  9168. }
  9169. }
  9170. function setLineJoin( value ) {
  9171. // "round", "bevel", "miter"
  9172. if ( _contextLineJoin !== value ) {
  9173. _context.lineJoin = value;
  9174. _contextLineJoin = value;
  9175. }
  9176. }
  9177. function setStrokeStyle( value ) {
  9178. if ( _contextStrokeStyle !== value ) {
  9179. _context.strokeStyle = value;
  9180. _contextStrokeStyle = value;
  9181. }
  9182. }
  9183. function setFillStyle( value ) {
  9184. if ( _contextFillStyle !== value ) {
  9185. _context.fillStyle = value;
  9186. _contextFillStyle = value;
  9187. }
  9188. }
  9189. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9190. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9191. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9192. _contextDashSize = dashSizeValue;
  9193. _contextGapSize = gapSizeValue;
  9194. }
  9195. }
  9196. };
  9197. /**
  9198. * @author alteredq / http://alteredqualia.com/
  9199. * @author mrdoob / http://mrdoob.com/
  9200. * @author mikael emtinger / http://gomo.se/
  9201. */
  9202. THREE.ShaderChunk = {
  9203. // FOG
  9204. fog_pars_fragment: [
  9205. "#ifdef USE_FOG",
  9206. "uniform vec3 fogColor;",
  9207. "#ifdef FOG_EXP2",
  9208. "uniform float fogDensity;",
  9209. "#else",
  9210. "uniform float fogNear;",
  9211. "uniform float fogFar;",
  9212. "#endif",
  9213. "#endif"
  9214. ].join("\n"),
  9215. fog_fragment: [
  9216. "#ifdef USE_FOG",
  9217. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9218. "#ifdef FOG_EXP2",
  9219. "const float LOG2 = 1.442695;",
  9220. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9221. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9222. "#else",
  9223. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9224. "#endif",
  9225. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9226. "#endif"
  9227. ].join("\n"),
  9228. // ENVIRONMENT MAP
  9229. envmap_pars_fragment: [
  9230. "#ifdef USE_ENVMAP",
  9231. "uniform float reflectivity;",
  9232. "uniform samplerCube envMap;",
  9233. "uniform float flipEnvMap;",
  9234. "uniform int combine;",
  9235. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9236. "uniform bool useRefract;",
  9237. "uniform float refractionRatio;",
  9238. "#else",
  9239. "varying vec3 vReflect;",
  9240. "#endif",
  9241. "#endif"
  9242. ].join("\n"),
  9243. envmap_fragment: [
  9244. "#ifdef USE_ENVMAP",
  9245. "vec3 reflectVec;",
  9246. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9247. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9248. "if ( useRefract ) {",
  9249. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9250. "} else { ",
  9251. "reflectVec = reflect( cameraToVertex, normal );",
  9252. "}",
  9253. "#else",
  9254. "reflectVec = vReflect;",
  9255. "#endif",
  9256. "#ifdef DOUBLE_SIDED",
  9257. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9258. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9259. "#else",
  9260. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9261. "#endif",
  9262. "#ifdef GAMMA_INPUT",
  9263. "cubeColor.xyz *= cubeColor.xyz;",
  9264. "#endif",
  9265. "if ( combine == 1 ) {",
  9266. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9267. "} else if ( combine == 2 ) {",
  9268. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9269. "} else {",
  9270. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9271. "}",
  9272. "#endif"
  9273. ].join("\n"),
  9274. envmap_pars_vertex: [
  9275. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9276. "varying vec3 vReflect;",
  9277. "uniform float refractionRatio;",
  9278. "uniform bool useRefract;",
  9279. "#endif"
  9280. ].join("\n"),
  9281. worldpos_vertex : [
  9282. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9283. "#ifdef USE_SKINNING",
  9284. "vec4 worldPosition = modelMatrix * skinned;",
  9285. "#endif",
  9286. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9287. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9288. "#endif",
  9289. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9290. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9291. "#endif",
  9292. "#endif"
  9293. ].join("\n"),
  9294. envmap_vertex : [
  9295. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9296. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9297. "worldNormal = normalize( worldNormal );",
  9298. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9299. "if ( useRefract ) {",
  9300. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9301. "} else {",
  9302. "vReflect = reflect( cameraToVertex, worldNormal );",
  9303. "}",
  9304. "#endif"
  9305. ].join("\n"),
  9306. // COLOR MAP (particles)
  9307. map_particle_pars_fragment: [
  9308. "#ifdef USE_MAP",
  9309. "uniform sampler2D map;",
  9310. "#endif"
  9311. ].join("\n"),
  9312. map_particle_fragment: [
  9313. "#ifdef USE_MAP",
  9314. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9315. "#endif"
  9316. ].join("\n"),
  9317. // COLOR MAP (triangles)
  9318. map_pars_vertex: [
  9319. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9320. "varying vec2 vUv;",
  9321. "uniform vec4 offsetRepeat;",
  9322. "#endif"
  9323. ].join("\n"),
  9324. map_pars_fragment: [
  9325. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9326. "varying vec2 vUv;",
  9327. "#endif",
  9328. "#ifdef USE_MAP",
  9329. "uniform sampler2D map;",
  9330. "#endif"
  9331. ].join("\n"),
  9332. map_vertex: [
  9333. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9334. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9335. "#endif"
  9336. ].join("\n"),
  9337. map_fragment: [
  9338. "#ifdef USE_MAP",
  9339. "vec4 texelColor = texture2D( map, vUv );",
  9340. "#ifdef GAMMA_INPUT",
  9341. "texelColor.xyz *= texelColor.xyz;",
  9342. "#endif",
  9343. "gl_FragColor = gl_FragColor * texelColor;",
  9344. "#endif"
  9345. ].join("\n"),
  9346. // LIGHT MAP
  9347. lightmap_pars_fragment: [
  9348. "#ifdef USE_LIGHTMAP",
  9349. "varying vec2 vUv2;",
  9350. "uniform sampler2D lightMap;",
  9351. "#endif"
  9352. ].join("\n"),
  9353. lightmap_pars_vertex: [
  9354. "#ifdef USE_LIGHTMAP",
  9355. "varying vec2 vUv2;",
  9356. "#endif"
  9357. ].join("\n"),
  9358. lightmap_fragment: [
  9359. "#ifdef USE_LIGHTMAP",
  9360. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9361. "#endif"
  9362. ].join("\n"),
  9363. lightmap_vertex: [
  9364. "#ifdef USE_LIGHTMAP",
  9365. "vUv2 = uv2;",
  9366. "#endif"
  9367. ].join("\n"),
  9368. // BUMP MAP
  9369. bumpmap_pars_fragment: [
  9370. "#ifdef USE_BUMPMAP",
  9371. "uniform sampler2D bumpMap;",
  9372. "uniform float bumpScale;",
  9373. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9374. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9375. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9376. "vec2 dHdxy_fwd() {",
  9377. "vec2 dSTdx = dFdx( vUv );",
  9378. "vec2 dSTdy = dFdy( vUv );",
  9379. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9380. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9381. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9382. "return vec2( dBx, dBy );",
  9383. "}",
  9384. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9385. "vec3 vSigmaX = dFdx( surf_pos );",
  9386. "vec3 vSigmaY = dFdy( surf_pos );",
  9387. "vec3 vN = surf_norm;", // normalized
  9388. "vec3 R1 = cross( vSigmaY, vN );",
  9389. "vec3 R2 = cross( vN, vSigmaX );",
  9390. "float fDet = dot( vSigmaX, R1 );",
  9391. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9392. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9393. "}",
  9394. "#endif"
  9395. ].join("\n"),
  9396. // NORMAL MAP
  9397. normalmap_pars_fragment: [
  9398. "#ifdef USE_NORMALMAP",
  9399. "uniform sampler2D normalMap;",
  9400. "uniform vec2 normalScale;",
  9401. // Per-Pixel Tangent Space Normal Mapping
  9402. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9403. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9404. "vec3 q0 = dFdx( eye_pos.xyz );",
  9405. "vec3 q1 = dFdy( eye_pos.xyz );",
  9406. "vec2 st0 = dFdx( vUv.st );",
  9407. "vec2 st1 = dFdy( vUv.st );",
  9408. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9409. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9410. "vec3 N = normalize( surf_norm );",
  9411. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9412. "mapN.xy = normalScale * mapN.xy;",
  9413. "mat3 tsn = mat3( S, T, N );",
  9414. "return normalize( tsn * mapN );",
  9415. "}",
  9416. "#endif"
  9417. ].join("\n"),
  9418. // SPECULAR MAP
  9419. specularmap_pars_fragment: [
  9420. "#ifdef USE_SPECULARMAP",
  9421. "uniform sampler2D specularMap;",
  9422. "#endif"
  9423. ].join("\n"),
  9424. specularmap_fragment: [
  9425. "float specularStrength;",
  9426. "#ifdef USE_SPECULARMAP",
  9427. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9428. "specularStrength = texelSpecular.r;",
  9429. "#else",
  9430. "specularStrength = 1.0;",
  9431. "#endif"
  9432. ].join("\n"),
  9433. // LIGHTS LAMBERT
  9434. lights_lambert_pars_vertex: [
  9435. "uniform vec3 ambient;",
  9436. "uniform vec3 diffuse;",
  9437. "uniform vec3 emissive;",
  9438. "uniform vec3 ambientLightColor;",
  9439. "#if MAX_DIR_LIGHTS > 0",
  9440. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9441. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9442. "#endif",
  9443. "#if MAX_HEMI_LIGHTS > 0",
  9444. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9445. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9446. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9447. "#endif",
  9448. "#if MAX_POINT_LIGHTS > 0",
  9449. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9450. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9451. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9452. "#endif",
  9453. "#if MAX_SPOT_LIGHTS > 0",
  9454. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9455. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9456. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9457. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9458. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9459. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9460. "#endif",
  9461. "#ifdef WRAP_AROUND",
  9462. "uniform vec3 wrapRGB;",
  9463. "#endif"
  9464. ].join("\n"),
  9465. lights_lambert_vertex: [
  9466. "vLightFront = vec3( 0.0 );",
  9467. "#ifdef DOUBLE_SIDED",
  9468. "vLightBack = vec3( 0.0 );",
  9469. "#endif",
  9470. "transformedNormal = normalize( transformedNormal );",
  9471. "#if MAX_DIR_LIGHTS > 0",
  9472. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9473. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9474. "vec3 dirVector = normalize( lDirection.xyz );",
  9475. "float dotProduct = dot( transformedNormal, dirVector );",
  9476. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9477. "#ifdef DOUBLE_SIDED",
  9478. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9479. "#ifdef WRAP_AROUND",
  9480. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9481. "#endif",
  9482. "#endif",
  9483. "#ifdef WRAP_AROUND",
  9484. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9485. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9486. "#ifdef DOUBLE_SIDED",
  9487. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9488. "#endif",
  9489. "#endif",
  9490. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9491. "#ifdef DOUBLE_SIDED",
  9492. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9493. "#endif",
  9494. "}",
  9495. "#endif",
  9496. "#if MAX_POINT_LIGHTS > 0",
  9497. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9498. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9499. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9500. "float lDistance = 1.0;",
  9501. "if ( pointLightDistance[ i ] > 0.0 )",
  9502. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9503. "lVector = normalize( lVector );",
  9504. "float dotProduct = dot( transformedNormal, lVector );",
  9505. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9506. "#ifdef DOUBLE_SIDED",
  9507. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9508. "#ifdef WRAP_AROUND",
  9509. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9510. "#endif",
  9511. "#endif",
  9512. "#ifdef WRAP_AROUND",
  9513. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9514. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9515. "#ifdef DOUBLE_SIDED",
  9516. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9517. "#endif",
  9518. "#endif",
  9519. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9520. "#ifdef DOUBLE_SIDED",
  9521. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9522. "#endif",
  9523. "}",
  9524. "#endif",
  9525. "#if MAX_SPOT_LIGHTS > 0",
  9526. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9527. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9528. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9529. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9530. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9531. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9532. "float lDistance = 1.0;",
  9533. "if ( spotLightDistance[ i ] > 0.0 )",
  9534. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9535. "lVector = normalize( lVector );",
  9536. "float dotProduct = dot( transformedNormal, lVector );",
  9537. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9538. "#ifdef DOUBLE_SIDED",
  9539. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9540. "#ifdef WRAP_AROUND",
  9541. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9542. "#endif",
  9543. "#endif",
  9544. "#ifdef WRAP_AROUND",
  9545. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9546. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9547. "#ifdef DOUBLE_SIDED",
  9548. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9549. "#endif",
  9550. "#endif",
  9551. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9552. "#ifdef DOUBLE_SIDED",
  9553. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9554. "#endif",
  9555. "}",
  9556. "}",
  9557. "#endif",
  9558. "#if MAX_HEMI_LIGHTS > 0",
  9559. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9560. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9561. "vec3 lVector = normalize( lDirection.xyz );",
  9562. "float dotProduct = dot( transformedNormal, lVector );",
  9563. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9564. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9565. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9566. "#ifdef DOUBLE_SIDED",
  9567. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9568. "#endif",
  9569. "}",
  9570. "#endif",
  9571. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9572. "#ifdef DOUBLE_SIDED",
  9573. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9574. "#endif"
  9575. ].join("\n"),
  9576. // LIGHTS PHONG
  9577. lights_phong_pars_vertex: [
  9578. "#ifndef PHONG_PER_PIXEL",
  9579. "#if MAX_POINT_LIGHTS > 0",
  9580. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9581. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9582. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9583. "#endif",
  9584. "#if MAX_SPOT_LIGHTS > 0",
  9585. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9586. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9587. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9588. "#endif",
  9589. "#endif",
  9590. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9591. "varying vec3 vWorldPosition;",
  9592. "#endif"
  9593. ].join("\n"),
  9594. lights_phong_vertex: [
  9595. "#ifndef PHONG_PER_PIXEL",
  9596. "#if MAX_POINT_LIGHTS > 0",
  9597. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9598. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9599. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9600. "float lDistance = 1.0;",
  9601. "if ( pointLightDistance[ i ] > 0.0 )",
  9602. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9603. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9604. "}",
  9605. "#endif",
  9606. "#if MAX_SPOT_LIGHTS > 0",
  9607. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9608. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9609. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9610. "float lDistance = 1.0;",
  9611. "if ( spotLightDistance[ i ] > 0.0 )",
  9612. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9613. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9614. "}",
  9615. "#endif",
  9616. "#endif",
  9617. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9618. "vWorldPosition = worldPosition.xyz;",
  9619. "#endif"
  9620. ].join("\n"),
  9621. lights_phong_pars_fragment: [
  9622. "uniform vec3 ambientLightColor;",
  9623. "#if MAX_DIR_LIGHTS > 0",
  9624. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9625. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9626. "#endif",
  9627. "#if MAX_HEMI_LIGHTS > 0",
  9628. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9629. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9630. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9631. "#endif",
  9632. "#if MAX_POINT_LIGHTS > 0",
  9633. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9634. "#ifdef PHONG_PER_PIXEL",
  9635. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9636. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9637. "#else",
  9638. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9639. "#endif",
  9640. "#endif",
  9641. "#if MAX_SPOT_LIGHTS > 0",
  9642. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9643. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9644. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9645. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9646. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9647. "#ifdef PHONG_PER_PIXEL",
  9648. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9649. "#else",
  9650. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9651. "#endif",
  9652. "#endif",
  9653. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9654. "varying vec3 vWorldPosition;",
  9655. "#endif",
  9656. "#ifdef WRAP_AROUND",
  9657. "uniform vec3 wrapRGB;",
  9658. "#endif",
  9659. "varying vec3 vViewPosition;",
  9660. "varying vec3 vNormal;"
  9661. ].join("\n"),
  9662. lights_phong_fragment: [
  9663. "vec3 normal = normalize( vNormal );",
  9664. "vec3 viewPosition = normalize( vViewPosition );",
  9665. "#ifdef DOUBLE_SIDED",
  9666. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9667. "#endif",
  9668. "#ifdef USE_NORMALMAP",
  9669. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  9670. "#elif defined( USE_BUMPMAP )",
  9671. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9672. "#endif",
  9673. "#if MAX_POINT_LIGHTS > 0",
  9674. "vec3 pointDiffuse = vec3( 0.0 );",
  9675. "vec3 pointSpecular = vec3( 0.0 );",
  9676. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9677. "#ifdef PHONG_PER_PIXEL",
  9678. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9679. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9680. "float lDistance = 1.0;",
  9681. "if ( pointLightDistance[ i ] > 0.0 )",
  9682. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9683. "lVector = normalize( lVector );",
  9684. "#else",
  9685. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9686. "float lDistance = vPointLight[ i ].w;",
  9687. "#endif",
  9688. // diffuse
  9689. "float dotProduct = dot( normal, lVector );",
  9690. "#ifdef WRAP_AROUND",
  9691. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9692. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9693. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9694. "#else",
  9695. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9696. "#endif",
  9697. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9698. // specular
  9699. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9700. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9701. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9702. "#ifdef PHYSICALLY_BASED_SHADING",
  9703. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9704. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9705. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9706. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9707. "#else",
  9708. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9709. "#endif",
  9710. "}",
  9711. "#endif",
  9712. "#if MAX_SPOT_LIGHTS > 0",
  9713. "vec3 spotDiffuse = vec3( 0.0 );",
  9714. "vec3 spotSpecular = vec3( 0.0 );",
  9715. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9716. "#ifdef PHONG_PER_PIXEL",
  9717. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9718. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9719. "float lDistance = 1.0;",
  9720. "if ( spotLightDistance[ i ] > 0.0 )",
  9721. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9722. "lVector = normalize( lVector );",
  9723. "#else",
  9724. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9725. "float lDistance = vSpotLight[ i ].w;",
  9726. "#endif",
  9727. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9728. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9729. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9730. // diffuse
  9731. "float dotProduct = dot( normal, lVector );",
  9732. "#ifdef WRAP_AROUND",
  9733. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9734. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9735. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9736. "#else",
  9737. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9738. "#endif",
  9739. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9740. // specular
  9741. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9742. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9743. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9744. "#ifdef PHYSICALLY_BASED_SHADING",
  9745. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9746. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9747. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9748. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9749. "#else",
  9750. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9751. "#endif",
  9752. "}",
  9753. "}",
  9754. "#endif",
  9755. "#if MAX_DIR_LIGHTS > 0",
  9756. "vec3 dirDiffuse = vec3( 0.0 );",
  9757. "vec3 dirSpecular = vec3( 0.0 );" ,
  9758. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9759. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9760. "vec3 dirVector = normalize( lDirection.xyz );",
  9761. // diffuse
  9762. "float dotProduct = dot( normal, dirVector );",
  9763. "#ifdef WRAP_AROUND",
  9764. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9765. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9766. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9767. "#else",
  9768. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9769. "#endif",
  9770. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9771. // specular
  9772. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9773. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9774. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9775. "#ifdef PHYSICALLY_BASED_SHADING",
  9776. /*
  9777. // fresnel term from skin shader
  9778. "const float F0 = 0.128;",
  9779. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9780. "float exponential = pow( base, 5.0 );",
  9781. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9782. */
  9783. /*
  9784. // fresnel term from fresnel shader
  9785. "const float mFresnelBias = 0.08;",
  9786. "const float mFresnelScale = 0.3;",
  9787. "const float mFresnelPower = 5.0;",
  9788. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9789. */
  9790. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9791. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9792. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9793. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9794. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9795. "#else",
  9796. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9797. "#endif",
  9798. "}",
  9799. "#endif",
  9800. "#if MAX_HEMI_LIGHTS > 0",
  9801. "vec3 hemiDiffuse = vec3( 0.0 );",
  9802. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9803. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9804. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9805. "vec3 lVector = normalize( lDirection.xyz );",
  9806. // diffuse
  9807. "float dotProduct = dot( normal, lVector );",
  9808. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9809. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9810. "hemiDiffuse += diffuse * hemiColor;",
  9811. // specular (sky light)
  9812. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9813. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9814. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9815. // specular (ground light)
  9816. "vec3 lVectorGround = -lVector;",
  9817. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9818. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9819. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9820. "#ifdef PHYSICALLY_BASED_SHADING",
  9821. "float dotProductGround = dot( normal, lVectorGround );",
  9822. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9823. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9824. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9825. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9826. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9827. "#else",
  9828. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9829. "#endif",
  9830. "}",
  9831. "#endif",
  9832. "vec3 totalDiffuse = vec3( 0.0 );",
  9833. "vec3 totalSpecular = vec3( 0.0 );",
  9834. "#if MAX_DIR_LIGHTS > 0",
  9835. "totalDiffuse += dirDiffuse;",
  9836. "totalSpecular += dirSpecular;",
  9837. "#endif",
  9838. "#if MAX_HEMI_LIGHTS > 0",
  9839. "totalDiffuse += hemiDiffuse;",
  9840. "totalSpecular += hemiSpecular;",
  9841. "#endif",
  9842. "#if MAX_POINT_LIGHTS > 0",
  9843. "totalDiffuse += pointDiffuse;",
  9844. "totalSpecular += pointSpecular;",
  9845. "#endif",
  9846. "#if MAX_SPOT_LIGHTS > 0",
  9847. "totalDiffuse += spotDiffuse;",
  9848. "totalSpecular += spotSpecular;",
  9849. "#endif",
  9850. "#ifdef METAL",
  9851. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9852. "#else",
  9853. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9854. "#endif"
  9855. ].join("\n"),
  9856. // VERTEX COLORS
  9857. color_pars_fragment: [
  9858. "#ifdef USE_COLOR",
  9859. "varying vec3 vColor;",
  9860. "#endif"
  9861. ].join("\n"),
  9862. color_fragment: [
  9863. "#ifdef USE_COLOR",
  9864. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9865. "#endif"
  9866. ].join("\n"),
  9867. color_pars_vertex: [
  9868. "#ifdef USE_COLOR",
  9869. "varying vec3 vColor;",
  9870. "#endif"
  9871. ].join("\n"),
  9872. color_vertex: [
  9873. "#ifdef USE_COLOR",
  9874. "#ifdef GAMMA_INPUT",
  9875. "vColor = color * color;",
  9876. "#else",
  9877. "vColor = color;",
  9878. "#endif",
  9879. "#endif"
  9880. ].join("\n"),
  9881. // SKINNING
  9882. skinning_pars_vertex: [
  9883. "#ifdef USE_SKINNING",
  9884. "#ifdef BONE_TEXTURE",
  9885. "uniform sampler2D boneTexture;",
  9886. "mat4 getBoneMatrix( const in float i ) {",
  9887. "float j = i * 4.0;",
  9888. "float x = mod( j, N_BONE_PIXEL_X );",
  9889. "float y = floor( j / N_BONE_PIXEL_X );",
  9890. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9891. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9892. "y = dy * ( y + 0.5 );",
  9893. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9894. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9895. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9896. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9897. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9898. "return bone;",
  9899. "}",
  9900. "#else",
  9901. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9902. "mat4 getBoneMatrix( const in float i ) {",
  9903. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9904. "return bone;",
  9905. "}",
  9906. "#endif",
  9907. "#endif"
  9908. ].join("\n"),
  9909. skinbase_vertex: [
  9910. "#ifdef USE_SKINNING",
  9911. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9912. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9913. "#endif"
  9914. ].join("\n"),
  9915. skinning_vertex: [
  9916. "#ifdef USE_SKINNING",
  9917. "#ifdef USE_MORPHTARGETS",
  9918. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9919. "#else",
  9920. "vec4 skinVertex = vec4( position, 1.0 );",
  9921. "#endif",
  9922. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9923. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9924. "#endif"
  9925. ].join("\n"),
  9926. // MORPHING
  9927. morphtarget_pars_vertex: [
  9928. "#ifdef USE_MORPHTARGETS",
  9929. "#ifndef USE_MORPHNORMALS",
  9930. "uniform float morphTargetInfluences[ 8 ];",
  9931. "#else",
  9932. "uniform float morphTargetInfluences[ 4 ];",
  9933. "#endif",
  9934. "#endif"
  9935. ].join("\n"),
  9936. morphtarget_vertex: [
  9937. "#ifdef USE_MORPHTARGETS",
  9938. "vec3 morphed = vec3( 0.0 );",
  9939. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9940. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9941. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9942. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9943. "#ifndef USE_MORPHNORMALS",
  9944. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9945. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9946. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9947. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9948. "#endif",
  9949. "morphed += position;",
  9950. "#endif"
  9951. ].join("\n"),
  9952. default_vertex : [
  9953. "vec4 mvPosition;",
  9954. "#ifdef USE_SKINNING",
  9955. "mvPosition = modelViewMatrix * skinned;",
  9956. "#endif",
  9957. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9958. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9959. "#endif",
  9960. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9961. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9962. "#endif",
  9963. "gl_Position = projectionMatrix * mvPosition;"
  9964. ].join("\n"),
  9965. morphnormal_vertex: [
  9966. "#ifdef USE_MORPHNORMALS",
  9967. "vec3 morphedNormal = vec3( 0.0 );",
  9968. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9969. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9970. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9971. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9972. "morphedNormal += normal;",
  9973. "#endif"
  9974. ].join("\n"),
  9975. skinnormal_vertex: [
  9976. "#ifdef USE_SKINNING",
  9977. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9978. "skinMatrix += skinWeight.y * boneMatY;",
  9979. "#ifdef USE_MORPHNORMALS",
  9980. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9981. "#else",
  9982. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9983. "#endif",
  9984. "#endif"
  9985. ].join("\n"),
  9986. defaultnormal_vertex: [
  9987. "vec3 objectNormal;",
  9988. "#ifdef USE_SKINNING",
  9989. "objectNormal = skinnedNormal.xyz;",
  9990. "#endif",
  9991. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9992. "objectNormal = morphedNormal;",
  9993. "#endif",
  9994. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9995. "objectNormal = normal;",
  9996. "#endif",
  9997. "#ifdef FLIP_SIDED",
  9998. "objectNormal = -objectNormal;",
  9999. "#endif",
  10000. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10001. ].join("\n"),
  10002. // SHADOW MAP
  10003. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10004. // http://spidergl.org/example.php?id=6
  10005. // http://fabiensanglard.net/shadowmapping
  10006. shadowmap_pars_fragment: [
  10007. "#ifdef USE_SHADOWMAP",
  10008. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10009. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10010. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10011. "uniform float shadowBias[ MAX_SHADOWS ];",
  10012. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10013. "float unpackDepth( const in vec4 rgba_depth ) {",
  10014. "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 );",
  10015. "float depth = dot( rgba_depth, bit_shift );",
  10016. "return depth;",
  10017. "}",
  10018. "#endif"
  10019. ].join("\n"),
  10020. shadowmap_fragment: [
  10021. "#ifdef USE_SHADOWMAP",
  10022. "#ifdef SHADOWMAP_DEBUG",
  10023. "vec3 frustumColors[3];",
  10024. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10025. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10026. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10027. "#endif",
  10028. "#ifdef SHADOWMAP_CASCADE",
  10029. "int inFrustumCount = 0;",
  10030. "#endif",
  10031. "float fDepth;",
  10032. "vec3 shadowColor = vec3( 1.0 );",
  10033. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10034. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10035. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10036. // "if ( all( something, something ) )" using this instead
  10037. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10038. "bool inFrustum = all( inFrustumVec );",
  10039. // don't shadow pixels outside of light frustum
  10040. // use just first frustum (for cascades)
  10041. // don't shadow pixels behind far plane of light frustum
  10042. "#ifdef SHADOWMAP_CASCADE",
  10043. "inFrustumCount += int( inFrustum );",
  10044. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10045. "#else",
  10046. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10047. "#endif",
  10048. "bool frustumTest = all( frustumTestVec );",
  10049. "if ( frustumTest ) {",
  10050. "shadowCoord.z += shadowBias[ i ];",
  10051. "#if defined( SHADOWMAP_TYPE_PCF )",
  10052. // Percentage-close filtering
  10053. // (9 pixel kernel)
  10054. // http://fabiensanglard.net/shadowmappingPCF/
  10055. "float shadow = 0.0;",
  10056. /*
  10057. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10058. // must enroll loop manually
  10059. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10060. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10061. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10062. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10063. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10064. "float fDepth = unpackDepth( rgbaDepth );",
  10065. "if ( fDepth < shadowCoord.z )",
  10066. "shadow += 1.0;",
  10067. "}",
  10068. "shadow /= 9.0;",
  10069. */
  10070. "const float shadowDelta = 1.0 / 9.0;",
  10071. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10072. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10073. "float dx0 = -1.25 * xPixelOffset;",
  10074. "float dy0 = -1.25 * yPixelOffset;",
  10075. "float dx1 = 1.25 * xPixelOffset;",
  10076. "float dy1 = 1.25 * yPixelOffset;",
  10077. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10078. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10079. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10080. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10081. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10082. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10083. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10084. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10085. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10086. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10087. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10088. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10089. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10090. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10091. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10092. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10093. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10094. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10095. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10096. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10097. // Percentage-close filtering
  10098. // (9 pixel kernel)
  10099. // http://fabiensanglard.net/shadowmappingPCF/
  10100. "float shadow = 0.0;",
  10101. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10102. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10103. "float dx0 = -1.0 * xPixelOffset;",
  10104. "float dy0 = -1.0 * yPixelOffset;",
  10105. "float dx1 = 1.0 * xPixelOffset;",
  10106. "float dy1 = 1.0 * yPixelOffset;",
  10107. "mat3 shadowKernel;",
  10108. "mat3 depthKernel;",
  10109. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10110. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10111. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10112. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10113. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10114. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10115. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10116. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10117. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10118. "vec3 shadowZ = vec3( shadowCoord.z );",
  10119. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10120. "shadowKernel[0] *= vec3(0.25);",
  10121. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10122. "shadowKernel[1] *= vec3(0.25);",
  10123. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10124. "shadowKernel[2] *= vec3(0.25);",
  10125. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10126. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10127. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10128. "vec4 shadowValues;",
  10129. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10130. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10131. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10132. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10133. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10134. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10135. "#else",
  10136. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10137. "float fDepth = unpackDepth( rgbaDepth );",
  10138. "if ( fDepth < shadowCoord.z )",
  10139. // spot with multiple shadows is darker
  10140. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10141. // spot with multiple shadows has the same color as single shadow spot
  10142. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10143. "#endif",
  10144. "}",
  10145. "#ifdef SHADOWMAP_DEBUG",
  10146. "#ifdef SHADOWMAP_CASCADE",
  10147. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10148. "#else",
  10149. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10150. "#endif",
  10151. "#endif",
  10152. "}",
  10153. "#ifdef GAMMA_OUTPUT",
  10154. "shadowColor *= shadowColor;",
  10155. "#endif",
  10156. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10157. "#endif"
  10158. ].join("\n"),
  10159. shadowmap_pars_vertex: [
  10160. "#ifdef USE_SHADOWMAP",
  10161. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10162. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10163. "#endif"
  10164. ].join("\n"),
  10165. shadowmap_vertex: [
  10166. "#ifdef USE_SHADOWMAP",
  10167. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10168. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10169. "}",
  10170. "#endif"
  10171. ].join("\n"),
  10172. // ALPHATEST
  10173. alphatest_fragment: [
  10174. "#ifdef ALPHATEST",
  10175. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10176. "#endif"
  10177. ].join("\n"),
  10178. // LINEAR SPACE
  10179. linear_to_gamma_fragment: [
  10180. "#ifdef GAMMA_OUTPUT",
  10181. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10182. "#endif"
  10183. ].join("\n")
  10184. };
  10185. THREE.UniformsUtils = {
  10186. merge: function ( uniforms ) {
  10187. var u, p, tmp, merged = {};
  10188. for ( u = 0; u < uniforms.length; u ++ ) {
  10189. tmp = this.clone( uniforms[ u ] );
  10190. for ( p in tmp ) {
  10191. merged[ p ] = tmp[ p ];
  10192. }
  10193. }
  10194. return merged;
  10195. },
  10196. clone: function ( uniforms_src ) {
  10197. var u, p, parameter, parameter_src, uniforms_dst = {};
  10198. for ( u in uniforms_src ) {
  10199. uniforms_dst[ u ] = {};
  10200. for ( p in uniforms_src[ u ] ) {
  10201. parameter_src = uniforms_src[ u ][ p ];
  10202. if ( parameter_src instanceof THREE.Color ||
  10203. parameter_src instanceof THREE.Vector2 ||
  10204. parameter_src instanceof THREE.Vector3 ||
  10205. parameter_src instanceof THREE.Vector4 ||
  10206. parameter_src instanceof THREE.Matrix4 ||
  10207. parameter_src instanceof THREE.Texture ) {
  10208. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10209. } else if ( parameter_src instanceof Array ) {
  10210. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10211. } else {
  10212. uniforms_dst[ u ][ p ] = parameter_src;
  10213. }
  10214. }
  10215. }
  10216. return uniforms_dst;
  10217. }
  10218. };
  10219. THREE.UniformsLib = {
  10220. common: {
  10221. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10222. "opacity" : { type: "f", value: 1.0 },
  10223. "map" : { type: "t", value: null },
  10224. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10225. "lightMap" : { type: "t", value: null },
  10226. "specularMap" : { type: "t", value: null },
  10227. "envMap" : { type: "t", value: null },
  10228. "flipEnvMap" : { type: "f", value: -1 },
  10229. "useRefract" : { type: "i", value: 0 },
  10230. "reflectivity" : { type: "f", value: 1.0 },
  10231. "refractionRatio" : { type: "f", value: 0.98 },
  10232. "combine" : { type: "i", value: 0 },
  10233. "morphTargetInfluences" : { type: "f", value: 0 }
  10234. },
  10235. bump: {
  10236. "bumpMap" : { type: "t", value: null },
  10237. "bumpScale" : { type: "f", value: 1 }
  10238. },
  10239. normalmap: {
  10240. "normalMap" : { type: "t", value: null },
  10241. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10242. },
  10243. fog : {
  10244. "fogDensity" : { type: "f", value: 0.00025 },
  10245. "fogNear" : { type: "f", value: 1 },
  10246. "fogFar" : { type: "f", value: 2000 },
  10247. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10248. },
  10249. lights: {
  10250. "ambientLightColor" : { type: "fv", value: [] },
  10251. "directionalLightDirection" : { type: "fv", value: [] },
  10252. "directionalLightColor" : { type: "fv", value: [] },
  10253. "hemisphereLightDirection" : { type: "fv", value: [] },
  10254. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10255. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10256. "pointLightColor" : { type: "fv", value: [] },
  10257. "pointLightPosition" : { type: "fv", value: [] },
  10258. "pointLightDistance" : { type: "fv1", value: [] },
  10259. "spotLightColor" : { type: "fv", value: [] },
  10260. "spotLightPosition" : { type: "fv", value: [] },
  10261. "spotLightDirection" : { type: "fv", value: [] },
  10262. "spotLightDistance" : { type: "fv1", value: [] },
  10263. "spotLightAngleCos" : { type: "fv1", value: [] },
  10264. "spotLightExponent" : { type: "fv1", value: [] }
  10265. },
  10266. particle: {
  10267. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10268. "opacity" : { type: "f", value: 1.0 },
  10269. "size" : { type: "f", value: 1.0 },
  10270. "scale" : { type: "f", value: 1.0 },
  10271. "map" : { type: "t", value: null },
  10272. "fogDensity" : { type: "f", value: 0.00025 },
  10273. "fogNear" : { type: "f", value: 1 },
  10274. "fogFar" : { type: "f", value: 2000 },
  10275. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10276. },
  10277. shadowmap: {
  10278. "shadowMap": { type: "tv", value: [] },
  10279. "shadowMapSize": { type: "v2v", value: [] },
  10280. "shadowBias" : { type: "fv1", value: [] },
  10281. "shadowDarkness": { type: "fv1", value: [] },
  10282. "shadowMatrix" : { type: "m4v", value: [] }
  10283. }
  10284. };
  10285. THREE.ShaderLib = {
  10286. 'basic': {
  10287. uniforms: THREE.UniformsUtils.merge( [
  10288. THREE.UniformsLib[ "common" ],
  10289. THREE.UniformsLib[ "fog" ],
  10290. THREE.UniformsLib[ "shadowmap" ]
  10291. ] ),
  10292. vertexShader: [
  10293. THREE.ShaderChunk[ "map_pars_vertex" ],
  10294. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10295. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10296. THREE.ShaderChunk[ "color_pars_vertex" ],
  10297. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10298. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10299. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10300. "void main() {",
  10301. THREE.ShaderChunk[ "map_vertex" ],
  10302. THREE.ShaderChunk[ "lightmap_vertex" ],
  10303. THREE.ShaderChunk[ "color_vertex" ],
  10304. THREE.ShaderChunk[ "skinbase_vertex" ],
  10305. "#ifdef USE_ENVMAP",
  10306. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10307. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10308. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10309. "#endif",
  10310. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10311. THREE.ShaderChunk[ "skinning_vertex" ],
  10312. THREE.ShaderChunk[ "default_vertex" ],
  10313. THREE.ShaderChunk[ "worldpos_vertex" ],
  10314. THREE.ShaderChunk[ "envmap_vertex" ],
  10315. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10316. "}"
  10317. ].join("\n"),
  10318. fragmentShader: [
  10319. "uniform vec3 diffuse;",
  10320. "uniform float opacity;",
  10321. THREE.ShaderChunk[ "color_pars_fragment" ],
  10322. THREE.ShaderChunk[ "map_pars_fragment" ],
  10323. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10324. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10325. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10326. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10327. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10328. "void main() {",
  10329. "gl_FragColor = vec4( diffuse, opacity );",
  10330. THREE.ShaderChunk[ "map_fragment" ],
  10331. THREE.ShaderChunk[ "alphatest_fragment" ],
  10332. THREE.ShaderChunk[ "specularmap_fragment" ],
  10333. THREE.ShaderChunk[ "lightmap_fragment" ],
  10334. THREE.ShaderChunk[ "color_fragment" ],
  10335. THREE.ShaderChunk[ "envmap_fragment" ],
  10336. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10337. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10338. THREE.ShaderChunk[ "fog_fragment" ],
  10339. "}"
  10340. ].join("\n")
  10341. },
  10342. 'lambert': {
  10343. uniforms: THREE.UniformsUtils.merge( [
  10344. THREE.UniformsLib[ "common" ],
  10345. THREE.UniformsLib[ "fog" ],
  10346. THREE.UniformsLib[ "lights" ],
  10347. THREE.UniformsLib[ "shadowmap" ],
  10348. {
  10349. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10350. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10351. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10352. }
  10353. ] ),
  10354. vertexShader: [
  10355. "#define LAMBERT",
  10356. "varying vec3 vLightFront;",
  10357. "#ifdef DOUBLE_SIDED",
  10358. "varying vec3 vLightBack;",
  10359. "#endif",
  10360. THREE.ShaderChunk[ "map_pars_vertex" ],
  10361. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10362. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10363. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10364. THREE.ShaderChunk[ "color_pars_vertex" ],
  10365. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10366. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10367. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10368. "void main() {",
  10369. THREE.ShaderChunk[ "map_vertex" ],
  10370. THREE.ShaderChunk[ "lightmap_vertex" ],
  10371. THREE.ShaderChunk[ "color_vertex" ],
  10372. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10373. THREE.ShaderChunk[ "skinbase_vertex" ],
  10374. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10375. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10376. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10377. THREE.ShaderChunk[ "skinning_vertex" ],
  10378. THREE.ShaderChunk[ "default_vertex" ],
  10379. THREE.ShaderChunk[ "worldpos_vertex" ],
  10380. THREE.ShaderChunk[ "envmap_vertex" ],
  10381. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10382. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10383. "}"
  10384. ].join("\n"),
  10385. fragmentShader: [
  10386. "uniform float opacity;",
  10387. "varying vec3 vLightFront;",
  10388. "#ifdef DOUBLE_SIDED",
  10389. "varying vec3 vLightBack;",
  10390. "#endif",
  10391. THREE.ShaderChunk[ "color_pars_fragment" ],
  10392. THREE.ShaderChunk[ "map_pars_fragment" ],
  10393. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10394. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10395. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10396. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10397. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10398. "void main() {",
  10399. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10400. THREE.ShaderChunk[ "map_fragment" ],
  10401. THREE.ShaderChunk[ "alphatest_fragment" ],
  10402. THREE.ShaderChunk[ "specularmap_fragment" ],
  10403. "#ifdef DOUBLE_SIDED",
  10404. //"float isFront = float( gl_FrontFacing );",
  10405. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10406. "if ( gl_FrontFacing )",
  10407. "gl_FragColor.xyz *= vLightFront;",
  10408. "else",
  10409. "gl_FragColor.xyz *= vLightBack;",
  10410. "#else",
  10411. "gl_FragColor.xyz *= vLightFront;",
  10412. "#endif",
  10413. THREE.ShaderChunk[ "lightmap_fragment" ],
  10414. THREE.ShaderChunk[ "color_fragment" ],
  10415. THREE.ShaderChunk[ "envmap_fragment" ],
  10416. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10417. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10418. THREE.ShaderChunk[ "fog_fragment" ],
  10419. "}"
  10420. ].join("\n")
  10421. },
  10422. 'phong': {
  10423. uniforms: THREE.UniformsUtils.merge( [
  10424. THREE.UniformsLib[ "common" ],
  10425. THREE.UniformsLib[ "bump" ],
  10426. THREE.UniformsLib[ "normalmap" ],
  10427. THREE.UniformsLib[ "fog" ],
  10428. THREE.UniformsLib[ "lights" ],
  10429. THREE.UniformsLib[ "shadowmap" ],
  10430. {
  10431. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10432. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10433. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10434. "shininess": { type: "f", value: 30 },
  10435. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10436. }
  10437. ] ),
  10438. vertexShader: [
  10439. "#define PHONG",
  10440. "varying vec3 vViewPosition;",
  10441. "varying vec3 vNormal;",
  10442. THREE.ShaderChunk[ "map_pars_vertex" ],
  10443. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10444. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10445. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10446. THREE.ShaderChunk[ "color_pars_vertex" ],
  10447. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10448. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10449. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10450. "void main() {",
  10451. THREE.ShaderChunk[ "map_vertex" ],
  10452. THREE.ShaderChunk[ "lightmap_vertex" ],
  10453. THREE.ShaderChunk[ "color_vertex" ],
  10454. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10455. THREE.ShaderChunk[ "skinbase_vertex" ],
  10456. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10457. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10458. "vNormal = normalize( transformedNormal );",
  10459. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10460. THREE.ShaderChunk[ "skinning_vertex" ],
  10461. THREE.ShaderChunk[ "default_vertex" ],
  10462. "vViewPosition = -mvPosition.xyz;",
  10463. THREE.ShaderChunk[ "worldpos_vertex" ],
  10464. THREE.ShaderChunk[ "envmap_vertex" ],
  10465. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10466. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10467. "}"
  10468. ].join("\n"),
  10469. fragmentShader: [
  10470. "uniform vec3 diffuse;",
  10471. "uniform float opacity;",
  10472. "uniform vec3 ambient;",
  10473. "uniform vec3 emissive;",
  10474. "uniform vec3 specular;",
  10475. "uniform float shininess;",
  10476. THREE.ShaderChunk[ "color_pars_fragment" ],
  10477. THREE.ShaderChunk[ "map_pars_fragment" ],
  10478. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10479. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10480. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10481. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10482. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10483. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10484. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10485. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10486. "void main() {",
  10487. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10488. THREE.ShaderChunk[ "map_fragment" ],
  10489. THREE.ShaderChunk[ "alphatest_fragment" ],
  10490. THREE.ShaderChunk[ "specularmap_fragment" ],
  10491. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10492. THREE.ShaderChunk[ "lightmap_fragment" ],
  10493. THREE.ShaderChunk[ "color_fragment" ],
  10494. THREE.ShaderChunk[ "envmap_fragment" ],
  10495. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10496. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10497. THREE.ShaderChunk[ "fog_fragment" ],
  10498. "}"
  10499. ].join("\n")
  10500. },
  10501. 'particle_basic': {
  10502. uniforms: THREE.UniformsUtils.merge( [
  10503. THREE.UniformsLib[ "particle" ],
  10504. THREE.UniformsLib[ "shadowmap" ]
  10505. ] ),
  10506. vertexShader: [
  10507. "uniform float size;",
  10508. "uniform float scale;",
  10509. THREE.ShaderChunk[ "color_pars_vertex" ],
  10510. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10511. "void main() {",
  10512. THREE.ShaderChunk[ "color_vertex" ],
  10513. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10514. "#ifdef USE_SIZEATTENUATION",
  10515. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10516. "#else",
  10517. "gl_PointSize = size;",
  10518. "#endif",
  10519. "gl_Position = projectionMatrix * mvPosition;",
  10520. THREE.ShaderChunk[ "worldpos_vertex" ],
  10521. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10522. "}"
  10523. ].join("\n"),
  10524. fragmentShader: [
  10525. "uniform vec3 psColor;",
  10526. "uniform float opacity;",
  10527. THREE.ShaderChunk[ "color_pars_fragment" ],
  10528. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10529. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10530. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10531. "void main() {",
  10532. "gl_FragColor = vec4( psColor, opacity );",
  10533. THREE.ShaderChunk[ "map_particle_fragment" ],
  10534. THREE.ShaderChunk[ "alphatest_fragment" ],
  10535. THREE.ShaderChunk[ "color_fragment" ],
  10536. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10537. THREE.ShaderChunk[ "fog_fragment" ],
  10538. "}"
  10539. ].join("\n")
  10540. },
  10541. 'dashed': {
  10542. uniforms: THREE.UniformsUtils.merge( [
  10543. THREE.UniformsLib[ "common" ],
  10544. THREE.UniformsLib[ "fog" ],
  10545. {
  10546. "scale": { type: "f", value: 1 },
  10547. "dashSize": { type: "f", value: 1 },
  10548. "totalSize": { type: "f", value: 2 }
  10549. }
  10550. ] ),
  10551. vertexShader: [
  10552. "uniform float scale;",
  10553. "attribute float lineDistance;",
  10554. "varying float vLineDistance;",
  10555. THREE.ShaderChunk[ "color_pars_vertex" ],
  10556. "void main() {",
  10557. THREE.ShaderChunk[ "color_vertex" ],
  10558. "vLineDistance = scale * lineDistance;",
  10559. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10560. "gl_Position = projectionMatrix * mvPosition;",
  10561. "}"
  10562. ].join("\n"),
  10563. fragmentShader: [
  10564. "uniform vec3 diffuse;",
  10565. "uniform float opacity;",
  10566. "uniform float dashSize;",
  10567. "uniform float totalSize;",
  10568. "varying float vLineDistance;",
  10569. THREE.ShaderChunk[ "color_pars_fragment" ],
  10570. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10571. "void main() {",
  10572. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10573. "discard;",
  10574. "}",
  10575. "gl_FragColor = vec4( diffuse, opacity );",
  10576. THREE.ShaderChunk[ "color_fragment" ],
  10577. THREE.ShaderChunk[ "fog_fragment" ],
  10578. "}"
  10579. ].join("\n")
  10580. },
  10581. 'depth': {
  10582. uniforms: {
  10583. "mNear": { type: "f", value: 1.0 },
  10584. "mFar" : { type: "f", value: 2000.0 },
  10585. "opacity" : { type: "f", value: 1.0 }
  10586. },
  10587. vertexShader: [
  10588. "void main() {",
  10589. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10590. "}"
  10591. ].join("\n"),
  10592. fragmentShader: [
  10593. "uniform float mNear;",
  10594. "uniform float mFar;",
  10595. "uniform float opacity;",
  10596. "void main() {",
  10597. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10598. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10599. "gl_FragColor = vec4( vec3( color ), opacity );",
  10600. "}"
  10601. ].join("\n")
  10602. },
  10603. 'normal': {
  10604. uniforms: {
  10605. "opacity" : { type: "f", value: 1.0 }
  10606. },
  10607. vertexShader: [
  10608. "varying vec3 vNormal;",
  10609. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10610. "void main() {",
  10611. "vNormal = normalize( normalMatrix * normal );",
  10612. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10613. THREE.ShaderChunk[ "default_vertex" ],
  10614. "}"
  10615. ].join("\n"),
  10616. fragmentShader: [
  10617. "uniform float opacity;",
  10618. "varying vec3 vNormal;",
  10619. "void main() {",
  10620. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10621. "}"
  10622. ].join("\n")
  10623. },
  10624. /* -------------------------------------------------------------------------
  10625. // Normal map shader
  10626. // - Blinn-Phong
  10627. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  10628. // - point and directional lights (use with "lights: true" material option)
  10629. ------------------------------------------------------------------------- */
  10630. 'normalmap' : {
  10631. uniforms: THREE.UniformsUtils.merge( [
  10632. THREE.UniformsLib[ "fog" ],
  10633. THREE.UniformsLib[ "lights" ],
  10634. THREE.UniformsLib[ "shadowmap" ],
  10635. {
  10636. "enableAO" : { type: "i", value: 0 },
  10637. "enableDiffuse" : { type: "i", value: 0 },
  10638. "enableSpecular" : { type: "i", value: 0 },
  10639. "enableReflection": { type: "i", value: 0 },
  10640. "enableDisplacement": { type: "i", value: 0 },
  10641. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  10642. "tDiffuse" : { type: "t", value: null },
  10643. "tCube" : { type: "t", value: null },
  10644. "tNormal" : { type: "t", value: null },
  10645. "tSpecular" : { type: "t", value: null },
  10646. "tAO" : { type: "t", value: null },
  10647. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10648. "uDisplacementBias": { type: "f", value: 0.0 },
  10649. "uDisplacementScale": { type: "f", value: 1.0 },
  10650. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10651. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  10652. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10653. "uShininess": { type: "f", value: 30 },
  10654. "uOpacity": { type: "f", value: 1 },
  10655. "useRefract": { type: "i", value: 0 },
  10656. "uRefractionRatio": { type: "f", value: 0.98 },
  10657. "uReflectivity": { type: "f", value: 0.5 },
  10658. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  10659. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10660. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10661. }
  10662. ] ),
  10663. fragmentShader: [
  10664. "uniform vec3 uAmbientColor;",
  10665. "uniform vec3 uDiffuseColor;",
  10666. "uniform vec3 uSpecularColor;",
  10667. "uniform float uShininess;",
  10668. "uniform float uOpacity;",
  10669. "uniform bool enableDiffuse;",
  10670. "uniform bool enableSpecular;",
  10671. "uniform bool enableAO;",
  10672. "uniform bool enableReflection;",
  10673. "uniform sampler2D tDiffuse;",
  10674. "uniform sampler2D tNormal;",
  10675. "uniform sampler2D tSpecular;",
  10676. "uniform sampler2D tAO;",
  10677. "uniform samplerCube tCube;",
  10678. "uniform vec2 uNormalScale;",
  10679. "uniform bool useRefract;",
  10680. "uniform float uRefractionRatio;",
  10681. "uniform float uReflectivity;",
  10682. "varying vec3 vTangent;",
  10683. "varying vec3 vBinormal;",
  10684. "varying vec3 vNormal;",
  10685. "varying vec2 vUv;",
  10686. "uniform vec3 ambientLightColor;",
  10687. "#if MAX_DIR_LIGHTS > 0",
  10688. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10689. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10690. "#endif",
  10691. "#if MAX_HEMI_LIGHTS > 0",
  10692. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10693. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10694. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10695. "#endif",
  10696. "#if MAX_POINT_LIGHTS > 0",
  10697. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10698. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10699. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10700. "#endif",
  10701. "#if MAX_SPOT_LIGHTS > 0",
  10702. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10703. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10704. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10705. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10706. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10707. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10708. "#endif",
  10709. "#ifdef WRAP_AROUND",
  10710. "uniform vec3 wrapRGB;",
  10711. "#endif",
  10712. "varying vec3 vWorldPosition;",
  10713. "varying vec3 vViewPosition;",
  10714. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10715. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10716. "void main() {",
  10717. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  10718. "vec3 specularTex = vec3( 1.0 );",
  10719. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  10720. "normalTex.xy *= uNormalScale;",
  10721. "normalTex = normalize( normalTex );",
  10722. "if( enableDiffuse ) {",
  10723. "#ifdef GAMMA_INPUT",
  10724. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  10725. "texelColor.xyz *= texelColor.xyz;",
  10726. "gl_FragColor = gl_FragColor * texelColor;",
  10727. "#else",
  10728. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  10729. "#endif",
  10730. "}",
  10731. "if( enableAO ) {",
  10732. "#ifdef GAMMA_INPUT",
  10733. "vec4 aoColor = texture2D( tAO, vUv );",
  10734. "aoColor.xyz *= aoColor.xyz;",
  10735. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  10736. "#else",
  10737. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  10738. "#endif",
  10739. "}",
  10740. "if( enableSpecular )",
  10741. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  10742. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  10743. "vec3 finalNormal = tsb * normalTex;",
  10744. "#ifdef FLIP_SIDED",
  10745. "finalNormal = -finalNormal;",
  10746. "#endif",
  10747. "vec3 normal = normalize( finalNormal );",
  10748. "vec3 viewPosition = normalize( vViewPosition );",
  10749. // point lights
  10750. "#if MAX_POINT_LIGHTS > 0",
  10751. "vec3 pointDiffuse = vec3( 0.0 );",
  10752. "vec3 pointSpecular = vec3( 0.0 );",
  10753. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10754. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10755. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  10756. "float pointDistance = 1.0;",
  10757. "if ( pointLightDistance[ i ] > 0.0 )",
  10758. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  10759. "pointVector = normalize( pointVector );",
  10760. // diffuse
  10761. "#ifdef WRAP_AROUND",
  10762. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  10763. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  10764. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10765. "#else",
  10766. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  10767. "#endif",
  10768. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  10769. // specular
  10770. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  10771. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10772. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  10773. "#ifdef PHYSICALLY_BASED_SHADING",
  10774. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10775. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10776. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  10777. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  10778. "#else",
  10779. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  10780. "#endif",
  10781. "}",
  10782. "#endif",
  10783. // spot lights
  10784. "#if MAX_SPOT_LIGHTS > 0",
  10785. "vec3 spotDiffuse = vec3( 0.0 );",
  10786. "vec3 spotSpecular = vec3( 0.0 );",
  10787. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10788. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10789. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  10790. "float spotDistance = 1.0;",
  10791. "if ( spotLightDistance[ i ] > 0.0 )",
  10792. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  10793. "spotVector = normalize( spotVector );",
  10794. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10795. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10796. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10797. // diffuse
  10798. "#ifdef WRAP_AROUND",
  10799. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  10800. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  10801. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10802. "#else",
  10803. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  10804. "#endif",
  10805. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  10806. // specular
  10807. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  10808. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10809. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  10810. "#ifdef PHYSICALLY_BASED_SHADING",
  10811. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10812. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10813. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  10814. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  10815. "#else",
  10816. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  10817. "#endif",
  10818. "}",
  10819. "}",
  10820. "#endif",
  10821. // directional lights
  10822. "#if MAX_DIR_LIGHTS > 0",
  10823. "vec3 dirDiffuse = vec3( 0.0 );",
  10824. "vec3 dirSpecular = vec3( 0.0 );",
  10825. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  10826. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10827. "vec3 dirVector = normalize( lDirection.xyz );",
  10828. // diffuse
  10829. "#ifdef WRAP_AROUND",
  10830. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  10831. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  10832. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  10833. "#else",
  10834. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  10835. "#endif",
  10836. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  10837. // specular
  10838. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10839. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10840. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  10841. "#ifdef PHYSICALLY_BASED_SHADING",
  10842. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10843. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10844. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10845. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10846. "#else",
  10847. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  10848. "#endif",
  10849. "}",
  10850. "#endif",
  10851. // hemisphere lights
  10852. "#if MAX_HEMI_LIGHTS > 0",
  10853. "vec3 hemiDiffuse = vec3( 0.0 );",
  10854. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10855. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10856. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10857. "vec3 lVector = normalize( lDirection.xyz );",
  10858. // diffuse
  10859. "float dotProduct = dot( normal, lVector );",
  10860. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10861. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10862. "hemiDiffuse += uDiffuseColor * hemiColor;",
  10863. // specular (sky light)
  10864. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10865. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10866. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  10867. // specular (ground light)
  10868. "vec3 lVectorGround = -lVector;",
  10869. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10870. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10871. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  10872. "#ifdef PHYSICALLY_BASED_SHADING",
  10873. "float dotProductGround = dot( normal, lVectorGround );",
  10874. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10875. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10876. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10877. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10878. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10879. "#else",
  10880. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10881. "#endif",
  10882. "}",
  10883. "#endif",
  10884. // all lights contribution summation
  10885. "vec3 totalDiffuse = vec3( 0.0 );",
  10886. "vec3 totalSpecular = vec3( 0.0 );",
  10887. "#if MAX_DIR_LIGHTS > 0",
  10888. "totalDiffuse += dirDiffuse;",
  10889. "totalSpecular += dirSpecular;",
  10890. "#endif",
  10891. "#if MAX_HEMI_LIGHTS > 0",
  10892. "totalDiffuse += hemiDiffuse;",
  10893. "totalSpecular += hemiSpecular;",
  10894. "#endif",
  10895. "#if MAX_POINT_LIGHTS > 0",
  10896. "totalDiffuse += pointDiffuse;",
  10897. "totalSpecular += pointSpecular;",
  10898. "#endif",
  10899. "#if MAX_SPOT_LIGHTS > 0",
  10900. "totalDiffuse += spotDiffuse;",
  10901. "totalSpecular += spotSpecular;",
  10902. "#endif",
  10903. "#ifdef METAL",
  10904. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  10905. "#else",
  10906. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  10907. "#endif",
  10908. "if ( enableReflection ) {",
  10909. "vec3 vReflect;",
  10910. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10911. "if ( useRefract ) {",
  10912. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  10913. "} else {",
  10914. "vReflect = reflect( cameraToVertex, normal );",
  10915. "}",
  10916. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  10917. "#ifdef GAMMA_INPUT",
  10918. "cubeColor.xyz *= cubeColor.xyz;",
  10919. "#endif",
  10920. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  10921. "}",
  10922. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10923. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10924. THREE.ShaderChunk[ "fog_fragment" ],
  10925. "}"
  10926. ].join("\n"),
  10927. vertexShader: [
  10928. "attribute vec4 tangent;",
  10929. "uniform vec2 uOffset;",
  10930. "uniform vec2 uRepeat;",
  10931. "uniform bool enableDisplacement;",
  10932. "#ifdef VERTEX_TEXTURES",
  10933. "uniform sampler2D tDisplacement;",
  10934. "uniform float uDisplacementScale;",
  10935. "uniform float uDisplacementBias;",
  10936. "#endif",
  10937. "varying vec3 vTangent;",
  10938. "varying vec3 vBinormal;",
  10939. "varying vec3 vNormal;",
  10940. "varying vec2 vUv;",
  10941. "varying vec3 vWorldPosition;",
  10942. "varying vec3 vViewPosition;",
  10943. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10944. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10945. "void main() {",
  10946. THREE.ShaderChunk[ "skinbase_vertex" ],
  10947. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10948. // normal, tangent and binormal vectors
  10949. "#ifdef USE_SKINNING",
  10950. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  10951. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  10952. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  10953. "#else",
  10954. "vNormal = normalize( normalMatrix * normal );",
  10955. "vTangent = normalize( normalMatrix * tangent.xyz );",
  10956. "#endif",
  10957. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  10958. "vUv = uv * uRepeat + uOffset;",
  10959. // displacement mapping
  10960. "vec3 displacedPosition;",
  10961. "#ifdef VERTEX_TEXTURES",
  10962. "if ( enableDisplacement ) {",
  10963. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  10964. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  10965. "displacedPosition = position + normalize( normal ) * df;",
  10966. "} else {",
  10967. "#ifdef USE_SKINNING",
  10968. "vec4 skinVertex = vec4( position, 1.0 );",
  10969. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10970. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10971. "displacedPosition = skinned.xyz;",
  10972. "#else",
  10973. "displacedPosition = position;",
  10974. "#endif",
  10975. "}",
  10976. "#else",
  10977. "#ifdef USE_SKINNING",
  10978. "vec4 skinVertex = vec4( position, 1.0 );",
  10979. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10980. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10981. "displacedPosition = skinned.xyz;",
  10982. "#else",
  10983. "displacedPosition = position;",
  10984. "#endif",
  10985. "#endif",
  10986. //
  10987. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  10988. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  10989. "gl_Position = projectionMatrix * mvPosition;",
  10990. //
  10991. "vWorldPosition = worldPosition.xyz;",
  10992. "vViewPosition = -mvPosition.xyz;",
  10993. // shadows
  10994. "#ifdef USE_SHADOWMAP",
  10995. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10996. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10997. "}",
  10998. "#endif",
  10999. "}"
  11000. ].join("\n")
  11001. },
  11002. /* -------------------------------------------------------------------------
  11003. // Cube map shader
  11004. ------------------------------------------------------------------------- */
  11005. 'cube': {
  11006. uniforms: { "tCube": { type: "t", value: null },
  11007. "tFlip": { type: "f", value: -1 } },
  11008. vertexShader: [
  11009. "varying vec3 vWorldPosition;",
  11010. "void main() {",
  11011. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11012. "vWorldPosition = worldPosition.xyz;",
  11013. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11014. "}"
  11015. ].join("\n"),
  11016. fragmentShader: [
  11017. "uniform samplerCube tCube;",
  11018. "uniform float tFlip;",
  11019. "varying vec3 vWorldPosition;",
  11020. "void main() {",
  11021. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11022. "}"
  11023. ].join("\n")
  11024. },
  11025. // Depth encoding into RGBA texture
  11026. // based on SpiderGL shadow map example
  11027. // http://spidergl.org/example.php?id=6
  11028. // originally from
  11029. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11030. // see also here:
  11031. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11032. 'depthRGBA': {
  11033. uniforms: {},
  11034. vertexShader: [
  11035. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11036. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11037. "void main() {",
  11038. THREE.ShaderChunk[ "skinbase_vertex" ],
  11039. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11040. THREE.ShaderChunk[ "skinning_vertex" ],
  11041. THREE.ShaderChunk[ "default_vertex" ],
  11042. "}"
  11043. ].join("\n"),
  11044. fragmentShader: [
  11045. "vec4 pack_depth( const in float depth ) {",
  11046. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11047. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11048. "vec4 res = fract( depth * bit_shift );",
  11049. "res -= res.xxyz * bit_mask;",
  11050. "return res;",
  11051. "}",
  11052. "void main() {",
  11053. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11054. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11055. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11056. //"gl_FragData[ 0 ] = pack_depth( z );",
  11057. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11058. "}"
  11059. ].join("\n")
  11060. }
  11061. };
  11062. /**
  11063. * @author supereggbert / http://www.paulbrunt.co.uk/
  11064. * @author mrdoob / http://mrdoob.com/
  11065. * @author alteredq / http://alteredqualia.com/
  11066. * @author szimek / https://github.com/szimek/
  11067. */
  11068. THREE.WebGLRenderer = function ( parameters ) {
  11069. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11070. parameters = parameters || {};
  11071. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11072. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11073. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  11074. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11075. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11076. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11077. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11078. _clearColor = new THREE.Color( 0x000000 ),
  11079. _clearAlpha = 0;
  11080. if ( parameters.clearColor !== undefined ) {
  11081. console.warn( 'DEPRECATED: clearColor in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  11082. _clearColor.setHex( parameters.clearColor );
  11083. }
  11084. if ( parameters.clearAlpha !== undefined ) {
  11085. console.warn( 'DEPRECATED: clearAlpha in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  11086. _clearAlpha = parameters.clearAlpha;
  11087. }
  11088. // public properties
  11089. this.domElement = _canvas;
  11090. this.context = null;
  11091. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11092. ? parameters.devicePixelRatio
  11093. : window.devicePixelRatio !== undefined
  11094. ? window.devicePixelRatio
  11095. : 1;
  11096. // clearing
  11097. this.autoClear = true;
  11098. this.autoClearColor = true;
  11099. this.autoClearDepth = true;
  11100. this.autoClearStencil = true;
  11101. // scene graph
  11102. this.sortObjects = true;
  11103. this.autoUpdateObjects = true;
  11104. // physically based shading
  11105. this.gammaInput = false;
  11106. this.gammaOutput = false;
  11107. this.physicallyBasedShading = false;
  11108. // shadow map
  11109. this.shadowMapEnabled = false;
  11110. this.shadowMapAutoUpdate = true;
  11111. this.shadowMapType = THREE.PCFShadowMap;
  11112. this.shadowMapCullFace = THREE.CullFaceFront;
  11113. this.shadowMapDebug = false;
  11114. this.shadowMapCascade = false;
  11115. // morphs
  11116. this.maxMorphTargets = 8;
  11117. this.maxMorphNormals = 4;
  11118. // flags
  11119. this.autoScaleCubemaps = true;
  11120. // custom render plugins
  11121. this.renderPluginsPre = [];
  11122. this.renderPluginsPost = [];
  11123. // info
  11124. this.info = {
  11125. memory: {
  11126. programs: 0,
  11127. geometries: 0,
  11128. textures: 0
  11129. },
  11130. render: {
  11131. calls: 0,
  11132. vertices: 0,
  11133. faces: 0,
  11134. points: 0
  11135. }
  11136. };
  11137. // internal properties
  11138. var _this = this,
  11139. _programs = [],
  11140. _programs_counter = 0,
  11141. // internal state cache
  11142. _currentProgram = null,
  11143. _currentFramebuffer = null,
  11144. _currentMaterialId = -1,
  11145. _currentGeometryGroupHash = null,
  11146. _currentCamera = null,
  11147. _geometryGroupCounter = 0,
  11148. _usedTextureUnits = 0,
  11149. // GL state cache
  11150. _oldDoubleSided = -1,
  11151. _oldFlipSided = -1,
  11152. _oldBlending = -1,
  11153. _oldBlendEquation = -1,
  11154. _oldBlendSrc = -1,
  11155. _oldBlendDst = -1,
  11156. _oldDepthTest = -1,
  11157. _oldDepthWrite = -1,
  11158. _oldPolygonOffset = null,
  11159. _oldPolygonOffsetFactor = null,
  11160. _oldPolygonOffsetUnits = null,
  11161. _oldLineWidth = null,
  11162. _viewportX = 0,
  11163. _viewportY = 0,
  11164. _viewportWidth = 0,
  11165. _viewportHeight = 0,
  11166. _currentWidth = 0,
  11167. _currentHeight = 0,
  11168. _enabledAttributes = {},
  11169. // frustum
  11170. _frustum = new THREE.Frustum(),
  11171. // camera matrices cache
  11172. _projScreenMatrix = new THREE.Matrix4(),
  11173. _projScreenMatrixPS = new THREE.Matrix4(),
  11174. _vector3 = new THREE.Vector3(),
  11175. // light arrays cache
  11176. _direction = new THREE.Vector3(),
  11177. _lightsNeedUpdate = true,
  11178. _lights = {
  11179. ambient: [ 0, 0, 0 ],
  11180. directional: { length: 0, colors: new Array(), positions: new Array() },
  11181. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11182. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11183. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11184. };
  11185. // initialize
  11186. var _gl;
  11187. var _glExtensionTextureFloat;
  11188. var _glExtensionStandardDerivatives;
  11189. var _glExtensionTextureFilterAnisotropic;
  11190. var _glExtensionCompressedTextureS3TC;
  11191. initGL();
  11192. setDefaultGLState();
  11193. this.context = _gl;
  11194. // GPU capabilities
  11195. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11196. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11197. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11198. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11199. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11200. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11201. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11202. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11203. //
  11204. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11205. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11206. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11207. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11208. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11209. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11210. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11211. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11212. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11213. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11214. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11215. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11216. // clamp precision to maximum available
  11217. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11218. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11219. if ( _precision === "highp" && ! highpAvailable ) {
  11220. if ( mediumpAvailable ) {
  11221. _precision = "mediump";
  11222. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11223. } else {
  11224. _precision = "lowp";
  11225. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11226. }
  11227. }
  11228. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11229. _precision = "lowp";
  11230. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11231. }
  11232. // API
  11233. this.getContext = function () {
  11234. return _gl;
  11235. };
  11236. this.supportsVertexTextures = function () {
  11237. return _supportsVertexTextures;
  11238. };
  11239. this.supportsFloatTextures = function () {
  11240. return _glExtensionTextureFloat;
  11241. };
  11242. this.supportsStandardDerivatives = function () {
  11243. return _glExtensionStandardDerivatives;
  11244. };
  11245. this.supportsCompressedTextureS3TC = function () {
  11246. return _glExtensionCompressedTextureS3TC;
  11247. };
  11248. this.getMaxAnisotropy = function () {
  11249. return _maxAnisotropy;
  11250. };
  11251. this.getPrecision = function () {
  11252. return _precision;
  11253. };
  11254. this.setSize = function ( width, height, updateStyle ) {
  11255. _canvas.width = width * this.devicePixelRatio;
  11256. _canvas.height = height * this.devicePixelRatio;
  11257. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11258. _canvas.style.width = width + 'px';
  11259. _canvas.style.height = height + 'px';
  11260. }
  11261. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  11262. };
  11263. this.setViewport = function ( x, y, width, height ) {
  11264. _viewportX = x !== undefined ? x : 0;
  11265. _viewportY = y !== undefined ? y : 0;
  11266. _viewportWidth = width !== undefined ? width : _canvas.width;
  11267. _viewportHeight = height !== undefined ? height : _canvas.height;
  11268. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11269. };
  11270. this.setScissor = function ( x, y, width, height ) {
  11271. _gl.scissor( x, y, width, height );
  11272. };
  11273. this.enableScissorTest = function ( enable ) {
  11274. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11275. };
  11276. // Clearing
  11277. this.setClearColor = function ( color, alpha ) {
  11278. _clearColor.set( color );
  11279. _clearAlpha = alpha !== undefined ? alpha : 1;
  11280. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11281. };
  11282. this.setClearColorHex = function ( hex, alpha ) {
  11283. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11284. this.setClearColor( hex, alpha );
  11285. };
  11286. this.getClearColor = function () {
  11287. return _clearColor;
  11288. };
  11289. this.getClearAlpha = function () {
  11290. return _clearAlpha;
  11291. };
  11292. this.clear = function ( color, depth, stencil ) {
  11293. var bits = 0;
  11294. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11295. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11296. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11297. _gl.clear( bits );
  11298. };
  11299. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11300. this.setRenderTarget( renderTarget );
  11301. this.clear( color, depth, stencil );
  11302. };
  11303. // Plugins
  11304. this.addPostPlugin = function ( plugin ) {
  11305. plugin.init( this );
  11306. this.renderPluginsPost.push( plugin );
  11307. };
  11308. this.addPrePlugin = function ( plugin ) {
  11309. plugin.init( this );
  11310. this.renderPluginsPre.push( plugin );
  11311. };
  11312. // Rendering
  11313. this.updateShadowMap = function ( scene, camera ) {
  11314. _currentProgram = null;
  11315. _oldBlending = -1;
  11316. _oldDepthTest = -1;
  11317. _oldDepthWrite = -1;
  11318. _currentGeometryGroupHash = -1;
  11319. _currentMaterialId = -1;
  11320. _lightsNeedUpdate = true;
  11321. _oldDoubleSided = -1;
  11322. _oldFlipSided = -1;
  11323. this.shadowMapPlugin.update( scene, camera );
  11324. };
  11325. // Internal functions
  11326. // Buffer allocation
  11327. function createParticleBuffers ( geometry ) {
  11328. geometry.__webglVertexBuffer = _gl.createBuffer();
  11329. geometry.__webglColorBuffer = _gl.createBuffer();
  11330. _this.info.memory.geometries ++;
  11331. };
  11332. function createLineBuffers ( geometry ) {
  11333. geometry.__webglVertexBuffer = _gl.createBuffer();
  11334. geometry.__webglColorBuffer = _gl.createBuffer();
  11335. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11336. _this.info.memory.geometries ++;
  11337. };
  11338. function createRibbonBuffers ( geometry ) {
  11339. geometry.__webglVertexBuffer = _gl.createBuffer();
  11340. geometry.__webglColorBuffer = _gl.createBuffer();
  11341. geometry.__webglNormalBuffer = _gl.createBuffer();
  11342. _this.info.memory.geometries ++;
  11343. };
  11344. function createMeshBuffers ( geometryGroup ) {
  11345. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11346. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11347. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11348. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11349. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11350. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11351. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11352. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11353. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11354. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11355. var m, ml;
  11356. if ( geometryGroup.numMorphTargets ) {
  11357. geometryGroup.__webglMorphTargetsBuffers = [];
  11358. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11359. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11360. }
  11361. }
  11362. if ( geometryGroup.numMorphNormals ) {
  11363. geometryGroup.__webglMorphNormalsBuffers = [];
  11364. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11365. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11366. }
  11367. }
  11368. _this.info.memory.geometries ++;
  11369. };
  11370. // Events
  11371. var onGeometryDispose = function ( event ) {
  11372. var geometry = event.target;
  11373. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11374. deallocateGeometry( geometry );
  11375. _this.info.memory.geometries --;
  11376. };
  11377. var onTextureDispose = function ( event ) {
  11378. var texture = event.target;
  11379. texture.removeEventListener( 'dispose', onTextureDispose );
  11380. deallocateTexture( texture );
  11381. _this.info.memory.textures --;
  11382. };
  11383. var onRenderTargetDispose = function ( event ) {
  11384. var renderTarget = event.target;
  11385. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11386. deallocateRenderTarget( renderTarget );
  11387. _this.info.memory.textures --;
  11388. };
  11389. var onMaterialDispose = function ( event ) {
  11390. var material = event.target;
  11391. material.removeEventListener( 'dispose', onMaterialDispose );
  11392. deallocateMaterial( material );
  11393. };
  11394. // Buffer deallocation
  11395. var deallocateGeometry = function ( geometry ) {
  11396. geometry.__webglInit = undefined;
  11397. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11398. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11399. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11400. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11401. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11402. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11403. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11404. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11405. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11406. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11407. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11408. // geometry groups
  11409. if ( geometry.geometryGroups !== undefined ) {
  11410. for ( var g in geometry.geometryGroups ) {
  11411. var geometryGroup = geometry.geometryGroups[ g ];
  11412. if ( geometryGroup.numMorphTargets !== undefined ) {
  11413. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11414. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11415. }
  11416. }
  11417. if ( geometryGroup.numMorphNormals !== undefined ) {
  11418. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11419. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11420. }
  11421. }
  11422. deleteCustomAttributesBuffers( geometryGroup );
  11423. }
  11424. }
  11425. deleteCustomAttributesBuffers( geometry );
  11426. };
  11427. var deallocateTexture = function ( texture ) {
  11428. if ( texture.image && texture.image.__webglTextureCube ) {
  11429. // cube texture
  11430. _gl.deleteTexture( texture.image.__webglTextureCube );
  11431. } else {
  11432. // 2D texture
  11433. if ( ! texture.__webglInit ) return;
  11434. texture.__webglInit = false;
  11435. _gl.deleteTexture( texture.__webglTexture );
  11436. }
  11437. };
  11438. var deallocateRenderTarget = function ( renderTarget ) {
  11439. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11440. _gl.deleteTexture( renderTarget.__webglTexture );
  11441. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11442. for ( var i = 0; i < 6; i ++ ) {
  11443. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11444. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11445. }
  11446. } else {
  11447. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11448. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11449. }
  11450. };
  11451. var deallocateMaterial = function ( material ) {
  11452. var program = material.program;
  11453. if ( program === undefined ) return;
  11454. material.program = undefined;
  11455. // only deallocate GL program if this was the last use of shared program
  11456. // assumed there is only single copy of any program in the _programs list
  11457. // (that's how it's constructed)
  11458. var i, il, programInfo;
  11459. var deleteProgram = false;
  11460. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11461. programInfo = _programs[ i ];
  11462. if ( programInfo.program === program ) {
  11463. programInfo.usedTimes --;
  11464. if ( programInfo.usedTimes === 0 ) {
  11465. deleteProgram = true;
  11466. }
  11467. break;
  11468. }
  11469. }
  11470. if ( deleteProgram === true ) {
  11471. // avoid using array.splice, this is costlier than creating new array from scratch
  11472. var newPrograms = [];
  11473. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11474. programInfo = _programs[ i ];
  11475. if ( programInfo.program !== program ) {
  11476. newPrograms.push( programInfo );
  11477. }
  11478. }
  11479. _programs = newPrograms;
  11480. _gl.deleteProgram( program );
  11481. _this.info.memory.programs --;
  11482. }
  11483. };
  11484. //
  11485. function deleteCustomAttributesBuffers( geometry ) {
  11486. if ( geometry.__webglCustomAttributesList ) {
  11487. for ( var id in geometry.__webglCustomAttributesList ) {
  11488. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11489. }
  11490. }
  11491. };
  11492. // Buffer initialization
  11493. function initCustomAttributes ( geometry, object ) {
  11494. var nvertices = geometry.vertices.length;
  11495. var material = object.material;
  11496. if ( material.attributes ) {
  11497. if ( geometry.__webglCustomAttributesList === undefined ) {
  11498. geometry.__webglCustomAttributesList = [];
  11499. }
  11500. for ( var a in material.attributes ) {
  11501. var attribute = material.attributes[ a ];
  11502. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11503. attribute.__webglInitialized = true;
  11504. var size = 1; // "f" and "i"
  11505. if ( attribute.type === "v2" ) size = 2;
  11506. else if ( attribute.type === "v3" ) size = 3;
  11507. else if ( attribute.type === "v4" ) size = 4;
  11508. else if ( attribute.type === "c" ) size = 3;
  11509. attribute.size = size;
  11510. attribute.array = new Float32Array( nvertices * size );
  11511. attribute.buffer = _gl.createBuffer();
  11512. attribute.buffer.belongsToAttribute = a;
  11513. attribute.needsUpdate = true;
  11514. }
  11515. geometry.__webglCustomAttributesList.push( attribute );
  11516. }
  11517. }
  11518. };
  11519. function initParticleBuffers ( geometry, object ) {
  11520. var nvertices = geometry.vertices.length;
  11521. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11522. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11523. geometry.__sortArray = [];
  11524. geometry.__webglParticleCount = nvertices;
  11525. initCustomAttributes ( geometry, object );
  11526. };
  11527. function initLineBuffers ( geometry, object ) {
  11528. var nvertices = geometry.vertices.length;
  11529. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11530. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11531. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  11532. geometry.__webglLineCount = nvertices;
  11533. initCustomAttributes ( geometry, object );
  11534. };
  11535. function initRibbonBuffers ( geometry, object ) {
  11536. var nvertices = geometry.vertices.length;
  11537. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11538. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11539. geometry.__normalArray = new Float32Array( nvertices * 3 );
  11540. geometry.__webglVertexCount = nvertices;
  11541. initCustomAttributes ( geometry, object );
  11542. };
  11543. function initMeshBuffers ( geometryGroup, object ) {
  11544. var geometry = object.geometry,
  11545. faces3 = geometryGroup.faces3,
  11546. faces4 = geometryGroup.faces4,
  11547. nvertices = faces3.length * 3 + faces4.length * 4,
  11548. ntris = faces3.length * 1 + faces4.length * 2,
  11549. nlines = faces3.length * 3 + faces4.length * 4,
  11550. material = getBufferMaterial( object, geometryGroup ),
  11551. uvType = bufferGuessUVType( material ),
  11552. normalType = bufferGuessNormalType( material ),
  11553. vertexColorType = bufferGuessVertexColorType( material );
  11554. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  11555. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  11556. if ( normalType ) {
  11557. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11558. }
  11559. if ( geometry.hasTangents ) {
  11560. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11561. }
  11562. if ( vertexColorType ) {
  11563. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11564. }
  11565. if ( uvType ) {
  11566. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  11567. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11568. }
  11569. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  11570. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11571. }
  11572. }
  11573. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11574. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11575. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11576. }
  11577. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  11578. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  11579. var m, ml;
  11580. if ( geometryGroup.numMorphTargets ) {
  11581. geometryGroup.__morphTargetsArrays = [];
  11582. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11583. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11584. }
  11585. }
  11586. if ( geometryGroup.numMorphNormals ) {
  11587. geometryGroup.__morphNormalsArrays = [];
  11588. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11589. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11590. }
  11591. }
  11592. geometryGroup.__webglFaceCount = ntris * 3;
  11593. geometryGroup.__webglLineCount = nlines * 2;
  11594. // custom attributes
  11595. if ( material.attributes ) {
  11596. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11597. geometryGroup.__webglCustomAttributesList = [];
  11598. }
  11599. for ( var a in material.attributes ) {
  11600. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11601. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11602. var originalAttribute = material.attributes[ a ];
  11603. var attribute = {};
  11604. for ( var property in originalAttribute ) {
  11605. attribute[ property ] = originalAttribute[ property ];
  11606. }
  11607. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11608. attribute.__webglInitialized = true;
  11609. var size = 1; // "f" and "i"
  11610. if( attribute.type === "v2" ) size = 2;
  11611. else if( attribute.type === "v3" ) size = 3;
  11612. else if( attribute.type === "v4" ) size = 4;
  11613. else if( attribute.type === "c" ) size = 3;
  11614. attribute.size = size;
  11615. attribute.array = new Float32Array( nvertices * size );
  11616. attribute.buffer = _gl.createBuffer();
  11617. attribute.buffer.belongsToAttribute = a;
  11618. originalAttribute.needsUpdate = true;
  11619. attribute.__original = originalAttribute;
  11620. }
  11621. geometryGroup.__webglCustomAttributesList.push( attribute );
  11622. }
  11623. }
  11624. geometryGroup.__inittedArrays = true;
  11625. };
  11626. function getBufferMaterial( object, geometryGroup ) {
  11627. return object.material instanceof THREE.MeshFaceMaterial
  11628. ? object.material.materials[ geometryGroup.materialIndex ]
  11629. : object.material;
  11630. };
  11631. function materialNeedsSmoothNormals ( material ) {
  11632. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  11633. };
  11634. function bufferGuessNormalType ( material ) {
  11635. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  11636. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  11637. return false;
  11638. }
  11639. if ( materialNeedsSmoothNormals( material ) ) {
  11640. return THREE.SmoothShading;
  11641. } else {
  11642. return THREE.FlatShading;
  11643. }
  11644. };
  11645. function bufferGuessVertexColorType( material ) {
  11646. if ( material.vertexColors ) {
  11647. return material.vertexColors;
  11648. }
  11649. return false;
  11650. };
  11651. function bufferGuessUVType( material ) {
  11652. // material must use some texture to require uvs
  11653. if ( material.map ||
  11654. material.lightMap ||
  11655. material.bumpMap ||
  11656. material.normalMap ||
  11657. material.specularMap ||
  11658. material instanceof THREE.ShaderMaterial ) {
  11659. return true;
  11660. }
  11661. return false;
  11662. };
  11663. //
  11664. function initDirectBuffers( geometry ) {
  11665. var a, attribute, type;
  11666. for ( a in geometry.attributes ) {
  11667. if ( a === "index" ) {
  11668. type = _gl.ELEMENT_ARRAY_BUFFER;
  11669. } else {
  11670. type = _gl.ARRAY_BUFFER;
  11671. }
  11672. attribute = geometry.attributes[ a ];
  11673. attribute.buffer = _gl.createBuffer();
  11674. _gl.bindBuffer( type, attribute.buffer );
  11675. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  11676. }
  11677. };
  11678. // Buffer setting
  11679. function setParticleBuffers ( geometry, hint, object ) {
  11680. var v, c, vertex, offset, index, color,
  11681. vertices = geometry.vertices,
  11682. vl = vertices.length,
  11683. colors = geometry.colors,
  11684. cl = colors.length,
  11685. vertexArray = geometry.__vertexArray,
  11686. colorArray = geometry.__colorArray,
  11687. sortArray = geometry.__sortArray,
  11688. dirtyVertices = geometry.verticesNeedUpdate,
  11689. dirtyElements = geometry.elementsNeedUpdate,
  11690. dirtyColors = geometry.colorsNeedUpdate,
  11691. customAttributes = geometry.__webglCustomAttributesList,
  11692. i, il,
  11693. a, ca, cal, value,
  11694. customAttribute;
  11695. if ( object.sortParticles ) {
  11696. _projScreenMatrixPS.copy( _projScreenMatrix );
  11697. _projScreenMatrixPS.multiply( object.matrixWorld );
  11698. for ( v = 0; v < vl; v ++ ) {
  11699. vertex = vertices[ v ];
  11700. _vector3.copy( vertex );
  11701. _vector3.applyProjection( _projScreenMatrixPS );
  11702. sortArray[ v ] = [ _vector3.z, v ];
  11703. }
  11704. sortArray.sort( numericalSort );
  11705. for ( v = 0; v < vl; v ++ ) {
  11706. vertex = vertices[ sortArray[v][1] ];
  11707. offset = v * 3;
  11708. vertexArray[ offset ] = vertex.x;
  11709. vertexArray[ offset + 1 ] = vertex.y;
  11710. vertexArray[ offset + 2 ] = vertex.z;
  11711. }
  11712. for ( c = 0; c < cl; c ++ ) {
  11713. offset = c * 3;
  11714. color = colors[ sortArray[c][1] ];
  11715. colorArray[ offset ] = color.r;
  11716. colorArray[ offset + 1 ] = color.g;
  11717. colorArray[ offset + 2 ] = color.b;
  11718. }
  11719. if ( customAttributes ) {
  11720. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11721. customAttribute = customAttributes[ i ];
  11722. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  11723. offset = 0;
  11724. cal = customAttribute.value.length;
  11725. if ( customAttribute.size === 1 ) {
  11726. for ( ca = 0; ca < cal; ca ++ ) {
  11727. index = sortArray[ ca ][ 1 ];
  11728. customAttribute.array[ ca ] = customAttribute.value[ index ];
  11729. }
  11730. } else if ( customAttribute.size === 2 ) {
  11731. for ( ca = 0; ca < cal; ca ++ ) {
  11732. index = sortArray[ ca ][ 1 ];
  11733. value = customAttribute.value[ index ];
  11734. customAttribute.array[ offset ] = value.x;
  11735. customAttribute.array[ offset + 1 ] = value.y;
  11736. offset += 2;
  11737. }
  11738. } else if ( customAttribute.size === 3 ) {
  11739. if ( customAttribute.type === "c" ) {
  11740. for ( ca = 0; ca < cal; ca ++ ) {
  11741. index = sortArray[ ca ][ 1 ];
  11742. value = customAttribute.value[ index ];
  11743. customAttribute.array[ offset ] = value.r;
  11744. customAttribute.array[ offset + 1 ] = value.g;
  11745. customAttribute.array[ offset + 2 ] = value.b;
  11746. offset += 3;
  11747. }
  11748. } else {
  11749. for ( ca = 0; ca < cal; ca ++ ) {
  11750. index = sortArray[ ca ][ 1 ];
  11751. value = customAttribute.value[ index ];
  11752. customAttribute.array[ offset ] = value.x;
  11753. customAttribute.array[ offset + 1 ] = value.y;
  11754. customAttribute.array[ offset + 2 ] = value.z;
  11755. offset += 3;
  11756. }
  11757. }
  11758. } else if ( customAttribute.size === 4 ) {
  11759. for ( ca = 0; ca < cal; ca ++ ) {
  11760. index = sortArray[ ca ][ 1 ];
  11761. value = customAttribute.value[ index ];
  11762. customAttribute.array[ offset ] = value.x;
  11763. customAttribute.array[ offset + 1 ] = value.y;
  11764. customAttribute.array[ offset + 2 ] = value.z;
  11765. customAttribute.array[ offset + 3 ] = value.w;
  11766. offset += 4;
  11767. }
  11768. }
  11769. }
  11770. }
  11771. } else {
  11772. if ( dirtyVertices ) {
  11773. for ( v = 0; v < vl; v ++ ) {
  11774. vertex = vertices[ v ];
  11775. offset = v * 3;
  11776. vertexArray[ offset ] = vertex.x;
  11777. vertexArray[ offset + 1 ] = vertex.y;
  11778. vertexArray[ offset + 2 ] = vertex.z;
  11779. }
  11780. }
  11781. if ( dirtyColors ) {
  11782. for ( c = 0; c < cl; c ++ ) {
  11783. color = colors[ c ];
  11784. offset = c * 3;
  11785. colorArray[ offset ] = color.r;
  11786. colorArray[ offset + 1 ] = color.g;
  11787. colorArray[ offset + 2 ] = color.b;
  11788. }
  11789. }
  11790. if ( customAttributes ) {
  11791. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11792. customAttribute = customAttributes[ i ];
  11793. if ( customAttribute.needsUpdate &&
  11794. ( customAttribute.boundTo === undefined ||
  11795. customAttribute.boundTo === "vertices") ) {
  11796. cal = customAttribute.value.length;
  11797. offset = 0;
  11798. if ( customAttribute.size === 1 ) {
  11799. for ( ca = 0; ca < cal; ca ++ ) {
  11800. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11801. }
  11802. } else if ( customAttribute.size === 2 ) {
  11803. for ( ca = 0; ca < cal; ca ++ ) {
  11804. value = customAttribute.value[ ca ];
  11805. customAttribute.array[ offset ] = value.x;
  11806. customAttribute.array[ offset + 1 ] = value.y;
  11807. offset += 2;
  11808. }
  11809. } else if ( customAttribute.size === 3 ) {
  11810. if ( customAttribute.type === "c" ) {
  11811. for ( ca = 0; ca < cal; ca ++ ) {
  11812. value = customAttribute.value[ ca ];
  11813. customAttribute.array[ offset ] = value.r;
  11814. customAttribute.array[ offset + 1 ] = value.g;
  11815. customAttribute.array[ offset + 2 ] = value.b;
  11816. offset += 3;
  11817. }
  11818. } else {
  11819. for ( ca = 0; ca < cal; ca ++ ) {
  11820. value = customAttribute.value[ ca ];
  11821. customAttribute.array[ offset ] = value.x;
  11822. customAttribute.array[ offset + 1 ] = value.y;
  11823. customAttribute.array[ offset + 2 ] = value.z;
  11824. offset += 3;
  11825. }
  11826. }
  11827. } else if ( customAttribute.size === 4 ) {
  11828. for ( ca = 0; ca < cal; ca ++ ) {
  11829. value = customAttribute.value[ ca ];
  11830. customAttribute.array[ offset ] = value.x;
  11831. customAttribute.array[ offset + 1 ] = value.y;
  11832. customAttribute.array[ offset + 2 ] = value.z;
  11833. customAttribute.array[ offset + 3 ] = value.w;
  11834. offset += 4;
  11835. }
  11836. }
  11837. }
  11838. }
  11839. }
  11840. }
  11841. if ( dirtyVertices || object.sortParticles ) {
  11842. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11843. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11844. }
  11845. if ( dirtyColors || object.sortParticles ) {
  11846. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11847. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11848. }
  11849. if ( customAttributes ) {
  11850. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11851. customAttribute = customAttributes[ i ];
  11852. if ( customAttribute.needsUpdate || object.sortParticles ) {
  11853. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11854. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11855. }
  11856. }
  11857. }
  11858. };
  11859. function setLineBuffers ( geometry, hint ) {
  11860. var v, c, d, vertex, offset, color,
  11861. vertices = geometry.vertices,
  11862. colors = geometry.colors,
  11863. lineDistances = geometry.lineDistances,
  11864. vl = vertices.length,
  11865. cl = colors.length,
  11866. dl = lineDistances.length,
  11867. vertexArray = geometry.__vertexArray,
  11868. colorArray = geometry.__colorArray,
  11869. lineDistanceArray = geometry.__lineDistanceArray,
  11870. dirtyVertices = geometry.verticesNeedUpdate,
  11871. dirtyColors = geometry.colorsNeedUpdate,
  11872. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  11873. customAttributes = geometry.__webglCustomAttributesList,
  11874. i, il,
  11875. a, ca, cal, value,
  11876. customAttribute;
  11877. if ( dirtyVertices ) {
  11878. for ( v = 0; v < vl; v ++ ) {
  11879. vertex = vertices[ v ];
  11880. offset = v * 3;
  11881. vertexArray[ offset ] = vertex.x;
  11882. vertexArray[ offset + 1 ] = vertex.y;
  11883. vertexArray[ offset + 2 ] = vertex.z;
  11884. }
  11885. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11886. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11887. }
  11888. if ( dirtyColors ) {
  11889. for ( c = 0; c < cl; c ++ ) {
  11890. color = colors[ c ];
  11891. offset = c * 3;
  11892. colorArray[ offset ] = color.r;
  11893. colorArray[ offset + 1 ] = color.g;
  11894. colorArray[ offset + 2 ] = color.b;
  11895. }
  11896. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11897. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11898. }
  11899. if ( dirtyLineDistances ) {
  11900. for ( d = 0; d < dl; d ++ ) {
  11901. lineDistanceArray[ d ] = lineDistances[ d ];
  11902. }
  11903. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  11904. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  11905. }
  11906. if ( customAttributes ) {
  11907. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11908. customAttribute = customAttributes[ i ];
  11909. if ( customAttribute.needsUpdate &&
  11910. ( customAttribute.boundTo === undefined ||
  11911. customAttribute.boundTo === "vertices" ) ) {
  11912. offset = 0;
  11913. cal = customAttribute.value.length;
  11914. if ( customAttribute.size === 1 ) {
  11915. for ( ca = 0; ca < cal; ca ++ ) {
  11916. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11917. }
  11918. } else if ( customAttribute.size === 2 ) {
  11919. for ( ca = 0; ca < cal; ca ++ ) {
  11920. value = customAttribute.value[ ca ];
  11921. customAttribute.array[ offset ] = value.x;
  11922. customAttribute.array[ offset + 1 ] = value.y;
  11923. offset += 2;
  11924. }
  11925. } else if ( customAttribute.size === 3 ) {
  11926. if ( customAttribute.type === "c" ) {
  11927. for ( ca = 0; ca < cal; ca ++ ) {
  11928. value = customAttribute.value[ ca ];
  11929. customAttribute.array[ offset ] = value.r;
  11930. customAttribute.array[ offset + 1 ] = value.g;
  11931. customAttribute.array[ offset + 2 ] = value.b;
  11932. offset += 3;
  11933. }
  11934. } else {
  11935. for ( ca = 0; ca < cal; ca ++ ) {
  11936. value = customAttribute.value[ ca ];
  11937. customAttribute.array[ offset ] = value.x;
  11938. customAttribute.array[ offset + 1 ] = value.y;
  11939. customAttribute.array[ offset + 2 ] = value.z;
  11940. offset += 3;
  11941. }
  11942. }
  11943. } else if ( customAttribute.size === 4 ) {
  11944. for ( ca = 0; ca < cal; ca ++ ) {
  11945. value = customAttribute.value[ ca ];
  11946. customAttribute.array[ offset ] = value.x;
  11947. customAttribute.array[ offset + 1 ] = value.y;
  11948. customAttribute.array[ offset + 2 ] = value.z;
  11949. customAttribute.array[ offset + 3 ] = value.w;
  11950. offset += 4;
  11951. }
  11952. }
  11953. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11954. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11955. }
  11956. }
  11957. }
  11958. };
  11959. function setRibbonBuffers ( geometry, hint ) {
  11960. var v, c, n, vertex, offset, color, normal,
  11961. i, il, ca, cal, customAttribute, value,
  11962. vertices = geometry.vertices,
  11963. colors = geometry.colors,
  11964. normals = geometry.normals,
  11965. vl = vertices.length,
  11966. cl = colors.length,
  11967. nl = normals.length,
  11968. vertexArray = geometry.__vertexArray,
  11969. colorArray = geometry.__colorArray,
  11970. normalArray = geometry.__normalArray,
  11971. dirtyVertices = geometry.verticesNeedUpdate,
  11972. dirtyColors = geometry.colorsNeedUpdate,
  11973. dirtyNormals = geometry.normalsNeedUpdate,
  11974. customAttributes = geometry.__webglCustomAttributesList;
  11975. if ( dirtyVertices ) {
  11976. for ( v = 0; v < vl; v ++ ) {
  11977. vertex = vertices[ v ];
  11978. offset = v * 3;
  11979. vertexArray[ offset ] = vertex.x;
  11980. vertexArray[ offset + 1 ] = vertex.y;
  11981. vertexArray[ offset + 2 ] = vertex.z;
  11982. }
  11983. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11984. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11985. }
  11986. if ( dirtyColors ) {
  11987. for ( c = 0; c < cl; c ++ ) {
  11988. color = colors[ c ];
  11989. offset = c * 3;
  11990. colorArray[ offset ] = color.r;
  11991. colorArray[ offset + 1 ] = color.g;
  11992. colorArray[ offset + 2 ] = color.b;
  11993. }
  11994. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11995. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11996. }
  11997. if ( dirtyNormals ) {
  11998. for ( n = 0; n < nl; n ++ ) {
  11999. normal = normals[ n ];
  12000. offset = n * 3;
  12001. normalArray[ offset ] = normal.x;
  12002. normalArray[ offset + 1 ] = normal.y;
  12003. normalArray[ offset + 2 ] = normal.z;
  12004. }
  12005. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  12006. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12007. }
  12008. if ( customAttributes ) {
  12009. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12010. customAttribute = customAttributes[ i ];
  12011. if ( customAttribute.needsUpdate &&
  12012. ( customAttribute.boundTo === undefined ||
  12013. customAttribute.boundTo === "vertices" ) ) {
  12014. offset = 0;
  12015. cal = customAttribute.value.length;
  12016. if ( customAttribute.size === 1 ) {
  12017. for ( ca = 0; ca < cal; ca ++ ) {
  12018. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12019. }
  12020. } else if ( customAttribute.size === 2 ) {
  12021. for ( ca = 0; ca < cal; ca ++ ) {
  12022. value = customAttribute.value[ ca ];
  12023. customAttribute.array[ offset ] = value.x;
  12024. customAttribute.array[ offset + 1 ] = value.y;
  12025. offset += 2;
  12026. }
  12027. } else if ( customAttribute.size === 3 ) {
  12028. if ( customAttribute.type === "c" ) {
  12029. for ( ca = 0; ca < cal; ca ++ ) {
  12030. value = customAttribute.value[ ca ];
  12031. customAttribute.array[ offset ] = value.r;
  12032. customAttribute.array[ offset + 1 ] = value.g;
  12033. customAttribute.array[ offset + 2 ] = value.b;
  12034. offset += 3;
  12035. }
  12036. } else {
  12037. for ( ca = 0; ca < cal; ca ++ ) {
  12038. value = customAttribute.value[ ca ];
  12039. customAttribute.array[ offset ] = value.x;
  12040. customAttribute.array[ offset + 1 ] = value.y;
  12041. customAttribute.array[ offset + 2 ] = value.z;
  12042. offset += 3;
  12043. }
  12044. }
  12045. } else if ( customAttribute.size === 4 ) {
  12046. for ( ca = 0; ca < cal; ca ++ ) {
  12047. value = customAttribute.value[ ca ];
  12048. customAttribute.array[ offset ] = value.x;
  12049. customAttribute.array[ offset + 1 ] = value.y;
  12050. customAttribute.array[ offset + 2 ] = value.z;
  12051. customAttribute.array[ offset + 3 ] = value.w;
  12052. offset += 4;
  12053. }
  12054. }
  12055. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12056. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12057. }
  12058. }
  12059. }
  12060. };
  12061. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12062. if ( ! geometryGroup.__inittedArrays ) {
  12063. return;
  12064. }
  12065. var normalType = bufferGuessNormalType( material ),
  12066. vertexColorType = bufferGuessVertexColorType( material ),
  12067. uvType = bufferGuessUVType( material ),
  12068. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12069. var f, fl, fi, face,
  12070. vertexNormals, faceNormal, normal,
  12071. vertexColors, faceColor,
  12072. vertexTangents,
  12073. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12074. c1, c2, c3, c4,
  12075. sw1, sw2, sw3, sw4,
  12076. si1, si2, si3, si4,
  12077. sa1, sa2, sa3, sa4,
  12078. sb1, sb2, sb3, sb4,
  12079. m, ml, i, il,
  12080. vn, uvi, uv2i,
  12081. vk, vkl, vka,
  12082. nka, chf, faceVertexNormals,
  12083. a,
  12084. vertexIndex = 0,
  12085. offset = 0,
  12086. offset_uv = 0,
  12087. offset_uv2 = 0,
  12088. offset_face = 0,
  12089. offset_normal = 0,
  12090. offset_tangent = 0,
  12091. offset_line = 0,
  12092. offset_color = 0,
  12093. offset_skin = 0,
  12094. offset_morphTarget = 0,
  12095. offset_custom = 0,
  12096. offset_customSrc = 0,
  12097. value,
  12098. vertexArray = geometryGroup.__vertexArray,
  12099. uvArray = geometryGroup.__uvArray,
  12100. uv2Array = geometryGroup.__uv2Array,
  12101. normalArray = geometryGroup.__normalArray,
  12102. tangentArray = geometryGroup.__tangentArray,
  12103. colorArray = geometryGroup.__colorArray,
  12104. skinIndexArray = geometryGroup.__skinIndexArray,
  12105. skinWeightArray = geometryGroup.__skinWeightArray,
  12106. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12107. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12108. customAttributes = geometryGroup.__webglCustomAttributesList,
  12109. customAttribute,
  12110. faceArray = geometryGroup.__faceArray,
  12111. lineArray = geometryGroup.__lineArray,
  12112. geometry = object.geometry, // this is shared for all chunks
  12113. dirtyVertices = geometry.verticesNeedUpdate,
  12114. dirtyElements = geometry.elementsNeedUpdate,
  12115. dirtyUvs = geometry.uvsNeedUpdate,
  12116. dirtyNormals = geometry.normalsNeedUpdate,
  12117. dirtyTangents = geometry.tangentsNeedUpdate,
  12118. dirtyColors = geometry.colorsNeedUpdate,
  12119. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12120. vertices = geometry.vertices,
  12121. chunk_faces3 = geometryGroup.faces3,
  12122. chunk_faces4 = geometryGroup.faces4,
  12123. obj_faces = geometry.faces,
  12124. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12125. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12126. obj_colors = geometry.colors,
  12127. obj_skinIndices = geometry.skinIndices,
  12128. obj_skinWeights = geometry.skinWeights,
  12129. morphTargets = geometry.morphTargets,
  12130. morphNormals = geometry.morphNormals;
  12131. if ( dirtyVertices ) {
  12132. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12133. face = obj_faces[ chunk_faces3[ f ] ];
  12134. v1 = vertices[ face.a ];
  12135. v2 = vertices[ face.b ];
  12136. v3 = vertices[ face.c ];
  12137. vertexArray[ offset ] = v1.x;
  12138. vertexArray[ offset + 1 ] = v1.y;
  12139. vertexArray[ offset + 2 ] = v1.z;
  12140. vertexArray[ offset + 3 ] = v2.x;
  12141. vertexArray[ offset + 4 ] = v2.y;
  12142. vertexArray[ offset + 5 ] = v2.z;
  12143. vertexArray[ offset + 6 ] = v3.x;
  12144. vertexArray[ offset + 7 ] = v3.y;
  12145. vertexArray[ offset + 8 ] = v3.z;
  12146. offset += 9;
  12147. }
  12148. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12149. face = obj_faces[ chunk_faces4[ f ] ];
  12150. v1 = vertices[ face.a ];
  12151. v2 = vertices[ face.b ];
  12152. v3 = vertices[ face.c ];
  12153. v4 = vertices[ face.d ];
  12154. vertexArray[ offset ] = v1.x;
  12155. vertexArray[ offset + 1 ] = v1.y;
  12156. vertexArray[ offset + 2 ] = v1.z;
  12157. vertexArray[ offset + 3 ] = v2.x;
  12158. vertexArray[ offset + 4 ] = v2.y;
  12159. vertexArray[ offset + 5 ] = v2.z;
  12160. vertexArray[ offset + 6 ] = v3.x;
  12161. vertexArray[ offset + 7 ] = v3.y;
  12162. vertexArray[ offset + 8 ] = v3.z;
  12163. vertexArray[ offset + 9 ] = v4.x;
  12164. vertexArray[ offset + 10 ] = v4.y;
  12165. vertexArray[ offset + 11 ] = v4.z;
  12166. offset += 12;
  12167. }
  12168. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12169. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12170. }
  12171. if ( dirtyMorphTargets ) {
  12172. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12173. offset_morphTarget = 0;
  12174. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12175. chf = chunk_faces3[ f ];
  12176. face = obj_faces[ chf ];
  12177. // morph positions
  12178. v1 = morphTargets[ vk ].vertices[ face.a ];
  12179. v2 = morphTargets[ vk ].vertices[ face.b ];
  12180. v3 = morphTargets[ vk ].vertices[ face.c ];
  12181. vka = morphTargetsArrays[ vk ];
  12182. vka[ offset_morphTarget ] = v1.x;
  12183. vka[ offset_morphTarget + 1 ] = v1.y;
  12184. vka[ offset_morphTarget + 2 ] = v1.z;
  12185. vka[ offset_morphTarget + 3 ] = v2.x;
  12186. vka[ offset_morphTarget + 4 ] = v2.y;
  12187. vka[ offset_morphTarget + 5 ] = v2.z;
  12188. vka[ offset_morphTarget + 6 ] = v3.x;
  12189. vka[ offset_morphTarget + 7 ] = v3.y;
  12190. vka[ offset_morphTarget + 8 ] = v3.z;
  12191. // morph normals
  12192. if ( material.morphNormals ) {
  12193. if ( needsSmoothNormals ) {
  12194. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12195. n1 = faceVertexNormals.a;
  12196. n2 = faceVertexNormals.b;
  12197. n3 = faceVertexNormals.c;
  12198. } else {
  12199. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12200. n2 = n1;
  12201. n3 = n1;
  12202. }
  12203. nka = morphNormalsArrays[ vk ];
  12204. nka[ offset_morphTarget ] = n1.x;
  12205. nka[ offset_morphTarget + 1 ] = n1.y;
  12206. nka[ offset_morphTarget + 2 ] = n1.z;
  12207. nka[ offset_morphTarget + 3 ] = n2.x;
  12208. nka[ offset_morphTarget + 4 ] = n2.y;
  12209. nka[ offset_morphTarget + 5 ] = n2.z;
  12210. nka[ offset_morphTarget + 6 ] = n3.x;
  12211. nka[ offset_morphTarget + 7 ] = n3.y;
  12212. nka[ offset_morphTarget + 8 ] = n3.z;
  12213. }
  12214. //
  12215. offset_morphTarget += 9;
  12216. }
  12217. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12218. chf = chunk_faces4[ f ];
  12219. face = obj_faces[ chf ];
  12220. // morph positions
  12221. v1 = morphTargets[ vk ].vertices[ face.a ];
  12222. v2 = morphTargets[ vk ].vertices[ face.b ];
  12223. v3 = morphTargets[ vk ].vertices[ face.c ];
  12224. v4 = morphTargets[ vk ].vertices[ face.d ];
  12225. vka = morphTargetsArrays[ vk ];
  12226. vka[ offset_morphTarget ] = v1.x;
  12227. vka[ offset_morphTarget + 1 ] = v1.y;
  12228. vka[ offset_morphTarget + 2 ] = v1.z;
  12229. vka[ offset_morphTarget + 3 ] = v2.x;
  12230. vka[ offset_morphTarget + 4 ] = v2.y;
  12231. vka[ offset_morphTarget + 5 ] = v2.z;
  12232. vka[ offset_morphTarget + 6 ] = v3.x;
  12233. vka[ offset_morphTarget + 7 ] = v3.y;
  12234. vka[ offset_morphTarget + 8 ] = v3.z;
  12235. vka[ offset_morphTarget + 9 ] = v4.x;
  12236. vka[ offset_morphTarget + 10 ] = v4.y;
  12237. vka[ offset_morphTarget + 11 ] = v4.z;
  12238. // morph normals
  12239. if ( material.morphNormals ) {
  12240. if ( needsSmoothNormals ) {
  12241. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12242. n1 = faceVertexNormals.a;
  12243. n2 = faceVertexNormals.b;
  12244. n3 = faceVertexNormals.c;
  12245. n4 = faceVertexNormals.d;
  12246. } else {
  12247. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12248. n2 = n1;
  12249. n3 = n1;
  12250. n4 = n1;
  12251. }
  12252. nka = morphNormalsArrays[ vk ];
  12253. nka[ offset_morphTarget ] = n1.x;
  12254. nka[ offset_morphTarget + 1 ] = n1.y;
  12255. nka[ offset_morphTarget + 2 ] = n1.z;
  12256. nka[ offset_morphTarget + 3 ] = n2.x;
  12257. nka[ offset_morphTarget + 4 ] = n2.y;
  12258. nka[ offset_morphTarget + 5 ] = n2.z;
  12259. nka[ offset_morphTarget + 6 ] = n3.x;
  12260. nka[ offset_morphTarget + 7 ] = n3.y;
  12261. nka[ offset_morphTarget + 8 ] = n3.z;
  12262. nka[ offset_morphTarget + 9 ] = n4.x;
  12263. nka[ offset_morphTarget + 10 ] = n4.y;
  12264. nka[ offset_morphTarget + 11 ] = n4.z;
  12265. }
  12266. //
  12267. offset_morphTarget += 12;
  12268. }
  12269. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12270. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12271. if ( material.morphNormals ) {
  12272. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12273. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12274. }
  12275. }
  12276. }
  12277. if ( obj_skinWeights.length ) {
  12278. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12279. face = obj_faces[ chunk_faces3[ f ] ];
  12280. // weights
  12281. sw1 = obj_skinWeights[ face.a ];
  12282. sw2 = obj_skinWeights[ face.b ];
  12283. sw3 = obj_skinWeights[ face.c ];
  12284. skinWeightArray[ offset_skin ] = sw1.x;
  12285. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12286. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12287. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12288. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12289. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12290. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12291. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12292. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12293. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12294. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12295. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12296. // indices
  12297. si1 = obj_skinIndices[ face.a ];
  12298. si2 = obj_skinIndices[ face.b ];
  12299. si3 = obj_skinIndices[ face.c ];
  12300. skinIndexArray[ offset_skin ] = si1.x;
  12301. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12302. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12303. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12304. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12305. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12306. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12307. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12308. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12309. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12310. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12311. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12312. offset_skin += 12;
  12313. }
  12314. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12315. face = obj_faces[ chunk_faces4[ f ] ];
  12316. // weights
  12317. sw1 = obj_skinWeights[ face.a ];
  12318. sw2 = obj_skinWeights[ face.b ];
  12319. sw3 = obj_skinWeights[ face.c ];
  12320. sw4 = obj_skinWeights[ face.d ];
  12321. skinWeightArray[ offset_skin ] = sw1.x;
  12322. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12323. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12324. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12325. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12326. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12327. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12328. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12329. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12330. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12331. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12332. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12333. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  12334. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  12335. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  12336. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  12337. // indices
  12338. si1 = obj_skinIndices[ face.a ];
  12339. si2 = obj_skinIndices[ face.b ];
  12340. si3 = obj_skinIndices[ face.c ];
  12341. si4 = obj_skinIndices[ face.d ];
  12342. skinIndexArray[ offset_skin ] = si1.x;
  12343. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12344. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12345. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12346. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12347. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12348. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12349. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12350. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12351. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12352. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12353. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12354. skinIndexArray[ offset_skin + 12 ] = si4.x;
  12355. skinIndexArray[ offset_skin + 13 ] = si4.y;
  12356. skinIndexArray[ offset_skin + 14 ] = si4.z;
  12357. skinIndexArray[ offset_skin + 15 ] = si4.w;
  12358. offset_skin += 16;
  12359. }
  12360. if ( offset_skin > 0 ) {
  12361. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12362. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12363. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12364. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12365. }
  12366. }
  12367. if ( dirtyColors && vertexColorType ) {
  12368. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12369. face = obj_faces[ chunk_faces3[ f ] ];
  12370. vertexColors = face.vertexColors;
  12371. faceColor = face.color;
  12372. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12373. c1 = vertexColors[ 0 ];
  12374. c2 = vertexColors[ 1 ];
  12375. c3 = vertexColors[ 2 ];
  12376. } else {
  12377. c1 = faceColor;
  12378. c2 = faceColor;
  12379. c3 = faceColor;
  12380. }
  12381. colorArray[ offset_color ] = c1.r;
  12382. colorArray[ offset_color + 1 ] = c1.g;
  12383. colorArray[ offset_color + 2 ] = c1.b;
  12384. colorArray[ offset_color + 3 ] = c2.r;
  12385. colorArray[ offset_color + 4 ] = c2.g;
  12386. colorArray[ offset_color + 5 ] = c2.b;
  12387. colorArray[ offset_color + 6 ] = c3.r;
  12388. colorArray[ offset_color + 7 ] = c3.g;
  12389. colorArray[ offset_color + 8 ] = c3.b;
  12390. offset_color += 9;
  12391. }
  12392. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12393. face = obj_faces[ chunk_faces4[ f ] ];
  12394. vertexColors = face.vertexColors;
  12395. faceColor = face.color;
  12396. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  12397. c1 = vertexColors[ 0 ];
  12398. c2 = vertexColors[ 1 ];
  12399. c3 = vertexColors[ 2 ];
  12400. c4 = vertexColors[ 3 ];
  12401. } else {
  12402. c1 = faceColor;
  12403. c2 = faceColor;
  12404. c3 = faceColor;
  12405. c4 = faceColor;
  12406. }
  12407. colorArray[ offset_color ] = c1.r;
  12408. colorArray[ offset_color + 1 ] = c1.g;
  12409. colorArray[ offset_color + 2 ] = c1.b;
  12410. colorArray[ offset_color + 3 ] = c2.r;
  12411. colorArray[ offset_color + 4 ] = c2.g;
  12412. colorArray[ offset_color + 5 ] = c2.b;
  12413. colorArray[ offset_color + 6 ] = c3.r;
  12414. colorArray[ offset_color + 7 ] = c3.g;
  12415. colorArray[ offset_color + 8 ] = c3.b;
  12416. colorArray[ offset_color + 9 ] = c4.r;
  12417. colorArray[ offset_color + 10 ] = c4.g;
  12418. colorArray[ offset_color + 11 ] = c4.b;
  12419. offset_color += 12;
  12420. }
  12421. if ( offset_color > 0 ) {
  12422. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12423. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12424. }
  12425. }
  12426. if ( dirtyTangents && geometry.hasTangents ) {
  12427. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12428. face = obj_faces[ chunk_faces3[ f ] ];
  12429. vertexTangents = face.vertexTangents;
  12430. t1 = vertexTangents[ 0 ];
  12431. t2 = vertexTangents[ 1 ];
  12432. t3 = vertexTangents[ 2 ];
  12433. tangentArray[ offset_tangent ] = t1.x;
  12434. tangentArray[ offset_tangent + 1 ] = t1.y;
  12435. tangentArray[ offset_tangent + 2 ] = t1.z;
  12436. tangentArray[ offset_tangent + 3 ] = t1.w;
  12437. tangentArray[ offset_tangent + 4 ] = t2.x;
  12438. tangentArray[ offset_tangent + 5 ] = t2.y;
  12439. tangentArray[ offset_tangent + 6 ] = t2.z;
  12440. tangentArray[ offset_tangent + 7 ] = t2.w;
  12441. tangentArray[ offset_tangent + 8 ] = t3.x;
  12442. tangentArray[ offset_tangent + 9 ] = t3.y;
  12443. tangentArray[ offset_tangent + 10 ] = t3.z;
  12444. tangentArray[ offset_tangent + 11 ] = t3.w;
  12445. offset_tangent += 12;
  12446. }
  12447. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12448. face = obj_faces[ chunk_faces4[ f ] ];
  12449. vertexTangents = face.vertexTangents;
  12450. t1 = vertexTangents[ 0 ];
  12451. t2 = vertexTangents[ 1 ];
  12452. t3 = vertexTangents[ 2 ];
  12453. t4 = vertexTangents[ 3 ];
  12454. tangentArray[ offset_tangent ] = t1.x;
  12455. tangentArray[ offset_tangent + 1 ] = t1.y;
  12456. tangentArray[ offset_tangent + 2 ] = t1.z;
  12457. tangentArray[ offset_tangent + 3 ] = t1.w;
  12458. tangentArray[ offset_tangent + 4 ] = t2.x;
  12459. tangentArray[ offset_tangent + 5 ] = t2.y;
  12460. tangentArray[ offset_tangent + 6 ] = t2.z;
  12461. tangentArray[ offset_tangent + 7 ] = t2.w;
  12462. tangentArray[ offset_tangent + 8 ] = t3.x;
  12463. tangentArray[ offset_tangent + 9 ] = t3.y;
  12464. tangentArray[ offset_tangent + 10 ] = t3.z;
  12465. tangentArray[ offset_tangent + 11 ] = t3.w;
  12466. tangentArray[ offset_tangent + 12 ] = t4.x;
  12467. tangentArray[ offset_tangent + 13 ] = t4.y;
  12468. tangentArray[ offset_tangent + 14 ] = t4.z;
  12469. tangentArray[ offset_tangent + 15 ] = t4.w;
  12470. offset_tangent += 16;
  12471. }
  12472. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12473. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12474. }
  12475. if ( dirtyNormals && normalType ) {
  12476. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12477. face = obj_faces[ chunk_faces3[ f ] ];
  12478. vertexNormals = face.vertexNormals;
  12479. faceNormal = face.normal;
  12480. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12481. for ( i = 0; i < 3; i ++ ) {
  12482. vn = vertexNormals[ i ];
  12483. normalArray[ offset_normal ] = vn.x;
  12484. normalArray[ offset_normal + 1 ] = vn.y;
  12485. normalArray[ offset_normal + 2 ] = vn.z;
  12486. offset_normal += 3;
  12487. }
  12488. } else {
  12489. for ( i = 0; i < 3; i ++ ) {
  12490. normalArray[ offset_normal ] = faceNormal.x;
  12491. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12492. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12493. offset_normal += 3;
  12494. }
  12495. }
  12496. }
  12497. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12498. face = obj_faces[ chunk_faces4[ f ] ];
  12499. vertexNormals = face.vertexNormals;
  12500. faceNormal = face.normal;
  12501. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  12502. for ( i = 0; i < 4; i ++ ) {
  12503. vn = vertexNormals[ i ];
  12504. normalArray[ offset_normal ] = vn.x;
  12505. normalArray[ offset_normal + 1 ] = vn.y;
  12506. normalArray[ offset_normal + 2 ] = vn.z;
  12507. offset_normal += 3;
  12508. }
  12509. } else {
  12510. for ( i = 0; i < 4; i ++ ) {
  12511. normalArray[ offset_normal ] = faceNormal.x;
  12512. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12513. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12514. offset_normal += 3;
  12515. }
  12516. }
  12517. }
  12518. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12519. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12520. }
  12521. if ( dirtyUvs && obj_uvs && uvType ) {
  12522. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12523. fi = chunk_faces3[ f ];
  12524. uv = obj_uvs[ fi ];
  12525. if ( uv === undefined ) continue;
  12526. for ( i = 0; i < 3; i ++ ) {
  12527. uvi = uv[ i ];
  12528. uvArray[ offset_uv ] = uvi.x;
  12529. uvArray[ offset_uv + 1 ] = uvi.y;
  12530. offset_uv += 2;
  12531. }
  12532. }
  12533. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12534. fi = chunk_faces4[ f ];
  12535. uv = obj_uvs[ fi ];
  12536. if ( uv === undefined ) continue;
  12537. for ( i = 0; i < 4; i ++ ) {
  12538. uvi = uv[ i ];
  12539. uvArray[ offset_uv ] = uvi.x;
  12540. uvArray[ offset_uv + 1 ] = uvi.y;
  12541. offset_uv += 2;
  12542. }
  12543. }
  12544. if ( offset_uv > 0 ) {
  12545. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12546. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12547. }
  12548. }
  12549. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12550. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12551. fi = chunk_faces3[ f ];
  12552. uv2 = obj_uvs2[ fi ];
  12553. if ( uv2 === undefined ) continue;
  12554. for ( i = 0; i < 3; i ++ ) {
  12555. uv2i = uv2[ i ];
  12556. uv2Array[ offset_uv2 ] = uv2i.x;
  12557. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12558. offset_uv2 += 2;
  12559. }
  12560. }
  12561. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12562. fi = chunk_faces4[ f ];
  12563. uv2 = obj_uvs2[ fi ];
  12564. if ( uv2 === undefined ) continue;
  12565. for ( i = 0; i < 4; i ++ ) {
  12566. uv2i = uv2[ i ];
  12567. uv2Array[ offset_uv2 ] = uv2i.x;
  12568. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12569. offset_uv2 += 2;
  12570. }
  12571. }
  12572. if ( offset_uv2 > 0 ) {
  12573. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12574. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12575. }
  12576. }
  12577. if ( dirtyElements ) {
  12578. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12579. faceArray[ offset_face ] = vertexIndex;
  12580. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12581. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12582. offset_face += 3;
  12583. lineArray[ offset_line ] = vertexIndex;
  12584. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12585. lineArray[ offset_line + 2 ] = vertexIndex;
  12586. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12587. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12588. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12589. offset_line += 6;
  12590. vertexIndex += 3;
  12591. }
  12592. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12593. faceArray[ offset_face ] = vertexIndex;
  12594. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12595. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  12596. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  12597. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  12598. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  12599. offset_face += 6;
  12600. lineArray[ offset_line ] = vertexIndex;
  12601. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12602. lineArray[ offset_line + 2 ] = vertexIndex;
  12603. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  12604. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12605. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12606. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  12607. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  12608. offset_line += 8;
  12609. vertexIndex += 4;
  12610. }
  12611. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12612. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12613. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12614. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12615. }
  12616. if ( customAttributes ) {
  12617. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12618. customAttribute = customAttributes[ i ];
  12619. if ( ! customAttribute.__original.needsUpdate ) continue;
  12620. offset_custom = 0;
  12621. offset_customSrc = 0;
  12622. if ( customAttribute.size === 1 ) {
  12623. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12624. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12625. face = obj_faces[ chunk_faces3[ f ] ];
  12626. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12627. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12628. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12629. offset_custom += 3;
  12630. }
  12631. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12632. face = obj_faces[ chunk_faces4[ f ] ];
  12633. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12634. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12635. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12636. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  12637. offset_custom += 4;
  12638. }
  12639. } else if ( customAttribute.boundTo === "faces" ) {
  12640. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12641. value = customAttribute.value[ chunk_faces3[ f ] ];
  12642. customAttribute.array[ offset_custom ] = value;
  12643. customAttribute.array[ offset_custom + 1 ] = value;
  12644. customAttribute.array[ offset_custom + 2 ] = value;
  12645. offset_custom += 3;
  12646. }
  12647. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12648. value = customAttribute.value[ chunk_faces4[ f ] ];
  12649. customAttribute.array[ offset_custom ] = value;
  12650. customAttribute.array[ offset_custom + 1 ] = value;
  12651. customAttribute.array[ offset_custom + 2 ] = value;
  12652. customAttribute.array[ offset_custom + 3 ] = value;
  12653. offset_custom += 4;
  12654. }
  12655. }
  12656. } else if ( customAttribute.size === 2 ) {
  12657. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12658. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12659. face = obj_faces[ chunk_faces3[ f ] ];
  12660. v1 = customAttribute.value[ face.a ];
  12661. v2 = customAttribute.value[ face.b ];
  12662. v3 = customAttribute.value[ face.c ];
  12663. customAttribute.array[ offset_custom ] = v1.x;
  12664. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12665. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12666. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12667. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12668. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12669. offset_custom += 6;
  12670. }
  12671. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12672. face = obj_faces[ chunk_faces4[ f ] ];
  12673. v1 = customAttribute.value[ face.a ];
  12674. v2 = customAttribute.value[ face.b ];
  12675. v3 = customAttribute.value[ face.c ];
  12676. v4 = customAttribute.value[ face.d ];
  12677. customAttribute.array[ offset_custom ] = v1.x;
  12678. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12679. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12680. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12681. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12682. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12683. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12684. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12685. offset_custom += 8;
  12686. }
  12687. } else if ( customAttribute.boundTo === "faces" ) {
  12688. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12689. value = customAttribute.value[ chunk_faces3[ f ] ];
  12690. v1 = value;
  12691. v2 = value;
  12692. v3 = value;
  12693. customAttribute.array[ offset_custom ] = v1.x;
  12694. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12695. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12696. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12697. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12698. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12699. offset_custom += 6;
  12700. }
  12701. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12702. value = customAttribute.value[ chunk_faces4[ f ] ];
  12703. v1 = value;
  12704. v2 = value;
  12705. v3 = value;
  12706. v4 = value;
  12707. customAttribute.array[ offset_custom ] = v1.x;
  12708. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12709. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12710. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12711. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12712. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12713. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12714. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12715. offset_custom += 8;
  12716. }
  12717. }
  12718. } else if ( customAttribute.size === 3 ) {
  12719. var pp;
  12720. if ( customAttribute.type === "c" ) {
  12721. pp = [ "r", "g", "b" ];
  12722. } else {
  12723. pp = [ "x", "y", "z" ];
  12724. }
  12725. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12726. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12727. face = obj_faces[ chunk_faces3[ f ] ];
  12728. v1 = customAttribute.value[ face.a ];
  12729. v2 = customAttribute.value[ face.b ];
  12730. v3 = customAttribute.value[ face.c ];
  12731. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12732. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12733. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12734. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12735. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12736. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12737. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12738. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12739. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12740. offset_custom += 9;
  12741. }
  12742. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12743. face = obj_faces[ chunk_faces4[ f ] ];
  12744. v1 = customAttribute.value[ face.a ];
  12745. v2 = customAttribute.value[ face.b ];
  12746. v3 = customAttribute.value[ face.c ];
  12747. v4 = customAttribute.value[ face.d ];
  12748. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12749. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12750. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12751. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12752. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12753. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12754. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12755. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12756. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12757. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12758. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12759. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12760. offset_custom += 12;
  12761. }
  12762. } else if ( customAttribute.boundTo === "faces" ) {
  12763. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12764. value = customAttribute.value[ chunk_faces3[ f ] ];
  12765. v1 = value;
  12766. v2 = value;
  12767. v3 = value;
  12768. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12769. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12770. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12771. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12772. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12773. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12774. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12775. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12776. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12777. offset_custom += 9;
  12778. }
  12779. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12780. value = customAttribute.value[ chunk_faces4[ f ] ];
  12781. v1 = value;
  12782. v2 = value;
  12783. v3 = value;
  12784. v4 = value;
  12785. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12786. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12787. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12788. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12789. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12790. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12791. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12792. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12793. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12794. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12795. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12796. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12797. offset_custom += 12;
  12798. }
  12799. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12800. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12801. value = customAttribute.value[ chunk_faces3[ f ] ];
  12802. v1 = value[ 0 ];
  12803. v2 = value[ 1 ];
  12804. v3 = value[ 2 ];
  12805. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12806. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12807. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12808. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12809. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12810. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12811. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12812. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12813. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12814. offset_custom += 9;
  12815. }
  12816. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12817. value = customAttribute.value[ chunk_faces4[ f ] ];
  12818. v1 = value[ 0 ];
  12819. v2 = value[ 1 ];
  12820. v3 = value[ 2 ];
  12821. v4 = value[ 3 ];
  12822. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12823. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12824. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12825. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12826. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12827. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12828. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12829. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12830. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12831. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12832. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12833. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12834. offset_custom += 12;
  12835. }
  12836. }
  12837. } else if ( customAttribute.size === 4 ) {
  12838. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12839. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12840. face = obj_faces[ chunk_faces3[ f ] ];
  12841. v1 = customAttribute.value[ face.a ];
  12842. v2 = customAttribute.value[ face.b ];
  12843. v3 = customAttribute.value[ face.c ];
  12844. customAttribute.array[ offset_custom ] = v1.x;
  12845. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12846. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12847. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12848. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12849. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12850. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12851. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12852. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12853. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12854. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12855. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12856. offset_custom += 12;
  12857. }
  12858. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12859. face = obj_faces[ chunk_faces4[ f ] ];
  12860. v1 = customAttribute.value[ face.a ];
  12861. v2 = customAttribute.value[ face.b ];
  12862. v3 = customAttribute.value[ face.c ];
  12863. v4 = customAttribute.value[ face.d ];
  12864. customAttribute.array[ offset_custom ] = v1.x;
  12865. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12866. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12867. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12868. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12869. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12870. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12871. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12872. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12873. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12874. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12875. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12876. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12877. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12878. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12879. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12880. offset_custom += 16;
  12881. }
  12882. } else if ( customAttribute.boundTo === "faces" ) {
  12883. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12884. value = customAttribute.value[ chunk_faces3[ f ] ];
  12885. v1 = value;
  12886. v2 = value;
  12887. v3 = value;
  12888. customAttribute.array[ offset_custom ] = v1.x;
  12889. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12890. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12891. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12892. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12893. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12894. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12895. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12896. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12897. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12898. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12899. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12900. offset_custom += 12;
  12901. }
  12902. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12903. value = customAttribute.value[ chunk_faces4[ f ] ];
  12904. v1 = value;
  12905. v2 = value;
  12906. v3 = value;
  12907. v4 = value;
  12908. customAttribute.array[ offset_custom ] = v1.x;
  12909. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12910. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12911. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12912. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12913. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12914. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12915. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12916. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12917. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12918. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12919. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12920. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12921. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12922. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12923. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12924. offset_custom += 16;
  12925. }
  12926. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12927. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12928. value = customAttribute.value[ chunk_faces3[ f ] ];
  12929. v1 = value[ 0 ];
  12930. v2 = value[ 1 ];
  12931. v3 = value[ 2 ];
  12932. customAttribute.array[ offset_custom ] = v1.x;
  12933. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12934. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12935. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12936. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12937. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12938. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12939. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12940. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12941. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12942. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12943. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12944. offset_custom += 12;
  12945. }
  12946. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12947. value = customAttribute.value[ chunk_faces4[ f ] ];
  12948. v1 = value[ 0 ];
  12949. v2 = value[ 1 ];
  12950. v3 = value[ 2 ];
  12951. v4 = value[ 3 ];
  12952. customAttribute.array[ offset_custom ] = v1.x;
  12953. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12954. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12955. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12956. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12957. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12958. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12959. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12960. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12961. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12962. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12963. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12964. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12965. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12966. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12967. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12968. offset_custom += 16;
  12969. }
  12970. }
  12971. }
  12972. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12973. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12974. }
  12975. }
  12976. if ( dispose ) {
  12977. delete geometryGroup.__inittedArrays;
  12978. delete geometryGroup.__colorArray;
  12979. delete geometryGroup.__normalArray;
  12980. delete geometryGroup.__tangentArray;
  12981. delete geometryGroup.__uvArray;
  12982. delete geometryGroup.__uv2Array;
  12983. delete geometryGroup.__faceArray;
  12984. delete geometryGroup.__vertexArray;
  12985. delete geometryGroup.__lineArray;
  12986. delete geometryGroup.__skinIndexArray;
  12987. delete geometryGroup.__skinWeightArray;
  12988. }
  12989. };
  12990. function setDirectBuffers ( geometry, hint, dispose ) {
  12991. var attributes = geometry.attributes;
  12992. var attributeName, attributeItem;
  12993. for ( attributeName in attributes ) {
  12994. attributeItem = attributes[ attributeName ];
  12995. if ( attributeItem.needsUpdate ) {
  12996. if ( attributeName === 'index' ) {
  12997. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  12998. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  12999. } else {
  13000. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13001. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13002. }
  13003. attributeItem.needsUpdate = false;
  13004. }
  13005. if ( dispose && ! attributeItem.dynamic ) {
  13006. delete attributeItem.array;
  13007. }
  13008. }
  13009. };
  13010. // Buffer rendering
  13011. this.renderBufferImmediate = function ( object, program, material ) {
  13012. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13013. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13014. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13015. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13016. if ( object.hasPositions ) {
  13017. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13018. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13019. _gl.enableVertexAttribArray( program.attributes.position );
  13020. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13021. }
  13022. if ( object.hasNormals ) {
  13023. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13024. if ( material.shading === THREE.FlatShading ) {
  13025. var nx, ny, nz,
  13026. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13027. normalArray,
  13028. i, il = object.count * 3;
  13029. for( i = 0; i < il; i += 9 ) {
  13030. normalArray = object.normalArray;
  13031. nax = normalArray[ i ];
  13032. nay = normalArray[ i + 1 ];
  13033. naz = normalArray[ i + 2 ];
  13034. nbx = normalArray[ i + 3 ];
  13035. nby = normalArray[ i + 4 ];
  13036. nbz = normalArray[ i + 5 ];
  13037. ncx = normalArray[ i + 6 ];
  13038. ncy = normalArray[ i + 7 ];
  13039. ncz = normalArray[ i + 8 ];
  13040. nx = ( nax + nbx + ncx ) / 3;
  13041. ny = ( nay + nby + ncy ) / 3;
  13042. nz = ( naz + nbz + ncz ) / 3;
  13043. normalArray[ i ] = nx;
  13044. normalArray[ i + 1 ] = ny;
  13045. normalArray[ i + 2 ] = nz;
  13046. normalArray[ i + 3 ] = nx;
  13047. normalArray[ i + 4 ] = ny;
  13048. normalArray[ i + 5 ] = nz;
  13049. normalArray[ i + 6 ] = nx;
  13050. normalArray[ i + 7 ] = ny;
  13051. normalArray[ i + 8 ] = nz;
  13052. }
  13053. }
  13054. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13055. _gl.enableVertexAttribArray( program.attributes.normal );
  13056. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13057. }
  13058. if ( object.hasUvs && material.map ) {
  13059. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13060. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13061. _gl.enableVertexAttribArray( program.attributes.uv );
  13062. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13063. }
  13064. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13065. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13066. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13067. _gl.enableVertexAttribArray( program.attributes.color );
  13068. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13069. }
  13070. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13071. object.count = 0;
  13072. };
  13073. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13074. if ( material.visible === false ) return;
  13075. var program, programAttributes, linewidth, primitives, a, attribute, geometryAttributes;
  13076. var attributeItem, attributeName, attributePointer, attributeSize;
  13077. program = setProgram( camera, lights, fog, material, object );
  13078. programAttributes = program.attributes;
  13079. geometryAttributes = geometry.attributes;
  13080. var updateBuffers = false,
  13081. wireframeBit = material.wireframe ? 1 : 0,
  13082. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13083. if ( geometryHash !== _currentGeometryGroupHash ) {
  13084. _currentGeometryGroupHash = geometryHash;
  13085. updateBuffers = true;
  13086. }
  13087. if ( updateBuffers ) {
  13088. disableAttributes();
  13089. }
  13090. // render mesh
  13091. if ( object instanceof THREE.Mesh ) {
  13092. var index = geometryAttributes[ "index" ];
  13093. // indexed triangles
  13094. if ( index ) {
  13095. var offsets = geometry.offsets;
  13096. // if there is more than 1 chunk
  13097. // must set attribute pointers to use new offsets for each chunk
  13098. // even if geometry and materials didn't change
  13099. if ( offsets.length > 1 ) updateBuffers = true;
  13100. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13101. var startIndex = offsets[ i ].index;
  13102. if ( updateBuffers ) {
  13103. for ( attributeName in geometryAttributes ) {
  13104. if ( attributeName === 'index' ) continue;
  13105. attributePointer = programAttributes[ attributeName ];
  13106. attributeItem = geometryAttributes[ attributeName ];
  13107. attributeSize = attributeItem.itemSize;
  13108. if ( attributePointer >= 0 ) {
  13109. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13110. enableAttribute( attributePointer );
  13111. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13112. }
  13113. }
  13114. // indices
  13115. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13116. }
  13117. // render indexed triangles
  13118. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13119. _this.info.render.calls ++;
  13120. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13121. _this.info.render.faces += offsets[ i ].count / 3;
  13122. }
  13123. // non-indexed triangles
  13124. } else {
  13125. if ( updateBuffers ) {
  13126. for ( attributeName in geometryAttributes ) {
  13127. if ( attributeName === 'index') continue;
  13128. attributePointer = programAttributes[ attributeName ];
  13129. attributeItem = geometryAttributes[ attributeName ];
  13130. attributeSize = attributeItem.itemSize;
  13131. if ( attributePointer >= 0 ) {
  13132. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13133. enableAttribute( attributePointer );
  13134. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13135. }
  13136. }
  13137. }
  13138. var position = geometry.attributes[ "position" ];
  13139. // render non-indexed triangles
  13140. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  13141. _this.info.render.calls ++;
  13142. _this.info.render.vertices += position.numItems / 3;
  13143. _this.info.render.faces += position.numItems / 3 / 3;
  13144. }
  13145. // render particles
  13146. } else if ( object instanceof THREE.ParticleSystem ) {
  13147. if ( updateBuffers ) {
  13148. for ( attributeName in geometryAttributes ) {
  13149. attributePointer = programAttributes[ attributeName ];
  13150. attributeItem = geometryAttributes[ attributeName ];
  13151. attributeSize = attributeItem.itemSize;
  13152. if ( attributePointer >= 0 ) {
  13153. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13154. enableAttribute( attributePointer );
  13155. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13156. }
  13157. }
  13158. var position = geometryAttributes[ "position" ];
  13159. // render particles
  13160. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  13161. _this.info.render.calls ++;
  13162. _this.info.render.points += position.numItems / 3;
  13163. }
  13164. } else if ( object instanceof THREE.Line ) {
  13165. if ( updateBuffers ) {
  13166. for ( attributeName in geometryAttributes ) {
  13167. attributePointer = programAttributes[ attributeName ];
  13168. attributeItem = geometryAttributes[ attributeName ];
  13169. attributeSize = attributeItem.itemSize;
  13170. if ( attributePointer >= 0 ) {
  13171. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13172. enableAttribute( attributePointer );
  13173. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13174. }
  13175. }
  13176. // render lines
  13177. setLineWidth( material.linewidth );
  13178. var position = geometryAttributes[ "position" ];
  13179. _gl.drawArrays( _gl.LINE_STRIP, 0, position.numItems / 3 );
  13180. _this.info.render.calls ++;
  13181. _this.info.render.points += position.numItems;
  13182. }
  13183. }
  13184. };
  13185. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13186. if ( material.visible === false ) return;
  13187. var program, attributes, linewidth, primitives, a, attribute, i, il;
  13188. program = setProgram( camera, lights, fog, material, object );
  13189. attributes = program.attributes;
  13190. var updateBuffers = false,
  13191. wireframeBit = material.wireframe ? 1 : 0,
  13192. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13193. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13194. _currentGeometryGroupHash = geometryGroupHash;
  13195. updateBuffers = true;
  13196. }
  13197. if ( updateBuffers ) {
  13198. disableAttributes();
  13199. }
  13200. // vertices
  13201. if ( !material.morphTargets && attributes.position >= 0 ) {
  13202. if ( updateBuffers ) {
  13203. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13204. enableAttribute( attributes.position );
  13205. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13206. }
  13207. } else {
  13208. if ( object.morphTargetBase ) {
  13209. setupMorphTargets( material, geometryGroup, object );
  13210. }
  13211. }
  13212. if ( updateBuffers ) {
  13213. // custom attributes
  13214. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13215. if ( geometryGroup.__webglCustomAttributesList ) {
  13216. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13217. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13218. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13219. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13220. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13221. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13222. }
  13223. }
  13224. }
  13225. // colors
  13226. if ( attributes.color >= 0 ) {
  13227. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13228. enableAttribute( attributes.color );
  13229. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13230. }
  13231. // normals
  13232. if ( attributes.normal >= 0 ) {
  13233. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13234. enableAttribute( attributes.normal );
  13235. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13236. }
  13237. // tangents
  13238. if ( attributes.tangent >= 0 ) {
  13239. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13240. enableAttribute( attributes.tangent );
  13241. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13242. }
  13243. // uvs
  13244. if ( attributes.uv >= 0 ) {
  13245. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13246. enableAttribute( attributes.uv );
  13247. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13248. }
  13249. if ( attributes.uv2 >= 0 ) {
  13250. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13251. enableAttribute( attributes.uv2 );
  13252. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13253. }
  13254. if ( material.skinning &&
  13255. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13256. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13257. enableAttribute( attributes.skinIndex );
  13258. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13259. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13260. enableAttribute( attributes.skinWeight );
  13261. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13262. }
  13263. // line distances
  13264. if ( attributes.lineDistance >= 0 ) {
  13265. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13266. enableAttribute( attributes.lineDistance );
  13267. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13268. }
  13269. }
  13270. // render mesh
  13271. if ( object instanceof THREE.Mesh ) {
  13272. // wireframe
  13273. if ( material.wireframe ) {
  13274. setLineWidth( material.wireframeLinewidth );
  13275. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13276. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13277. // triangles
  13278. } else {
  13279. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13280. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13281. }
  13282. _this.info.render.calls ++;
  13283. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13284. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13285. // render lines
  13286. } else if ( object instanceof THREE.Line ) {
  13287. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13288. setLineWidth( material.linewidth );
  13289. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13290. _this.info.render.calls ++;
  13291. // render particles
  13292. } else if ( object instanceof THREE.ParticleSystem ) {
  13293. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13294. _this.info.render.calls ++;
  13295. _this.info.render.points += geometryGroup.__webglParticleCount;
  13296. // render ribbon
  13297. } else if ( object instanceof THREE.Ribbon ) {
  13298. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  13299. _this.info.render.calls ++;
  13300. }
  13301. };
  13302. function enableAttribute( attribute ) {
  13303. if ( ! _enabledAttributes[ attribute ] ) {
  13304. _gl.enableVertexAttribArray( attribute );
  13305. _enabledAttributes[ attribute ] = true;
  13306. }
  13307. };
  13308. function disableAttributes() {
  13309. for ( var attribute in _enabledAttributes ) {
  13310. if ( _enabledAttributes[ attribute ] ) {
  13311. _gl.disableVertexAttribArray( attribute );
  13312. _enabledAttributes[ attribute ] = false;
  13313. }
  13314. }
  13315. };
  13316. function setupMorphTargets ( material, geometryGroup, object ) {
  13317. // set base
  13318. var attributes = material.program.attributes;
  13319. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13320. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13321. enableAttribute( attributes.position );
  13322. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13323. } else if ( attributes.position >= 0 ) {
  13324. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13325. enableAttribute( attributes.position );
  13326. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13327. }
  13328. if ( object.morphTargetForcedOrder.length ) {
  13329. // set forced order
  13330. var m = 0;
  13331. var order = object.morphTargetForcedOrder;
  13332. var influences = object.morphTargetInfluences;
  13333. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13334. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13335. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13336. enableAttribute( attributes[ "morphTarget" + m ] );
  13337. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13338. }
  13339. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13340. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13341. enableAttribute( attributes[ "morphNormal" + m ] );
  13342. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13343. }
  13344. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13345. m ++;
  13346. }
  13347. } else {
  13348. // find the most influencing
  13349. var influence, activeInfluenceIndices = [];
  13350. var influences = object.morphTargetInfluences;
  13351. var i, il = influences.length;
  13352. for ( i = 0; i < il; i ++ ) {
  13353. influence = influences[ i ];
  13354. if ( influence > 0 ) {
  13355. activeInfluenceIndices.push( [ influence, i ] );
  13356. }
  13357. }
  13358. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13359. activeInfluenceIndices.sort( numericalSort );
  13360. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13361. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13362. activeInfluenceIndices.sort( numericalSort );
  13363. } else if ( activeInfluenceIndices.length === 0 ) {
  13364. activeInfluenceIndices.push( [ 0, 0 ] );
  13365. };
  13366. var influenceIndex, m = 0;
  13367. while ( m < material.numSupportedMorphTargets ) {
  13368. if ( activeInfluenceIndices[ m ] ) {
  13369. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13370. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13371. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13372. enableAttribute( attributes[ "morphTarget" + m ] );
  13373. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13374. }
  13375. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13376. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13377. enableAttribute( attributes[ "morphNormal" + m ] );
  13378. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13379. }
  13380. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13381. } else {
  13382. /*
  13383. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13384. if ( material.morphNormals ) {
  13385. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13386. }
  13387. */
  13388. object.__webglMorphTargetInfluences[ m ] = 0;
  13389. }
  13390. m ++;
  13391. }
  13392. }
  13393. // load updated influences uniform
  13394. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13395. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13396. }
  13397. };
  13398. // Sorting
  13399. function painterSortStable ( a, b ) {
  13400. if ( a.z !== b.z ) {
  13401. return b.z - a.z;
  13402. } else {
  13403. return a.id - b.id;
  13404. }
  13405. };
  13406. function numericalSort ( a, b ) {
  13407. return b[ 0 ] - a[ 0 ];
  13408. };
  13409. // Rendering
  13410. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13411. if ( camera instanceof THREE.Camera === false ) {
  13412. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13413. return;
  13414. }
  13415. var i, il,
  13416. webglObject, object,
  13417. renderList,
  13418. lights = scene.__lights,
  13419. fog = scene.fog;
  13420. // reset caching for this frame
  13421. _currentMaterialId = -1;
  13422. _lightsNeedUpdate = true;
  13423. // update scene graph
  13424. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13425. // update camera matrices and frustum
  13426. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13427. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13428. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13429. _frustum.setFromMatrix( _projScreenMatrix );
  13430. // update WebGL objects
  13431. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13432. // custom render plugins (pre pass)
  13433. renderPlugins( this.renderPluginsPre, scene, camera );
  13434. //
  13435. _this.info.render.calls = 0;
  13436. _this.info.render.vertices = 0;
  13437. _this.info.render.faces = 0;
  13438. _this.info.render.points = 0;
  13439. this.setRenderTarget( renderTarget );
  13440. if ( this.autoClear || forceClear ) {
  13441. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13442. }
  13443. // set matrices for regular objects (frustum culled)
  13444. renderList = scene.__webglObjects;
  13445. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13446. webglObject = renderList[ i ];
  13447. object = webglObject.object;
  13448. webglObject.id = i;
  13449. webglObject.render = false;
  13450. if ( object.visible ) {
  13451. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13452. setupMatrices( object, camera );
  13453. unrollBufferMaterial( webglObject );
  13454. webglObject.render = true;
  13455. if ( this.sortObjects === true ) {
  13456. if ( object.renderDepth !== null ) {
  13457. webglObject.z = object.renderDepth;
  13458. } else {
  13459. _vector3.getPositionFromMatrix( object.matrixWorld );
  13460. _vector3.applyProjection( _projScreenMatrix );
  13461. webglObject.z = _vector3.z;
  13462. }
  13463. }
  13464. }
  13465. }
  13466. }
  13467. if ( this.sortObjects ) {
  13468. renderList.sort( painterSortStable );
  13469. }
  13470. // set matrices for immediate objects
  13471. renderList = scene.__webglObjectsImmediate;
  13472. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13473. webglObject = renderList[ i ];
  13474. object = webglObject.object;
  13475. if ( object.visible ) {
  13476. setupMatrices( object, camera );
  13477. unrollImmediateBufferMaterial( webglObject );
  13478. }
  13479. }
  13480. if ( scene.overrideMaterial ) {
  13481. var material = scene.overrideMaterial;
  13482. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13483. this.setDepthTest( material.depthTest );
  13484. this.setDepthWrite( material.depthWrite );
  13485. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13486. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13487. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13488. } else {
  13489. var material = null;
  13490. // opaque pass (front-to-back order)
  13491. this.setBlending( THREE.NoBlending );
  13492. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13493. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13494. // transparent pass (back-to-front order)
  13495. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13496. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13497. }
  13498. // custom render plugins (post pass)
  13499. renderPlugins( this.renderPluginsPost, scene, camera );
  13500. // Generate mipmap if we're using any kind of mipmap filtering
  13501. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13502. updateRenderTargetMipmap( renderTarget );
  13503. }
  13504. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13505. this.setDepthTest( true );
  13506. this.setDepthWrite( true );
  13507. // _gl.finish();
  13508. };
  13509. function renderPlugins( plugins, scene, camera ) {
  13510. if ( ! plugins.length ) return;
  13511. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13512. // reset state for plugin (to start from clean slate)
  13513. _currentProgram = null;
  13514. _currentCamera = null;
  13515. _oldBlending = -1;
  13516. _oldDepthTest = -1;
  13517. _oldDepthWrite = -1;
  13518. _oldDoubleSided = -1;
  13519. _oldFlipSided = -1;
  13520. _currentGeometryGroupHash = -1;
  13521. _currentMaterialId = -1;
  13522. _lightsNeedUpdate = true;
  13523. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13524. // reset state after plugin (anything could have changed)
  13525. _currentProgram = null;
  13526. _currentCamera = null;
  13527. _oldBlending = -1;
  13528. _oldDepthTest = -1;
  13529. _oldDepthWrite = -1;
  13530. _oldDoubleSided = -1;
  13531. _oldFlipSided = -1;
  13532. _currentGeometryGroupHash = -1;
  13533. _currentMaterialId = -1;
  13534. _lightsNeedUpdate = true;
  13535. }
  13536. };
  13537. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13538. var webglObject, object, buffer, material, start, end, delta;
  13539. if ( reverse ) {
  13540. start = renderList.length - 1;
  13541. end = -1;
  13542. delta = -1;
  13543. } else {
  13544. start = 0;
  13545. end = renderList.length;
  13546. delta = 1;
  13547. }
  13548. for ( var i = start; i !== end; i += delta ) {
  13549. webglObject = renderList[ i ];
  13550. if ( webglObject.render ) {
  13551. object = webglObject.object;
  13552. buffer = webglObject.buffer;
  13553. if ( overrideMaterial ) {
  13554. material = overrideMaterial;
  13555. } else {
  13556. material = webglObject[ materialType ];
  13557. if ( ! material ) continue;
  13558. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13559. _this.setDepthTest( material.depthTest );
  13560. _this.setDepthWrite( material.depthWrite );
  13561. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13562. }
  13563. _this.setMaterialFaces( material );
  13564. if ( buffer instanceof THREE.BufferGeometry ) {
  13565. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13566. } else {
  13567. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13568. }
  13569. }
  13570. }
  13571. };
  13572. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13573. var webglObject, object, material, program;
  13574. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13575. webglObject = renderList[ i ];
  13576. object = webglObject.object;
  13577. if ( object.visible ) {
  13578. if ( overrideMaterial ) {
  13579. material = overrideMaterial;
  13580. } else {
  13581. material = webglObject[ materialType ];
  13582. if ( ! material ) continue;
  13583. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13584. _this.setDepthTest( material.depthTest );
  13585. _this.setDepthWrite( material.depthWrite );
  13586. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13587. }
  13588. _this.renderImmediateObject( camera, lights, fog, material, object );
  13589. }
  13590. }
  13591. };
  13592. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13593. var program = setProgram( camera, lights, fog, material, object );
  13594. _currentGeometryGroupHash = -1;
  13595. _this.setMaterialFaces( material );
  13596. if ( object.immediateRenderCallback ) {
  13597. object.immediateRenderCallback( program, _gl, _frustum );
  13598. } else {
  13599. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13600. }
  13601. };
  13602. function unrollImmediateBufferMaterial ( globject ) {
  13603. var object = globject.object,
  13604. material = object.material;
  13605. if ( material.transparent ) {
  13606. globject.transparent = material;
  13607. globject.opaque = null;
  13608. } else {
  13609. globject.opaque = material;
  13610. globject.transparent = null;
  13611. }
  13612. };
  13613. function unrollBufferMaterial ( globject ) {
  13614. var object = globject.object,
  13615. buffer = globject.buffer,
  13616. material, materialIndex, meshMaterial;
  13617. meshMaterial = object.material;
  13618. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13619. materialIndex = buffer.materialIndex;
  13620. material = meshMaterial.materials[ materialIndex ];
  13621. if ( material.transparent ) {
  13622. globject.transparent = material;
  13623. globject.opaque = null;
  13624. } else {
  13625. globject.opaque = material;
  13626. globject.transparent = null;
  13627. }
  13628. } else {
  13629. material = meshMaterial;
  13630. if ( material ) {
  13631. if ( material.transparent ) {
  13632. globject.transparent = material;
  13633. globject.opaque = null;
  13634. } else {
  13635. globject.opaque = material;
  13636. globject.transparent = null;
  13637. }
  13638. }
  13639. }
  13640. };
  13641. // Geometry splitting
  13642. function sortFacesByMaterial ( geometry, material ) {
  13643. var f, fl, face, materialIndex, vertices,
  13644. groupHash, hash_map = {};
  13645. var numMorphTargets = geometry.morphTargets.length;
  13646. var numMorphNormals = geometry.morphNormals.length;
  13647. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13648. geometry.geometryGroups = {};
  13649. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13650. face = geometry.faces[ f ];
  13651. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13652. if ( hash_map[ materialIndex ] === undefined ) {
  13653. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13654. }
  13655. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13656. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13657. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13658. }
  13659. vertices = face instanceof THREE.Face3 ? 3 : 4;
  13660. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13661. hash_map[ materialIndex ].counter += 1;
  13662. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13663. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13664. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13665. }
  13666. }
  13667. if ( face instanceof THREE.Face3 ) {
  13668. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13669. } else {
  13670. geometry.geometryGroups[ groupHash ].faces4.push( f );
  13671. }
  13672. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13673. }
  13674. geometry.geometryGroupsList = [];
  13675. for ( var g in geometry.geometryGroups ) {
  13676. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13677. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13678. }
  13679. };
  13680. // Objects refresh
  13681. this.initWebGLObjects = function ( scene ) {
  13682. if ( !scene.__webglObjects ) {
  13683. scene.__webglObjects = [];
  13684. scene.__webglObjectsImmediate = [];
  13685. scene.__webglSprites = [];
  13686. scene.__webglFlares = [];
  13687. }
  13688. while ( scene.__objectsAdded.length ) {
  13689. addObject( scene.__objectsAdded[ 0 ], scene );
  13690. scene.__objectsAdded.splice( 0, 1 );
  13691. }
  13692. while ( scene.__objectsRemoved.length ) {
  13693. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13694. scene.__objectsRemoved.splice( 0, 1 );
  13695. }
  13696. // update must be called after objects adding / removal
  13697. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13698. var object = scene.__webglObjects[ o ].object;
  13699. // TODO: Remove this hack (WebGLRenderer refactoring)
  13700. if ( object.__webglInit === undefined ) {
  13701. if ( object.__webglActive !== undefined ) {
  13702. removeObject( object, scene );
  13703. }
  13704. addObject( object, scene );
  13705. }
  13706. updateObject( object );
  13707. }
  13708. };
  13709. // Objects adding
  13710. function addObject( object, scene ) {
  13711. var g, geometry, material, geometryGroup;
  13712. if ( object.__webglInit === undefined ) {
  13713. object.__webglInit = true;
  13714. object._modelViewMatrix = new THREE.Matrix4();
  13715. object._normalMatrix = new THREE.Matrix3();
  13716. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13717. object.geometry.__webglInit = true;
  13718. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13719. }
  13720. geometry = object.geometry;
  13721. if ( geometry === undefined ) {
  13722. // fail silently for now
  13723. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13724. initDirectBuffers( geometry );
  13725. } else if ( object instanceof THREE.Mesh ) {
  13726. material = object.material;
  13727. if ( geometry.geometryGroups === undefined ) {
  13728. sortFacesByMaterial( geometry, material );
  13729. }
  13730. // create separate VBOs per geometry chunk
  13731. for ( g in geometry.geometryGroups ) {
  13732. geometryGroup = geometry.geometryGroups[ g ];
  13733. // initialise VBO on the first access
  13734. if ( ! geometryGroup.__webglVertexBuffer ) {
  13735. createMeshBuffers( geometryGroup );
  13736. initMeshBuffers( geometryGroup, object );
  13737. geometry.verticesNeedUpdate = true;
  13738. geometry.morphTargetsNeedUpdate = true;
  13739. geometry.elementsNeedUpdate = true;
  13740. geometry.uvsNeedUpdate = true;
  13741. geometry.normalsNeedUpdate = true;
  13742. geometry.tangentsNeedUpdate = true;
  13743. geometry.colorsNeedUpdate = true;
  13744. }
  13745. }
  13746. } else if ( object instanceof THREE.Ribbon ) {
  13747. if ( ! geometry.__webglVertexBuffer ) {
  13748. createRibbonBuffers( geometry );
  13749. initRibbonBuffers( geometry, object );
  13750. geometry.verticesNeedUpdate = true;
  13751. geometry.colorsNeedUpdate = true;
  13752. geometry.normalsNeedUpdate = true;
  13753. }
  13754. } else if ( object instanceof THREE.Line ) {
  13755. if ( ! geometry.__webglVertexBuffer ) {
  13756. createLineBuffers( geometry );
  13757. initLineBuffers( geometry, object );
  13758. geometry.verticesNeedUpdate = true;
  13759. geometry.colorsNeedUpdate = true;
  13760. geometry.lineDistancesNeedUpdate = true;
  13761. }
  13762. } else if ( object instanceof THREE.ParticleSystem ) {
  13763. if ( ! geometry.__webglVertexBuffer ) {
  13764. createParticleBuffers( geometry );
  13765. initParticleBuffers( geometry, object );
  13766. geometry.verticesNeedUpdate = true;
  13767. geometry.colorsNeedUpdate = true;
  13768. }
  13769. }
  13770. }
  13771. if ( object.__webglActive === undefined ) {
  13772. if ( object instanceof THREE.Mesh ) {
  13773. geometry = object.geometry;
  13774. if ( geometry instanceof THREE.BufferGeometry ) {
  13775. addBuffer( scene.__webglObjects, geometry, object );
  13776. } else if ( geometry instanceof THREE.Geometry ) {
  13777. for ( g in geometry.geometryGroups ) {
  13778. geometryGroup = geometry.geometryGroups[ g ];
  13779. addBuffer( scene.__webglObjects, geometryGroup, object );
  13780. }
  13781. }
  13782. } else if ( object instanceof THREE.Ribbon ||
  13783. object instanceof THREE.Line ||
  13784. object instanceof THREE.ParticleSystem ) {
  13785. geometry = object.geometry;
  13786. addBuffer( scene.__webglObjects, geometry, object );
  13787. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13788. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13789. } else if ( object instanceof THREE.Sprite ) {
  13790. scene.__webglSprites.push( object );
  13791. } else if ( object instanceof THREE.LensFlare ) {
  13792. scene.__webglFlares.push( object );
  13793. }
  13794. object.__webglActive = true;
  13795. }
  13796. };
  13797. function addBuffer( objlist, buffer, object ) {
  13798. objlist.push(
  13799. {
  13800. id: null,
  13801. buffer: buffer,
  13802. object: object,
  13803. opaque: null,
  13804. transparent: null,
  13805. z: 0
  13806. }
  13807. );
  13808. };
  13809. function addBufferImmediate( objlist, object ) {
  13810. objlist.push(
  13811. {
  13812. id: null,
  13813. object: object,
  13814. opaque: null,
  13815. transparent: null,
  13816. z: 0
  13817. }
  13818. );
  13819. };
  13820. // Objects updates
  13821. function updateObject( object ) {
  13822. var geometry = object.geometry,
  13823. geometryGroup, customAttributesDirty, material;
  13824. if ( geometry instanceof THREE.BufferGeometry ) {
  13825. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13826. } else if ( object instanceof THREE.Mesh ) {
  13827. // check all geometry groups
  13828. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13829. geometryGroup = geometry.geometryGroupsList[ i ];
  13830. material = getBufferMaterial( object, geometryGroup );
  13831. if ( geometry.buffersNeedUpdate ) {
  13832. initMeshBuffers( geometryGroup, object );
  13833. }
  13834. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13835. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13836. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13837. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13838. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13839. }
  13840. }
  13841. geometry.verticesNeedUpdate = false;
  13842. geometry.morphTargetsNeedUpdate = false;
  13843. geometry.elementsNeedUpdate = false;
  13844. geometry.uvsNeedUpdate = false;
  13845. geometry.normalsNeedUpdate = false;
  13846. geometry.colorsNeedUpdate = false;
  13847. geometry.tangentsNeedUpdate = false;
  13848. geometry.buffersNeedUpdate = false;
  13849. material.attributes && clearCustomAttributes( material );
  13850. } else if ( object instanceof THREE.Ribbon ) {
  13851. material = getBufferMaterial( object, geometry );
  13852. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13853. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  13854. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  13855. }
  13856. geometry.verticesNeedUpdate = false;
  13857. geometry.colorsNeedUpdate = false;
  13858. geometry.normalsNeedUpdate = false;
  13859. material.attributes && clearCustomAttributes( material );
  13860. } else if ( object instanceof THREE.Line ) {
  13861. material = getBufferMaterial( object, geometry );
  13862. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13863. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13864. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13865. }
  13866. geometry.verticesNeedUpdate = false;
  13867. geometry.colorsNeedUpdate = false;
  13868. geometry.lineDistancesNeedUpdate = false;
  13869. material.attributes && clearCustomAttributes( material );
  13870. } else if ( object instanceof THREE.ParticleSystem ) {
  13871. material = getBufferMaterial( object, geometry );
  13872. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13873. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13874. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13875. }
  13876. geometry.verticesNeedUpdate = false;
  13877. geometry.colorsNeedUpdate = false;
  13878. material.attributes && clearCustomAttributes( material );
  13879. }
  13880. };
  13881. // Objects updates - custom attributes check
  13882. function areCustomAttributesDirty( material ) {
  13883. for ( var a in material.attributes ) {
  13884. if ( material.attributes[ a ].needsUpdate ) return true;
  13885. }
  13886. return false;
  13887. };
  13888. function clearCustomAttributes( material ) {
  13889. for ( var a in material.attributes ) {
  13890. material.attributes[ a ].needsUpdate = false;
  13891. }
  13892. };
  13893. // Objects removal
  13894. function removeObject( object, scene ) {
  13895. if ( object instanceof THREE.Mesh ||
  13896. object instanceof THREE.ParticleSystem ||
  13897. object instanceof THREE.Ribbon ||
  13898. object instanceof THREE.Line ) {
  13899. removeInstances( scene.__webglObjects, object );
  13900. } else if ( object instanceof THREE.Sprite ) {
  13901. removeInstancesDirect( scene.__webglSprites, object );
  13902. } else if ( object instanceof THREE.LensFlare ) {
  13903. removeInstancesDirect( scene.__webglFlares, object );
  13904. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13905. removeInstances( scene.__webglObjectsImmediate, object );
  13906. }
  13907. delete object.__webglActive;
  13908. };
  13909. function removeInstances( objlist, object ) {
  13910. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13911. if ( objlist[ o ].object === object ) {
  13912. objlist.splice( o, 1 );
  13913. }
  13914. }
  13915. };
  13916. function removeInstancesDirect( objlist, object ) {
  13917. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13918. if ( objlist[ o ] === object ) {
  13919. objlist.splice( o, 1 );
  13920. }
  13921. }
  13922. };
  13923. // Materials
  13924. this.initMaterial = function ( material, lights, fog, object ) {
  13925. material.addEventListener( 'dispose', onMaterialDispose );
  13926. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13927. if ( material instanceof THREE.MeshDepthMaterial ) {
  13928. shaderID = 'depth';
  13929. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13930. shaderID = 'normal';
  13931. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13932. shaderID = 'basic';
  13933. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13934. shaderID = 'lambert';
  13935. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13936. shaderID = 'phong';
  13937. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13938. shaderID = 'basic';
  13939. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13940. shaderID = 'dashed';
  13941. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13942. shaderID = 'particle_basic';
  13943. }
  13944. if ( shaderID ) {
  13945. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13946. }
  13947. // heuristics to create shader parameters according to lights in the scene
  13948. // (not to blow over maxLights budget)
  13949. maxLightCount = allocateLights( lights );
  13950. maxShadows = allocateShadows( lights );
  13951. maxBones = allocateBones( object );
  13952. parameters = {
  13953. map: !!material.map,
  13954. envMap: !!material.envMap,
  13955. lightMap: !!material.lightMap,
  13956. bumpMap: !!material.bumpMap,
  13957. normalMap: !!material.normalMap,
  13958. specularMap: !!material.specularMap,
  13959. vertexColors: material.vertexColors,
  13960. fog: fog,
  13961. useFog: material.fog,
  13962. fogExp: fog instanceof THREE.FogExp2,
  13963. sizeAttenuation: material.sizeAttenuation,
  13964. skinning: material.skinning,
  13965. maxBones: maxBones,
  13966. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13967. boneTextureWidth: object && object.boneTextureWidth,
  13968. boneTextureHeight: object && object.boneTextureHeight,
  13969. morphTargets: material.morphTargets,
  13970. morphNormals: material.morphNormals,
  13971. maxMorphTargets: this.maxMorphTargets,
  13972. maxMorphNormals: this.maxMorphNormals,
  13973. maxDirLights: maxLightCount.directional,
  13974. maxPointLights: maxLightCount.point,
  13975. maxSpotLights: maxLightCount.spot,
  13976. maxHemiLights: maxLightCount.hemi,
  13977. maxShadows: maxShadows,
  13978. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13979. shadowMapType: this.shadowMapType,
  13980. shadowMapDebug: this.shadowMapDebug,
  13981. shadowMapCascade: this.shadowMapCascade,
  13982. alphaTest: material.alphaTest,
  13983. metal: material.metal,
  13984. perPixel: material.perPixel,
  13985. wrapAround: material.wrapAround,
  13986. doubleSided: material.side === THREE.DoubleSide,
  13987. flipSided: material.side === THREE.BackSide
  13988. };
  13989. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  13990. var attributes = material.program.attributes;
  13991. if ( material.morphTargets ) {
  13992. material.numSupportedMorphTargets = 0;
  13993. var id, base = "morphTarget";
  13994. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13995. id = base + i;
  13996. if ( attributes[ id ] >= 0 ) {
  13997. material.numSupportedMorphTargets ++;
  13998. }
  13999. }
  14000. }
  14001. if ( material.morphNormals ) {
  14002. material.numSupportedMorphNormals = 0;
  14003. var id, base = "morphNormal";
  14004. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14005. id = base + i;
  14006. if ( attributes[ id ] >= 0 ) {
  14007. material.numSupportedMorphNormals ++;
  14008. }
  14009. }
  14010. }
  14011. material.uniformsList = [];
  14012. for ( u in material.uniforms ) {
  14013. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14014. }
  14015. };
  14016. function setMaterialShaders( material, shaders ) {
  14017. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14018. material.vertexShader = shaders.vertexShader;
  14019. material.fragmentShader = shaders.fragmentShader;
  14020. };
  14021. function setProgram( camera, lights, fog, material, object ) {
  14022. _usedTextureUnits = 0;
  14023. if ( material.needsUpdate ) {
  14024. if ( material.program ) deallocateMaterial( material );
  14025. _this.initMaterial( material, lights, fog, object );
  14026. material.needsUpdate = false;
  14027. }
  14028. if ( material.morphTargets ) {
  14029. if ( ! object.__webglMorphTargetInfluences ) {
  14030. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14031. }
  14032. }
  14033. var refreshMaterial = false;
  14034. var program = material.program,
  14035. p_uniforms = program.uniforms,
  14036. m_uniforms = material.uniforms;
  14037. if ( program !== _currentProgram ) {
  14038. _gl.useProgram( program );
  14039. _currentProgram = program;
  14040. refreshMaterial = true;
  14041. }
  14042. if ( material.id !== _currentMaterialId ) {
  14043. _currentMaterialId = material.id;
  14044. refreshMaterial = true;
  14045. }
  14046. if ( refreshMaterial || camera !== _currentCamera ) {
  14047. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14048. if ( camera !== _currentCamera ) _currentCamera = camera;
  14049. }
  14050. // skinning uniforms must be set even if material didn't change
  14051. // auto-setting of texture unit for bone texture must go before other textures
  14052. // not sure why, but otherwise weird things happen
  14053. if ( material.skinning ) {
  14054. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14055. if ( p_uniforms.boneTexture !== null ) {
  14056. var textureUnit = getTextureUnit();
  14057. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14058. _this.setTexture( object.boneTexture, textureUnit );
  14059. }
  14060. } else {
  14061. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14062. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14063. }
  14064. }
  14065. }
  14066. if ( refreshMaterial ) {
  14067. // refresh uniforms common to several materials
  14068. if ( fog && material.fog ) {
  14069. refreshUniformsFog( m_uniforms, fog );
  14070. }
  14071. if ( material instanceof THREE.MeshPhongMaterial ||
  14072. material instanceof THREE.MeshLambertMaterial ||
  14073. material.lights ) {
  14074. if ( _lightsNeedUpdate ) {
  14075. setupLights( program, lights );
  14076. _lightsNeedUpdate = false;
  14077. }
  14078. refreshUniformsLights( m_uniforms, _lights );
  14079. }
  14080. if ( material instanceof THREE.MeshBasicMaterial ||
  14081. material instanceof THREE.MeshLambertMaterial ||
  14082. material instanceof THREE.MeshPhongMaterial ) {
  14083. refreshUniformsCommon( m_uniforms, material );
  14084. }
  14085. // refresh single material specific uniforms
  14086. if ( material instanceof THREE.LineBasicMaterial ) {
  14087. refreshUniformsLine( m_uniforms, material );
  14088. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14089. refreshUniformsLine( m_uniforms, material );
  14090. refreshUniformsDash( m_uniforms, material );
  14091. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  14092. refreshUniformsParticle( m_uniforms, material );
  14093. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14094. refreshUniformsPhong( m_uniforms, material );
  14095. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14096. refreshUniformsLambert( m_uniforms, material );
  14097. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14098. m_uniforms.mNear.value = camera.near;
  14099. m_uniforms.mFar.value = camera.far;
  14100. m_uniforms.opacity.value = material.opacity;
  14101. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14102. m_uniforms.opacity.value = material.opacity;
  14103. }
  14104. if ( object.receiveShadow && ! material._shadowPass ) {
  14105. refreshUniformsShadow( m_uniforms, lights );
  14106. }
  14107. // load common uniforms
  14108. loadUniformsGeneric( program, material.uniformsList );
  14109. // load material specific uniforms
  14110. // (shader material also gets them for the sake of genericity)
  14111. if ( material instanceof THREE.ShaderMaterial ||
  14112. material instanceof THREE.MeshPhongMaterial ||
  14113. material.envMap ) {
  14114. if ( p_uniforms.cameraPosition !== null ) {
  14115. _vector3.getPositionFromMatrix( camera.matrixWorld );
  14116. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14117. }
  14118. }
  14119. if ( material instanceof THREE.MeshPhongMaterial ||
  14120. material instanceof THREE.MeshLambertMaterial ||
  14121. material instanceof THREE.ShaderMaterial ||
  14122. material.skinning ) {
  14123. if ( p_uniforms.viewMatrix !== null ) {
  14124. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14125. }
  14126. }
  14127. }
  14128. loadUniformsMatrices( p_uniforms, object );
  14129. if ( p_uniforms.modelMatrix !== null ) {
  14130. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14131. }
  14132. return program;
  14133. };
  14134. // Uniforms (refresh uniforms objects)
  14135. function refreshUniformsCommon ( uniforms, material ) {
  14136. uniforms.opacity.value = material.opacity;
  14137. if ( _this.gammaInput ) {
  14138. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14139. } else {
  14140. uniforms.diffuse.value = material.color;
  14141. }
  14142. uniforms.map.value = material.map;
  14143. uniforms.lightMap.value = material.lightMap;
  14144. uniforms.specularMap.value = material.specularMap;
  14145. if ( material.bumpMap ) {
  14146. uniforms.bumpMap.value = material.bumpMap;
  14147. uniforms.bumpScale.value = material.bumpScale;
  14148. }
  14149. if ( material.normalMap ) {
  14150. uniforms.normalMap.value = material.normalMap;
  14151. uniforms.normalScale.value.copy( material.normalScale );
  14152. }
  14153. // uv repeat and offset setting priorities
  14154. // 1. color map
  14155. // 2. specular map
  14156. // 3. normal map
  14157. // 4. bump map
  14158. var uvScaleMap;
  14159. if ( material.map ) {
  14160. uvScaleMap = material.map;
  14161. } else if ( material.specularMap ) {
  14162. uvScaleMap = material.specularMap;
  14163. } else if ( material.normalMap ) {
  14164. uvScaleMap = material.normalMap;
  14165. } else if ( material.bumpMap ) {
  14166. uvScaleMap = material.bumpMap;
  14167. }
  14168. if ( uvScaleMap !== undefined ) {
  14169. var offset = uvScaleMap.offset;
  14170. var repeat = uvScaleMap.repeat;
  14171. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14172. }
  14173. uniforms.envMap.value = material.envMap;
  14174. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14175. if ( _this.gammaInput ) {
  14176. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14177. uniforms.reflectivity.value = material.reflectivity;
  14178. } else {
  14179. uniforms.reflectivity.value = material.reflectivity;
  14180. }
  14181. uniforms.refractionRatio.value = material.refractionRatio;
  14182. uniforms.combine.value = material.combine;
  14183. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14184. };
  14185. function refreshUniformsLine ( uniforms, material ) {
  14186. uniforms.diffuse.value = material.color;
  14187. uniforms.opacity.value = material.opacity;
  14188. };
  14189. function refreshUniformsDash ( uniforms, material ) {
  14190. uniforms.dashSize.value = material.dashSize;
  14191. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14192. uniforms.scale.value = material.scale;
  14193. };
  14194. function refreshUniformsParticle ( uniforms, material ) {
  14195. uniforms.psColor.value = material.color;
  14196. uniforms.opacity.value = material.opacity;
  14197. uniforms.size.value = material.size;
  14198. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14199. uniforms.map.value = material.map;
  14200. };
  14201. function refreshUniformsFog ( uniforms, fog ) {
  14202. uniforms.fogColor.value = fog.color;
  14203. if ( fog instanceof THREE.Fog ) {
  14204. uniforms.fogNear.value = fog.near;
  14205. uniforms.fogFar.value = fog.far;
  14206. } else if ( fog instanceof THREE.FogExp2 ) {
  14207. uniforms.fogDensity.value = fog.density;
  14208. }
  14209. };
  14210. function refreshUniformsPhong ( uniforms, material ) {
  14211. uniforms.shininess.value = material.shininess;
  14212. if ( _this.gammaInput ) {
  14213. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14214. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14215. uniforms.specular.value.copyGammaToLinear( material.specular );
  14216. } else {
  14217. uniforms.ambient.value = material.ambient;
  14218. uniforms.emissive.value = material.emissive;
  14219. uniforms.specular.value = material.specular;
  14220. }
  14221. if ( material.wrapAround ) {
  14222. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14223. }
  14224. };
  14225. function refreshUniformsLambert ( uniforms, material ) {
  14226. if ( _this.gammaInput ) {
  14227. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14228. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14229. } else {
  14230. uniforms.ambient.value = material.ambient;
  14231. uniforms.emissive.value = material.emissive;
  14232. }
  14233. if ( material.wrapAround ) {
  14234. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14235. }
  14236. };
  14237. function refreshUniformsLights ( uniforms, lights ) {
  14238. uniforms.ambientLightColor.value = lights.ambient;
  14239. uniforms.directionalLightColor.value = lights.directional.colors;
  14240. uniforms.directionalLightDirection.value = lights.directional.positions;
  14241. uniforms.pointLightColor.value = lights.point.colors;
  14242. uniforms.pointLightPosition.value = lights.point.positions;
  14243. uniforms.pointLightDistance.value = lights.point.distances;
  14244. uniforms.spotLightColor.value = lights.spot.colors;
  14245. uniforms.spotLightPosition.value = lights.spot.positions;
  14246. uniforms.spotLightDistance.value = lights.spot.distances;
  14247. uniforms.spotLightDirection.value = lights.spot.directions;
  14248. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14249. uniforms.spotLightExponent.value = lights.spot.exponents;
  14250. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14251. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14252. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14253. };
  14254. function refreshUniformsShadow ( uniforms, lights ) {
  14255. if ( uniforms.shadowMatrix ) {
  14256. var j = 0;
  14257. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14258. var light = lights[ i ];
  14259. if ( ! light.castShadow ) continue;
  14260. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14261. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14262. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14263. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14264. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14265. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14266. j ++;
  14267. }
  14268. }
  14269. }
  14270. };
  14271. // Uniforms (load to GPU)
  14272. function loadUniformsMatrices ( uniforms, object ) {
  14273. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14274. if ( uniforms.normalMatrix ) {
  14275. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14276. }
  14277. };
  14278. function getTextureUnit() {
  14279. var textureUnit = _usedTextureUnits;
  14280. if ( textureUnit >= _maxTextures ) {
  14281. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14282. }
  14283. _usedTextureUnits += 1;
  14284. return textureUnit;
  14285. };
  14286. function loadUniformsGeneric ( program, uniforms ) {
  14287. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14288. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14289. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14290. if ( !location ) continue;
  14291. uniform = uniforms[ j ][ 0 ];
  14292. type = uniform.type;
  14293. value = uniform.value;
  14294. if ( type === "i" ) { // single integer
  14295. _gl.uniform1i( location, value );
  14296. } else if ( type === "f" ) { // single float
  14297. _gl.uniform1f( location, value );
  14298. } else if ( type === "v2" ) { // single THREE.Vector2
  14299. _gl.uniform2f( location, value.x, value.y );
  14300. } else if ( type === "v3" ) { // single THREE.Vector3
  14301. _gl.uniform3f( location, value.x, value.y, value.z );
  14302. } else if ( type === "v4" ) { // single THREE.Vector4
  14303. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14304. } else if ( type === "c" ) { // single THREE.Color
  14305. _gl.uniform3f( location, value.r, value.g, value.b );
  14306. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14307. _gl.uniform1iv( location, value );
  14308. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14309. _gl.uniform3iv( location, value );
  14310. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14311. _gl.uniform1fv( location, value );
  14312. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14313. _gl.uniform3fv( location, value );
  14314. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14315. if ( uniform._array === undefined ) {
  14316. uniform._array = new Float32Array( 2 * value.length );
  14317. }
  14318. for ( i = 0, il = value.length; i < il; i ++ ) {
  14319. offset = i * 2;
  14320. uniform._array[ offset ] = value[ i ].x;
  14321. uniform._array[ offset + 1 ] = value[ i ].y;
  14322. }
  14323. _gl.uniform2fv( location, uniform._array );
  14324. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14325. if ( uniform._array === undefined ) {
  14326. uniform._array = new Float32Array( 3 * value.length );
  14327. }
  14328. for ( i = 0, il = value.length; i < il; i ++ ) {
  14329. offset = i * 3;
  14330. uniform._array[ offset ] = value[ i ].x;
  14331. uniform._array[ offset + 1 ] = value[ i ].y;
  14332. uniform._array[ offset + 2 ] = value[ i ].z;
  14333. }
  14334. _gl.uniform3fv( location, uniform._array );
  14335. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14336. if ( uniform._array === undefined ) {
  14337. uniform._array = new Float32Array( 4 * value.length );
  14338. }
  14339. for ( i = 0, il = value.length; i < il; i ++ ) {
  14340. offset = i * 4;
  14341. uniform._array[ offset ] = value[ i ].x;
  14342. uniform._array[ offset + 1 ] = value[ i ].y;
  14343. uniform._array[ offset + 2 ] = value[ i ].z;
  14344. uniform._array[ offset + 3 ] = value[ i ].w;
  14345. }
  14346. _gl.uniform4fv( location, uniform._array );
  14347. } else if ( type === "m4") { // single THREE.Matrix4
  14348. if ( uniform._array === undefined ) {
  14349. uniform._array = new Float32Array( 16 );
  14350. }
  14351. value.flattenToArray( uniform._array );
  14352. _gl.uniformMatrix4fv( location, false, uniform._array );
  14353. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14354. if ( uniform._array === undefined ) {
  14355. uniform._array = new Float32Array( 16 * value.length );
  14356. }
  14357. for ( i = 0, il = value.length; i < il; i ++ ) {
  14358. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14359. }
  14360. _gl.uniformMatrix4fv( location, false, uniform._array );
  14361. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14362. texture = value;
  14363. textureUnit = getTextureUnit();
  14364. _gl.uniform1i( location, textureUnit );
  14365. if ( !texture ) continue;
  14366. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14367. setCubeTexture( texture, textureUnit );
  14368. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14369. setCubeTextureDynamic( texture, textureUnit );
  14370. } else {
  14371. _this.setTexture( texture, textureUnit );
  14372. }
  14373. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14374. if ( uniform._array === undefined ) {
  14375. uniform._array = [];
  14376. }
  14377. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14378. uniform._array[ i ] = getTextureUnit();
  14379. }
  14380. _gl.uniform1iv( location, uniform._array );
  14381. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14382. texture = uniform.value[ i ];
  14383. textureUnit = uniform._array[ i ];
  14384. if ( !texture ) continue;
  14385. _this.setTexture( texture, textureUnit );
  14386. }
  14387. }
  14388. }
  14389. };
  14390. function setupMatrices ( object, camera ) {
  14391. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14392. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14393. };
  14394. //
  14395. function setColorGamma( array, offset, color, intensitySq ) {
  14396. array[ offset ] = color.r * color.r * intensitySq;
  14397. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14398. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14399. };
  14400. function setColorLinear( array, offset, color, intensity ) {
  14401. array[ offset ] = color.r * intensity;
  14402. array[ offset + 1 ] = color.g * intensity;
  14403. array[ offset + 2 ] = color.b * intensity;
  14404. };
  14405. function setupLights ( program, lights ) {
  14406. var l, ll, light, n,
  14407. r = 0, g = 0, b = 0,
  14408. color, skyColor, groundColor,
  14409. intensity, intensitySq,
  14410. position,
  14411. distance,
  14412. zlights = _lights,
  14413. dirColors = zlights.directional.colors,
  14414. dirPositions = zlights.directional.positions,
  14415. pointColors = zlights.point.colors,
  14416. pointPositions = zlights.point.positions,
  14417. pointDistances = zlights.point.distances,
  14418. spotColors = zlights.spot.colors,
  14419. spotPositions = zlights.spot.positions,
  14420. spotDistances = zlights.spot.distances,
  14421. spotDirections = zlights.spot.directions,
  14422. spotAnglesCos = zlights.spot.anglesCos,
  14423. spotExponents = zlights.spot.exponents,
  14424. hemiSkyColors = zlights.hemi.skyColors,
  14425. hemiGroundColors = zlights.hemi.groundColors,
  14426. hemiPositions = zlights.hemi.positions,
  14427. dirLength = 0,
  14428. pointLength = 0,
  14429. spotLength = 0,
  14430. hemiLength = 0,
  14431. dirCount = 0,
  14432. pointCount = 0,
  14433. spotCount = 0,
  14434. hemiCount = 0,
  14435. dirOffset = 0,
  14436. pointOffset = 0,
  14437. spotOffset = 0,
  14438. hemiOffset = 0;
  14439. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14440. light = lights[ l ];
  14441. if ( light.onlyShadow ) continue;
  14442. color = light.color;
  14443. intensity = light.intensity;
  14444. distance = light.distance;
  14445. if ( light instanceof THREE.AmbientLight ) {
  14446. if ( ! light.visible ) continue;
  14447. if ( _this.gammaInput ) {
  14448. r += color.r * color.r;
  14449. g += color.g * color.g;
  14450. b += color.b * color.b;
  14451. } else {
  14452. r += color.r;
  14453. g += color.g;
  14454. b += color.b;
  14455. }
  14456. } else if ( light instanceof THREE.DirectionalLight ) {
  14457. dirCount += 1;
  14458. if ( ! light.visible ) continue;
  14459. _direction.getPositionFromMatrix( light.matrixWorld );
  14460. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14461. _direction.sub( _vector3 );
  14462. _direction.normalize();
  14463. // skip lights with undefined direction
  14464. // these create troubles in OpenGL (making pixel black)
  14465. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14466. dirOffset = dirLength * 3;
  14467. dirPositions[ dirOffset ] = _direction.x;
  14468. dirPositions[ dirOffset + 1 ] = _direction.y;
  14469. dirPositions[ dirOffset + 2 ] = _direction.z;
  14470. if ( _this.gammaInput ) {
  14471. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14472. } else {
  14473. setColorLinear( dirColors, dirOffset, color, intensity );
  14474. }
  14475. dirLength += 1;
  14476. } else if ( light instanceof THREE.PointLight ) {
  14477. pointCount += 1;
  14478. if ( ! light.visible ) continue;
  14479. pointOffset = pointLength * 3;
  14480. if ( _this.gammaInput ) {
  14481. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14482. } else {
  14483. setColorLinear( pointColors, pointOffset, color, intensity );
  14484. }
  14485. _vector3.getPositionFromMatrix( light.matrixWorld );
  14486. pointPositions[ pointOffset ] = _vector3.x;
  14487. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14488. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14489. pointDistances[ pointLength ] = distance;
  14490. pointLength += 1;
  14491. } else if ( light instanceof THREE.SpotLight ) {
  14492. spotCount += 1;
  14493. if ( ! light.visible ) continue;
  14494. spotOffset = spotLength * 3;
  14495. if ( _this.gammaInput ) {
  14496. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14497. } else {
  14498. setColorLinear( spotColors, spotOffset, color, intensity );
  14499. }
  14500. _vector3.getPositionFromMatrix( light.matrixWorld );
  14501. spotPositions[ spotOffset ] = _vector3.x;
  14502. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14503. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14504. spotDistances[ spotLength ] = distance;
  14505. _direction.copy( _vector3 );
  14506. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14507. _direction.sub( _vector3 );
  14508. _direction.normalize();
  14509. spotDirections[ spotOffset ] = _direction.x;
  14510. spotDirections[ spotOffset + 1 ] = _direction.y;
  14511. spotDirections[ spotOffset + 2 ] = _direction.z;
  14512. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14513. spotExponents[ spotLength ] = light.exponent;
  14514. spotLength += 1;
  14515. } else if ( light instanceof THREE.HemisphereLight ) {
  14516. hemiCount += 1;
  14517. if ( ! light.visible ) continue;
  14518. _direction.getPositionFromMatrix( light.matrixWorld );
  14519. _direction.normalize();
  14520. // skip lights with undefined direction
  14521. // these create troubles in OpenGL (making pixel black)
  14522. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14523. hemiOffset = hemiLength * 3;
  14524. hemiPositions[ hemiOffset ] = _direction.x;
  14525. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14526. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14527. skyColor = light.color;
  14528. groundColor = light.groundColor;
  14529. if ( _this.gammaInput ) {
  14530. intensitySq = intensity * intensity;
  14531. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14532. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14533. } else {
  14534. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14535. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14536. }
  14537. hemiLength += 1;
  14538. }
  14539. }
  14540. // null eventual remains from removed lights
  14541. // (this is to avoid if in shader)
  14542. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14543. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14544. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14545. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14546. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14547. zlights.directional.length = dirLength;
  14548. zlights.point.length = pointLength;
  14549. zlights.spot.length = spotLength;
  14550. zlights.hemi.length = hemiLength;
  14551. zlights.ambient[ 0 ] = r;
  14552. zlights.ambient[ 1 ] = g;
  14553. zlights.ambient[ 2 ] = b;
  14554. };
  14555. // GL state setting
  14556. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14557. if ( cullFace === THREE.CullFaceNone ) {
  14558. _gl.disable( _gl.CULL_FACE );
  14559. } else {
  14560. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14561. _gl.frontFace( _gl.CW );
  14562. } else {
  14563. _gl.frontFace( _gl.CCW );
  14564. }
  14565. if ( cullFace === THREE.CullFaceBack ) {
  14566. _gl.cullFace( _gl.BACK );
  14567. } else if ( cullFace === THREE.CullFaceFront ) {
  14568. _gl.cullFace( _gl.FRONT );
  14569. } else {
  14570. _gl.cullFace( _gl.FRONT_AND_BACK );
  14571. }
  14572. _gl.enable( _gl.CULL_FACE );
  14573. }
  14574. };
  14575. this.setMaterialFaces = function ( material ) {
  14576. var doubleSided = material.side === THREE.DoubleSide;
  14577. var flipSided = material.side === THREE.BackSide;
  14578. if ( _oldDoubleSided !== doubleSided ) {
  14579. if ( doubleSided ) {
  14580. _gl.disable( _gl.CULL_FACE );
  14581. } else {
  14582. _gl.enable( _gl.CULL_FACE );
  14583. }
  14584. _oldDoubleSided = doubleSided;
  14585. }
  14586. if ( _oldFlipSided !== flipSided ) {
  14587. if ( flipSided ) {
  14588. _gl.frontFace( _gl.CW );
  14589. } else {
  14590. _gl.frontFace( _gl.CCW );
  14591. }
  14592. _oldFlipSided = flipSided;
  14593. }
  14594. };
  14595. this.setDepthTest = function ( depthTest ) {
  14596. if ( _oldDepthTest !== depthTest ) {
  14597. if ( depthTest ) {
  14598. _gl.enable( _gl.DEPTH_TEST );
  14599. } else {
  14600. _gl.disable( _gl.DEPTH_TEST );
  14601. }
  14602. _oldDepthTest = depthTest;
  14603. }
  14604. };
  14605. this.setDepthWrite = function ( depthWrite ) {
  14606. if ( _oldDepthWrite !== depthWrite ) {
  14607. _gl.depthMask( depthWrite );
  14608. _oldDepthWrite = depthWrite;
  14609. }
  14610. };
  14611. function setLineWidth ( width ) {
  14612. if ( width !== _oldLineWidth ) {
  14613. _gl.lineWidth( width );
  14614. _oldLineWidth = width;
  14615. }
  14616. };
  14617. function setPolygonOffset ( polygonoffset, factor, units ) {
  14618. if ( _oldPolygonOffset !== polygonoffset ) {
  14619. if ( polygonoffset ) {
  14620. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14621. } else {
  14622. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14623. }
  14624. _oldPolygonOffset = polygonoffset;
  14625. }
  14626. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14627. _gl.polygonOffset( factor, units );
  14628. _oldPolygonOffsetFactor = factor;
  14629. _oldPolygonOffsetUnits = units;
  14630. }
  14631. };
  14632. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14633. if ( blending !== _oldBlending ) {
  14634. if ( blending === THREE.NoBlending ) {
  14635. _gl.disable( _gl.BLEND );
  14636. } else if ( blending === THREE.AdditiveBlending ) {
  14637. _gl.enable( _gl.BLEND );
  14638. _gl.blendEquation( _gl.FUNC_ADD );
  14639. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14640. } else if ( blending === THREE.SubtractiveBlending ) {
  14641. // TODO: Find blendFuncSeparate() combination
  14642. _gl.enable( _gl.BLEND );
  14643. _gl.blendEquation( _gl.FUNC_ADD );
  14644. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14645. } else if ( blending === THREE.MultiplyBlending ) {
  14646. // TODO: Find blendFuncSeparate() combination
  14647. _gl.enable( _gl.BLEND );
  14648. _gl.blendEquation( _gl.FUNC_ADD );
  14649. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14650. } else if ( blending === THREE.CustomBlending ) {
  14651. _gl.enable( _gl.BLEND );
  14652. } else {
  14653. _gl.enable( _gl.BLEND );
  14654. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14655. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14656. }
  14657. _oldBlending = blending;
  14658. }
  14659. if ( blending === THREE.CustomBlending ) {
  14660. if ( blendEquation !== _oldBlendEquation ) {
  14661. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14662. _oldBlendEquation = blendEquation;
  14663. }
  14664. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14665. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14666. _oldBlendSrc = blendSrc;
  14667. _oldBlendDst = blendDst;
  14668. }
  14669. } else {
  14670. _oldBlendEquation = null;
  14671. _oldBlendSrc = null;
  14672. _oldBlendDst = null;
  14673. }
  14674. };
  14675. // Defines
  14676. function generateDefines ( defines ) {
  14677. var value, chunk, chunks = [];
  14678. for ( var d in defines ) {
  14679. value = defines[ d ];
  14680. if ( value === false ) continue;
  14681. chunk = "#define " + d + " " + value;
  14682. chunks.push( chunk );
  14683. }
  14684. return chunks.join( "\n" );
  14685. };
  14686. // Shaders
  14687. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  14688. var p, pl, d, program, code;
  14689. var chunks = [];
  14690. // Generate code
  14691. if ( shaderID ) {
  14692. chunks.push( shaderID );
  14693. } else {
  14694. chunks.push( fragmentShader );
  14695. chunks.push( vertexShader );
  14696. }
  14697. for ( d in defines ) {
  14698. chunks.push( d );
  14699. chunks.push( defines[ d ] );
  14700. }
  14701. for ( p in parameters ) {
  14702. chunks.push( p );
  14703. chunks.push( parameters[ p ] );
  14704. }
  14705. code = chunks.join();
  14706. // Check if code has been already compiled
  14707. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14708. var programInfo = _programs[ p ];
  14709. if ( programInfo.code === code ) {
  14710. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  14711. programInfo.usedTimes ++;
  14712. return programInfo.program;
  14713. }
  14714. }
  14715. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14716. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14717. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14718. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14719. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14720. }
  14721. // console.log( "building new program " );
  14722. //
  14723. var customDefines = generateDefines( defines );
  14724. //
  14725. program = _gl.createProgram();
  14726. var prefix_vertex = [
  14727. "precision " + _precision + " float;",
  14728. customDefines,
  14729. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14730. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14731. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14732. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14733. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14734. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14735. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14736. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14737. "#define MAX_SHADOWS " + parameters.maxShadows,
  14738. "#define MAX_BONES " + parameters.maxBones,
  14739. parameters.map ? "#define USE_MAP" : "",
  14740. parameters.envMap ? "#define USE_ENVMAP" : "",
  14741. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14742. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14743. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14744. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14745. parameters.vertexColors ? "#define USE_COLOR" : "",
  14746. parameters.skinning ? "#define USE_SKINNING" : "",
  14747. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14748. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  14749. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  14750. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14751. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14752. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14753. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14754. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14755. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14756. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14757. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14758. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14759. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14760. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14761. "uniform mat4 modelMatrix;",
  14762. "uniform mat4 modelViewMatrix;",
  14763. "uniform mat4 projectionMatrix;",
  14764. "uniform mat4 viewMatrix;",
  14765. "uniform mat3 normalMatrix;",
  14766. "uniform vec3 cameraPosition;",
  14767. "attribute vec3 position;",
  14768. "attribute vec3 normal;",
  14769. "attribute vec2 uv;",
  14770. "attribute vec2 uv2;",
  14771. "#ifdef USE_COLOR",
  14772. "attribute vec3 color;",
  14773. "#endif",
  14774. "#ifdef USE_MORPHTARGETS",
  14775. "attribute vec3 morphTarget0;",
  14776. "attribute vec3 morphTarget1;",
  14777. "attribute vec3 morphTarget2;",
  14778. "attribute vec3 morphTarget3;",
  14779. "#ifdef USE_MORPHNORMALS",
  14780. "attribute vec3 morphNormal0;",
  14781. "attribute vec3 morphNormal1;",
  14782. "attribute vec3 morphNormal2;",
  14783. "attribute vec3 morphNormal3;",
  14784. "#else",
  14785. "attribute vec3 morphTarget4;",
  14786. "attribute vec3 morphTarget5;",
  14787. "attribute vec3 morphTarget6;",
  14788. "attribute vec3 morphTarget7;",
  14789. "#endif",
  14790. "#endif",
  14791. "#ifdef USE_SKINNING",
  14792. "attribute vec4 skinIndex;",
  14793. "attribute vec4 skinWeight;",
  14794. "#endif",
  14795. ""
  14796. ].join("\n");
  14797. var prefix_fragment = [
  14798. "precision " + _precision + " float;",
  14799. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14800. customDefines,
  14801. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14802. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14803. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14804. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14805. "#define MAX_SHADOWS " + parameters.maxShadows,
  14806. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14807. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14808. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14809. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14810. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14811. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14812. parameters.map ? "#define USE_MAP" : "",
  14813. parameters.envMap ? "#define USE_ENVMAP" : "",
  14814. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14815. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14816. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14817. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14818. parameters.vertexColors ? "#define USE_COLOR" : "",
  14819. parameters.metal ? "#define METAL" : "",
  14820. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14821. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14822. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14823. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14824. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14825. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14826. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14827. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14828. "uniform mat4 viewMatrix;",
  14829. "uniform vec3 cameraPosition;",
  14830. ""
  14831. ].join("\n");
  14832. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14833. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14834. _gl.attachShader( program, glVertexShader );
  14835. _gl.attachShader( program, glFragmentShader );
  14836. _gl.linkProgram( program );
  14837. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14838. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14839. }
  14840. // clean up
  14841. _gl.deleteShader( glFragmentShader );
  14842. _gl.deleteShader( glVertexShader );
  14843. // console.log( prefix_fragment + fragmentShader );
  14844. // console.log( prefix_vertex + vertexShader );
  14845. program.uniforms = {};
  14846. program.attributes = {};
  14847. var identifiers, u, a, i;
  14848. // cache uniform locations
  14849. identifiers = [
  14850. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14851. 'morphTargetInfluences'
  14852. ];
  14853. if ( parameters.useVertexTexture ) {
  14854. identifiers.push( 'boneTexture' );
  14855. } else {
  14856. identifiers.push( 'boneGlobalMatrices' );
  14857. }
  14858. for ( u in uniforms ) {
  14859. identifiers.push( u );
  14860. }
  14861. cacheUniformLocations( program, identifiers );
  14862. // cache attributes locations
  14863. identifiers = [
  14864. "position", "normal", "uv", "uv2", "tangent", "color",
  14865. "skinIndex", "skinWeight", "lineDistance"
  14866. ];
  14867. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14868. identifiers.push( "morphTarget" + i );
  14869. }
  14870. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14871. identifiers.push( "morphNormal" + i );
  14872. }
  14873. for ( a in attributes ) {
  14874. identifiers.push( a );
  14875. }
  14876. cacheAttributeLocations( program, identifiers );
  14877. program.id = _programs_counter ++;
  14878. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14879. _this.info.memory.programs = _programs.length;
  14880. return program;
  14881. };
  14882. // Shader parameters cache
  14883. function cacheUniformLocations ( program, identifiers ) {
  14884. var i, l, id;
  14885. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14886. id = identifiers[ i ];
  14887. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14888. }
  14889. };
  14890. function cacheAttributeLocations ( program, identifiers ) {
  14891. var i, l, id;
  14892. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14893. id = identifiers[ i ];
  14894. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14895. }
  14896. };
  14897. function addLineNumbers ( string ) {
  14898. var chunks = string.split( "\n" );
  14899. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14900. // Chrome reports shader errors on lines
  14901. // starting counting from 1
  14902. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14903. }
  14904. return chunks.join( "\n" );
  14905. };
  14906. function getShader ( type, string ) {
  14907. var shader;
  14908. if ( type === "fragment" ) {
  14909. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14910. } else if ( type === "vertex" ) {
  14911. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14912. }
  14913. _gl.shaderSource( shader, string );
  14914. _gl.compileShader( shader );
  14915. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14916. console.error( _gl.getShaderInfoLog( shader ) );
  14917. console.error( addLineNumbers( string ) );
  14918. return null;
  14919. }
  14920. return shader;
  14921. };
  14922. // Textures
  14923. function isPowerOfTwo ( value ) {
  14924. return ( value & ( value - 1 ) ) === 0;
  14925. };
  14926. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14927. if ( isImagePowerOfTwo ) {
  14928. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14929. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14930. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14931. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14932. } else {
  14933. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14934. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14935. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14936. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14937. }
  14938. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14939. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14940. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14941. texture.__oldAnisotropy = texture.anisotropy;
  14942. }
  14943. }
  14944. };
  14945. this.setTexture = function ( texture, slot ) {
  14946. if ( texture.needsUpdate ) {
  14947. if ( ! texture.__webglInit ) {
  14948. texture.__webglInit = true;
  14949. texture.addEventListener( 'dispose', onTextureDispose );
  14950. texture.__webglTexture = _gl.createTexture();
  14951. _this.info.memory.textures ++;
  14952. }
  14953. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14954. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14955. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14956. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14957. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14958. var image = texture.image,
  14959. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14960. glFormat = paramThreeToGL( texture.format ),
  14961. glType = paramThreeToGL( texture.type );
  14962. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14963. var mipmap, mipmaps = texture.mipmaps;
  14964. if ( texture instanceof THREE.DataTexture ) {
  14965. // use manually created mipmaps if available
  14966. // if there are no manual mipmaps
  14967. // set 0 level mipmap and then use GL to generate other mipmap levels
  14968. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14969. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14970. mipmap = mipmaps[ i ];
  14971. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14972. }
  14973. texture.generateMipmaps = false;
  14974. } else {
  14975. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14976. }
  14977. } else if ( texture instanceof THREE.CompressedTexture ) {
  14978. // compressed textures can only use manually created mipmaps
  14979. // WebGL can't generate mipmaps for DDS textures
  14980. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14981. mipmap = mipmaps[ i ];
  14982. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14983. }
  14984. } else { // regular Texture (image, video, canvas)
  14985. // use manually created mipmaps if available
  14986. // if there are no manual mipmaps
  14987. // set 0 level mipmap and then use GL to generate other mipmap levels
  14988. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14989. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14990. mipmap = mipmaps[ i ];
  14991. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14992. }
  14993. texture.generateMipmaps = false;
  14994. } else {
  14995. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14996. }
  14997. }
  14998. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14999. texture.needsUpdate = false;
  15000. if ( texture.onUpdate ) texture.onUpdate();
  15001. } else {
  15002. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15003. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15004. }
  15005. };
  15006. function clampToMaxSize ( image, maxSize ) {
  15007. if ( image.width <= maxSize && image.height <= maxSize ) {
  15008. return image;
  15009. }
  15010. // Warning: Scaling through the canvas will only work with images that use
  15011. // premultiplied alpha.
  15012. var maxDimension = Math.max( image.width, image.height );
  15013. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15014. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15015. var canvas = document.createElement( 'canvas' );
  15016. canvas.width = newWidth;
  15017. canvas.height = newHeight;
  15018. var ctx = canvas.getContext( "2d" );
  15019. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15020. return canvas;
  15021. }
  15022. function setCubeTexture ( texture, slot ) {
  15023. if ( texture.image.length === 6 ) {
  15024. if ( texture.needsUpdate ) {
  15025. if ( ! texture.image.__webglTextureCube ) {
  15026. texture.image.__webglTextureCube = _gl.createTexture();
  15027. _this.info.memory.textures ++;
  15028. }
  15029. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15030. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15031. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15032. var isCompressed = texture instanceof THREE.CompressedTexture;
  15033. var cubeImage = [];
  15034. for ( var i = 0; i < 6; i ++ ) {
  15035. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15036. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15037. } else {
  15038. cubeImage[ i ] = texture.image[ i ];
  15039. }
  15040. }
  15041. var image = cubeImage[ 0 ],
  15042. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15043. glFormat = paramThreeToGL( texture.format ),
  15044. glType = paramThreeToGL( texture.type );
  15045. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15046. for ( var i = 0; i < 6; i ++ ) {
  15047. if ( isCompressed ) {
  15048. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15049. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15050. mipmap = mipmaps[ j ];
  15051. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15052. }
  15053. } else {
  15054. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15055. }
  15056. }
  15057. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15058. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15059. }
  15060. texture.needsUpdate = false;
  15061. if ( texture.onUpdate ) texture.onUpdate();
  15062. } else {
  15063. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15064. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15065. }
  15066. }
  15067. };
  15068. function setCubeTextureDynamic ( texture, slot ) {
  15069. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15070. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15071. };
  15072. // Render targets
  15073. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15074. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15075. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15076. };
  15077. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15078. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15079. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15080. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15081. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15082. /* For some reason this is not working. Defaulting to RGBA4.
  15083. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15084. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15085. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15086. */
  15087. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15088. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15089. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15090. } else {
  15091. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15092. }
  15093. };
  15094. this.setRenderTarget = function ( renderTarget ) {
  15095. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15096. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15097. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15098. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15099. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15100. renderTarget.__webglTexture = _gl.createTexture();
  15101. _this.info.memory.textures ++;
  15102. // Setup texture, create render and frame buffers
  15103. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  15104. glFormat = paramThreeToGL( renderTarget.format ),
  15105. glType = paramThreeToGL( renderTarget.type );
  15106. if ( isCube ) {
  15107. renderTarget.__webglFramebuffer = [];
  15108. renderTarget.__webglRenderbuffer = [];
  15109. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15110. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15111. for ( var i = 0; i < 6; i ++ ) {
  15112. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15113. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15114. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15115. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15116. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15117. }
  15118. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15119. } else {
  15120. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15121. if ( renderTarget.shareDepthFrom ) {
  15122. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15123. } else {
  15124. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15125. }
  15126. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15127. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15128. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15129. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15130. if ( renderTarget.shareDepthFrom ) {
  15131. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15132. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15133. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15134. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15135. }
  15136. } else {
  15137. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15138. }
  15139. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15140. }
  15141. // Release everything
  15142. if ( isCube ) {
  15143. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15144. } else {
  15145. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15146. }
  15147. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15148. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15149. }
  15150. var framebuffer, width, height, vx, vy;
  15151. if ( renderTarget ) {
  15152. if ( isCube ) {
  15153. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15154. } else {
  15155. framebuffer = renderTarget.__webglFramebuffer;
  15156. }
  15157. width = renderTarget.width;
  15158. height = renderTarget.height;
  15159. vx = 0;
  15160. vy = 0;
  15161. } else {
  15162. framebuffer = null;
  15163. width = _viewportWidth;
  15164. height = _viewportHeight;
  15165. vx = _viewportX;
  15166. vy = _viewportY;
  15167. }
  15168. if ( framebuffer !== _currentFramebuffer ) {
  15169. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15170. _gl.viewport( vx, vy, width, height );
  15171. _currentFramebuffer = framebuffer;
  15172. }
  15173. _currentWidth = width;
  15174. _currentHeight = height;
  15175. };
  15176. function updateRenderTargetMipmap ( renderTarget ) {
  15177. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15178. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15179. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15180. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15181. } else {
  15182. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15183. _gl.generateMipmap( _gl.TEXTURE_2D );
  15184. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15185. }
  15186. };
  15187. // Fallback filters for non-power-of-2 textures
  15188. function filterFallback ( f ) {
  15189. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15190. return _gl.NEAREST;
  15191. }
  15192. return _gl.LINEAR;
  15193. };
  15194. // Map three.js constants to WebGL constants
  15195. function paramThreeToGL ( p ) {
  15196. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15197. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15198. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15199. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15200. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15201. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15202. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15203. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15204. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15205. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15206. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15207. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15208. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15209. if ( p === THREE.ByteType ) return _gl.BYTE;
  15210. if ( p === THREE.ShortType ) return _gl.SHORT;
  15211. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15212. if ( p === THREE.IntType ) return _gl.INT;
  15213. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15214. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15215. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15216. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15217. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15218. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15219. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15220. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15221. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15222. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15223. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15224. if ( p === THREE.OneFactor ) return _gl.ONE;
  15225. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15226. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15227. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15228. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15229. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15230. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15231. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15232. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15233. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15234. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15235. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15236. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15237. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15238. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15239. }
  15240. return 0;
  15241. };
  15242. // Allocations
  15243. function allocateBones ( object ) {
  15244. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15245. return 1024;
  15246. } else {
  15247. // default for when object is not specified
  15248. // ( for example when prebuilding shader
  15249. // to be used with multiple objects )
  15250. //
  15251. // - leave some extra space for other uniforms
  15252. // - limit here is ANGLE's 254 max uniform vectors
  15253. // (up to 54 should be safe)
  15254. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15255. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15256. var maxBones = nVertexMatrices;
  15257. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15258. maxBones = Math.min( object.bones.length, maxBones );
  15259. if ( maxBones < object.bones.length ) {
  15260. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15261. }
  15262. }
  15263. return maxBones;
  15264. }
  15265. };
  15266. function allocateLights ( lights ) {
  15267. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  15268. dirLights = pointLights = spotLights = hemiLights = 0;
  15269. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  15270. light = lights[ l ];
  15271. if ( light.onlyShadow ) continue;
  15272. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15273. if ( light instanceof THREE.PointLight ) pointLights ++;
  15274. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15275. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15276. }
  15277. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15278. };
  15279. function allocateShadows ( lights ) {
  15280. var l, ll, light, maxShadows = 0;
  15281. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  15282. light = lights[ l ];
  15283. if ( ! light.castShadow ) continue;
  15284. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15285. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15286. }
  15287. return maxShadows;
  15288. };
  15289. // Initialization
  15290. function initGL () {
  15291. try {
  15292. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  15293. throw 'Error creating WebGL context.';
  15294. }
  15295. } catch ( error ) {
  15296. console.error( error );
  15297. }
  15298. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15299. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15300. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  15301. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  15302. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15303. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  15304. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  15305. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15306. if ( ! _glExtensionTextureFloat ) {
  15307. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15308. }
  15309. if ( ! _glExtensionStandardDerivatives ) {
  15310. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15311. }
  15312. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15313. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15314. }
  15315. if ( ! _glExtensionCompressedTextureS3TC ) {
  15316. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15317. }
  15318. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15319. _gl.getShaderPrecisionFormat = function() {
  15320. return {
  15321. "rangeMin" : 1,
  15322. "rangeMax" : 1,
  15323. "precision" : 1
  15324. };
  15325. }
  15326. }
  15327. };
  15328. function setDefaultGLState () {
  15329. _gl.clearColor( 0, 0, 0, 1 );
  15330. _gl.clearDepth( 1 );
  15331. _gl.clearStencil( 0 );
  15332. _gl.enable( _gl.DEPTH_TEST );
  15333. _gl.depthFunc( _gl.LEQUAL );
  15334. _gl.frontFace( _gl.CCW );
  15335. _gl.cullFace( _gl.BACK );
  15336. _gl.enable( _gl.CULL_FACE );
  15337. _gl.enable( _gl.BLEND );
  15338. _gl.blendEquation( _gl.FUNC_ADD );
  15339. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15340. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15341. };
  15342. // default plugins (order is important)
  15343. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15344. this.addPrePlugin( this.shadowMapPlugin );
  15345. this.addPostPlugin( new THREE.SpritePlugin() );
  15346. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15347. };
  15348. /**
  15349. * @author szimek / https://github.com/szimek/
  15350. * @author alteredq / http://alteredqualia.com/
  15351. */
  15352. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15353. this.width = width;
  15354. this.height = height;
  15355. options = options || {};
  15356. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15357. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15358. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15359. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15360. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15361. this.offset = new THREE.Vector2( 0, 0 );
  15362. this.repeat = new THREE.Vector2( 1, 1 );
  15363. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15364. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15365. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15366. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15367. this.generateMipmaps = true;
  15368. this.shareDepthFrom = null;
  15369. };
  15370. THREE.WebGLRenderTarget.prototype = {
  15371. constructor: THREE.WebGLRenderTarget,
  15372. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  15373. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  15374. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  15375. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  15376. clone: function () {
  15377. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15378. tmp.wrapS = this.wrapS;
  15379. tmp.wrapT = this.wrapT;
  15380. tmp.magFilter = this.magFilter;
  15381. tmp.minFilter = this.minFilter;
  15382. tmp.anisotropy = this.anisotropy;
  15383. tmp.offset.copy( this.offset );
  15384. tmp.repeat.copy( this.repeat );
  15385. tmp.format = this.format;
  15386. tmp.type = this.type;
  15387. tmp.depthBuffer = this.depthBuffer;
  15388. tmp.stencilBuffer = this.stencilBuffer;
  15389. tmp.generateMipmaps = this.generateMipmaps;
  15390. tmp.shareDepthFrom = this.shareDepthFrom;
  15391. return tmp;
  15392. },
  15393. dispose: function () {
  15394. this.dispatchEvent( { type: 'dispose' } );
  15395. }
  15396. };
  15397. /**
  15398. * @author alteredq / http://alteredqualia.com
  15399. */
  15400. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15401. THREE.WebGLRenderTarget.call( this, width, height, options );
  15402. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15403. };
  15404. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15405. /**
  15406. * @author mrdoob / http://mrdoob.com/
  15407. */
  15408. THREE.RenderableVertex = function () {
  15409. this.positionWorld = new THREE.Vector3();
  15410. this.positionScreen = new THREE.Vector4();
  15411. this.visible = true;
  15412. };
  15413. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15414. this.positionWorld.copy( vertex.positionWorld );
  15415. this.positionScreen.copy( vertex.positionScreen );
  15416. };
  15417. /**
  15418. * @author mrdoob / http://mrdoob.com/
  15419. */
  15420. THREE.RenderableFace3 = function () {
  15421. this.v1 = new THREE.RenderableVertex();
  15422. this.v2 = new THREE.RenderableVertex();
  15423. this.v3 = new THREE.RenderableVertex();
  15424. this.centroidModel = new THREE.Vector3();
  15425. this.normalModel = new THREE.Vector3();
  15426. this.normalModelView = new THREE.Vector3();
  15427. this.vertexNormalsLength = 0;
  15428. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15429. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15430. this.color = null;
  15431. this.material = null;
  15432. this.uvs = [[]];
  15433. this.z = null;
  15434. };
  15435. /**
  15436. * @author mrdoob / http://mrdoob.com/
  15437. */
  15438. THREE.RenderableFace4 = function () {
  15439. this.v1 = new THREE.RenderableVertex();
  15440. this.v2 = new THREE.RenderableVertex();
  15441. this.v3 = new THREE.RenderableVertex();
  15442. this.v4 = new THREE.RenderableVertex();
  15443. this.centroidModel = new THREE.Vector3();
  15444. this.normalModel = new THREE.Vector3();
  15445. this.normalModelView = new THREE.Vector3();
  15446. this.vertexNormalsLength = 0;
  15447. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15448. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15449. this.color = null;
  15450. this.material = null;
  15451. this.uvs = [[]];
  15452. this.z = null;
  15453. };
  15454. /**
  15455. * @author mrdoob / http://mrdoob.com/
  15456. */
  15457. THREE.RenderableObject = function () {
  15458. this.object = null;
  15459. this.z = null;
  15460. };
  15461. /**
  15462. * @author mrdoob / http://mrdoob.com/
  15463. */
  15464. THREE.RenderableParticle = function () {
  15465. this.object = null;
  15466. this.x = null;
  15467. this.y = null;
  15468. this.z = null;
  15469. this.rotation = null;
  15470. this.scale = new THREE.Vector2();
  15471. this.material = null;
  15472. };
  15473. /**
  15474. * @author mrdoob / http://mrdoob.com/
  15475. */
  15476. THREE.RenderableLine = function () {
  15477. this.z = null;
  15478. this.v1 = new THREE.RenderableVertex();
  15479. this.v2 = new THREE.RenderableVertex();
  15480. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15481. this.material = null;
  15482. };
  15483. /**
  15484. * @author mrdoob / http://mrdoob.com/
  15485. * @author alteredq / http://alteredqualia.com/
  15486. */
  15487. THREE.GeometryUtils = {
  15488. // Merge two geometries or geometry and geometry from object (using object's transform)
  15489. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15490. var matrix, normalMatrix,
  15491. vertexOffset = geometry1.vertices.length,
  15492. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15493. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15494. vertices1 = geometry1.vertices,
  15495. vertices2 = geometry2.vertices,
  15496. faces1 = geometry1.faces,
  15497. faces2 = geometry2.faces,
  15498. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15499. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15500. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15501. if ( object2 instanceof THREE.Mesh ) {
  15502. object2.matrixAutoUpdate && object2.updateMatrix();
  15503. matrix = object2.matrix;
  15504. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15505. }
  15506. // vertices
  15507. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15508. var vertex = vertices2[ i ];
  15509. var vertexCopy = vertex.clone();
  15510. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15511. vertices1.push( vertexCopy );
  15512. }
  15513. // faces
  15514. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15515. var face = faces2[ i ], faceCopy, normal, color,
  15516. faceVertexNormals = face.vertexNormals,
  15517. faceVertexColors = face.vertexColors;
  15518. if ( face instanceof THREE.Face3 ) {
  15519. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15520. } else if ( face instanceof THREE.Face4 ) {
  15521. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  15522. }
  15523. faceCopy.normal.copy( face.normal );
  15524. if ( normalMatrix ) {
  15525. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15526. }
  15527. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15528. normal = faceVertexNormals[ j ].clone();
  15529. if ( normalMatrix ) {
  15530. normal.applyMatrix3( normalMatrix ).normalize();
  15531. }
  15532. faceCopy.vertexNormals.push( normal );
  15533. }
  15534. faceCopy.color.copy( face.color );
  15535. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15536. color = faceVertexColors[ j ];
  15537. faceCopy.vertexColors.push( color.clone() );
  15538. }
  15539. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15540. faceCopy.centroid.copy( face.centroid );
  15541. if ( matrix ) {
  15542. faceCopy.centroid.applyMatrix4( matrix );
  15543. }
  15544. faces1.push( faceCopy );
  15545. }
  15546. // uvs
  15547. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15548. var uv = uvs2[ i ], uvCopy = [];
  15549. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15550. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15551. }
  15552. uvs1.push( uvCopy );
  15553. }
  15554. },
  15555. removeMaterials: function ( geometry, materialIndexArray ) {
  15556. var materialIndexMap = {};
  15557. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  15558. materialIndexMap[ materialIndexArray[i] ] = true;
  15559. }
  15560. var face, newFaces = [];
  15561. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15562. face = geometry.faces[ i ];
  15563. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15564. }
  15565. geometry.faces = newFaces;
  15566. },
  15567. // Get random point in triangle (via barycentric coordinates)
  15568. // (uniform distribution)
  15569. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15570. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  15571. var a, b, c,
  15572. point = new THREE.Vector3(),
  15573. tmp = THREE.GeometryUtils.__v1;
  15574. a = THREE.GeometryUtils.random();
  15575. b = THREE.GeometryUtils.random();
  15576. if ( ( a + b ) > 1 ) {
  15577. a = 1 - a;
  15578. b = 1 - b;
  15579. }
  15580. c = 1 - a - b;
  15581. point.copy( vectorA );
  15582. point.multiplyScalar( a );
  15583. tmp.copy( vectorB );
  15584. tmp.multiplyScalar( b );
  15585. point.add( tmp );
  15586. tmp.copy( vectorC );
  15587. tmp.multiplyScalar( c );
  15588. point.add( tmp );
  15589. return point;
  15590. },
  15591. // Get random point in face (triangle / quad)
  15592. // (uniform distribution)
  15593. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15594. var vA, vB, vC, vD;
  15595. if ( face instanceof THREE.Face3 ) {
  15596. vA = geometry.vertices[ face.a ];
  15597. vB = geometry.vertices[ face.b ];
  15598. vC = geometry.vertices[ face.c ];
  15599. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15600. } else if ( face instanceof THREE.Face4 ) {
  15601. vA = geometry.vertices[ face.a ];
  15602. vB = geometry.vertices[ face.b ];
  15603. vC = geometry.vertices[ face.c ];
  15604. vD = geometry.vertices[ face.d ];
  15605. var area1, area2;
  15606. if ( useCachedAreas ) {
  15607. if ( face._area1 && face._area2 ) {
  15608. area1 = face._area1;
  15609. area2 = face._area2;
  15610. } else {
  15611. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15612. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15613. face._area1 = area1;
  15614. face._area2 = area2;
  15615. }
  15616. } else {
  15617. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  15618. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15619. }
  15620. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  15621. if ( r < area1 ) {
  15622. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  15623. } else {
  15624. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  15625. }
  15626. }
  15627. },
  15628. // Get uniformly distributed random points in mesh
  15629. // - create array with cumulative sums of face areas
  15630. // - pick random number from 0 to total area
  15631. // - find corresponding place in area array by binary search
  15632. // - get random point in face
  15633. randomPointsInGeometry: function ( geometry, n ) {
  15634. var face, i,
  15635. faces = geometry.faces,
  15636. vertices = geometry.vertices,
  15637. il = faces.length,
  15638. totalArea = 0,
  15639. cumulativeAreas = [],
  15640. vA, vB, vC, vD;
  15641. // precompute face areas
  15642. for ( i = 0; i < il; i ++ ) {
  15643. face = faces[ i ];
  15644. if ( face instanceof THREE.Face3 ) {
  15645. vA = vertices[ face.a ];
  15646. vB = vertices[ face.b ];
  15647. vC = vertices[ face.c ];
  15648. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15649. } else if ( face instanceof THREE.Face4 ) {
  15650. vA = vertices[ face.a ];
  15651. vB = vertices[ face.b ];
  15652. vC = vertices[ face.c ];
  15653. vD = vertices[ face.d ];
  15654. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15655. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15656. face._area = face._area1 + face._area2;
  15657. }
  15658. totalArea += face._area;
  15659. cumulativeAreas[ i ] = totalArea;
  15660. }
  15661. // binary search cumulative areas array
  15662. function binarySearchIndices( value ) {
  15663. function binarySearch( start, end ) {
  15664. // return closest larger index
  15665. // if exact number is not found
  15666. if ( end < start )
  15667. return start;
  15668. var mid = start + Math.floor( ( end - start ) / 2 );
  15669. if ( cumulativeAreas[ mid ] > value ) {
  15670. return binarySearch( start, mid - 1 );
  15671. } else if ( cumulativeAreas[ mid ] < value ) {
  15672. return binarySearch( mid + 1, end );
  15673. } else {
  15674. return mid;
  15675. }
  15676. }
  15677. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15678. return result;
  15679. }
  15680. // pick random face weighted by face area
  15681. var r, index,
  15682. result = [];
  15683. var stats = {};
  15684. for ( i = 0; i < n; i ++ ) {
  15685. r = THREE.GeometryUtils.random() * totalArea;
  15686. index = binarySearchIndices( r );
  15687. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15688. if ( ! stats[ index ] ) {
  15689. stats[ index ] = 1;
  15690. } else {
  15691. stats[ index ] += 1;
  15692. }
  15693. }
  15694. return result;
  15695. },
  15696. // Get triangle area (half of parallelogram)
  15697. // http://mathworld.wolfram.com/TriangleArea.html
  15698. triangleArea: function ( vectorA, vectorB, vectorC ) {
  15699. var tmp1 = THREE.GeometryUtils.__v1,
  15700. tmp2 = THREE.GeometryUtils.__v2;
  15701. tmp1.subVectors( vectorB, vectorA );
  15702. tmp2.subVectors( vectorC, vectorA );
  15703. tmp1.cross( tmp2 );
  15704. return 0.5 * tmp1.length();
  15705. },
  15706. // Center geometry so that 0,0,0 is in center of bounding box
  15707. center: function ( geometry ) {
  15708. geometry.computeBoundingBox();
  15709. var bb = geometry.boundingBox;
  15710. var offset = new THREE.Vector3();
  15711. offset.addVectors( bb.min, bb.max );
  15712. offset.multiplyScalar( -0.5 );
  15713. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15714. geometry.computeBoundingBox();
  15715. return offset;
  15716. },
  15717. // Normalize UVs to be from <0,1>
  15718. // (for now just the first set of UVs)
  15719. normalizeUVs: function ( geometry ) {
  15720. var uvSet = geometry.faceVertexUvs[ 0 ];
  15721. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  15722. var uvs = uvSet[ i ];
  15723. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  15724. // texture repeat
  15725. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  15726. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  15727. }
  15728. }
  15729. },
  15730. triangulateQuads: function ( geometry ) {
  15731. var i, il, j, jl;
  15732. var faces = [];
  15733. var faceUvs = [];
  15734. var faceVertexUvs = [];
  15735. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  15736. faceUvs[ i ] = [];
  15737. }
  15738. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15739. faceVertexUvs[ i ] = [];
  15740. }
  15741. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15742. var face = geometry.faces[ i ];
  15743. if ( face instanceof THREE.Face4 ) {
  15744. var a = face.a;
  15745. var b = face.b;
  15746. var c = face.c;
  15747. var d = face.d;
  15748. var triA = new THREE.Face3();
  15749. var triB = new THREE.Face3();
  15750. triA.color.copy( face.color );
  15751. triB.color.copy( face.color );
  15752. triA.materialIndex = face.materialIndex;
  15753. triB.materialIndex = face.materialIndex;
  15754. triA.a = a;
  15755. triA.b = b;
  15756. triA.c = d;
  15757. triB.a = b;
  15758. triB.b = c;
  15759. triB.c = d;
  15760. if ( face.vertexColors.length === 4 ) {
  15761. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  15762. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  15763. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15764. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  15765. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  15766. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15767. }
  15768. faces.push( triA, triB );
  15769. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15770. if ( geometry.faceVertexUvs[ j ].length ) {
  15771. var uvs = geometry.faceVertexUvs[ j ][ i ];
  15772. var uvA = uvs[ 0 ];
  15773. var uvB = uvs[ 1 ];
  15774. var uvC = uvs[ 2 ];
  15775. var uvD = uvs[ 3 ];
  15776. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  15777. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  15778. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  15779. }
  15780. }
  15781. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15782. if ( geometry.faceUvs[ j ].length ) {
  15783. var faceUv = geometry.faceUvs[ j ][ i ];
  15784. faceUvs[ j ].push( faceUv, faceUv );
  15785. }
  15786. }
  15787. } else {
  15788. faces.push( face );
  15789. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15790. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  15791. }
  15792. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15793. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15794. }
  15795. }
  15796. }
  15797. geometry.faces = faces;
  15798. geometry.faceUvs = faceUvs;
  15799. geometry.faceVertexUvs = faceVertexUvs;
  15800. geometry.computeCentroids();
  15801. geometry.computeFaceNormals();
  15802. geometry.computeVertexNormals();
  15803. if ( geometry.hasTangents ) geometry.computeTangents();
  15804. },
  15805. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  15806. var faces = geometry.faces;
  15807. var start = startFace || 0;
  15808. var end = endFace || faces.length - 1;
  15809. for ( var i = start; i <= end; i ++ ) {
  15810. faces[i].materialIndex = index;
  15811. }
  15812. }
  15813. };
  15814. THREE.GeometryUtils.random = THREE.Math.random16;
  15815. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  15816. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  15817. /**
  15818. * @author alteredq / http://alteredqualia.com/
  15819. * @author mrdoob / http://mrdoob.com/
  15820. */
  15821. THREE.ImageUtils = {
  15822. crossOrigin: 'anonymous',
  15823. loadTexture: function ( url, mapping, onLoad, onError ) {
  15824. var image = new Image();
  15825. var texture = new THREE.Texture( image, mapping );
  15826. var loader = new THREE.ImageLoader();
  15827. loader.addEventListener( 'load', function ( event ) {
  15828. texture.image = event.content;
  15829. texture.needsUpdate = true;
  15830. if ( onLoad ) onLoad( texture );
  15831. } );
  15832. loader.addEventListener( 'error', function ( event ) {
  15833. if ( onError ) onError( event.message );
  15834. } );
  15835. loader.crossOrigin = this.crossOrigin;
  15836. loader.load( url, image );
  15837. texture.sourceFile = url;
  15838. return texture;
  15839. },
  15840. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15841. var texture = new THREE.CompressedTexture();
  15842. texture.mapping = mapping;
  15843. var request = new XMLHttpRequest();
  15844. request.onload = function () {
  15845. var buffer = request.response;
  15846. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15847. texture.format = dds.format;
  15848. texture.mipmaps = dds.mipmaps;
  15849. texture.image.width = dds.width;
  15850. texture.image.height = dds.height;
  15851. // gl.generateMipmap fails for compressed textures
  15852. // mipmaps must be embedded in the DDS file
  15853. // or texture filters must not use mipmapping
  15854. texture.generateMipmaps = false;
  15855. texture.needsUpdate = true;
  15856. if ( onLoad ) onLoad( texture );
  15857. }
  15858. request.onerror = onError;
  15859. request.open( 'GET', url, true );
  15860. request.responseType = "arraybuffer";
  15861. request.send( null );
  15862. return texture;
  15863. },
  15864. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15865. var images = [];
  15866. images.loadCount = 0;
  15867. var texture = new THREE.Texture();
  15868. texture.image = images;
  15869. if ( mapping !== undefined ) texture.mapping = mapping;
  15870. // no flipping needed for cube textures
  15871. texture.flipY = false;
  15872. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15873. var cubeImage = new Image();
  15874. images[ i ] = cubeImage;
  15875. cubeImage.onload = function () {
  15876. images.loadCount += 1;
  15877. if ( images.loadCount === 6 ) {
  15878. texture.needsUpdate = true;
  15879. if ( onLoad ) onLoad( texture );
  15880. }
  15881. };
  15882. cubeImage.onerror = onError;
  15883. cubeImage.crossOrigin = this.crossOrigin;
  15884. cubeImage.src = array[ i ];
  15885. }
  15886. return texture;
  15887. },
  15888. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15889. var images = [];
  15890. images.loadCount = 0;
  15891. var texture = new THREE.CompressedTexture();
  15892. texture.image = images;
  15893. if ( mapping !== undefined ) texture.mapping = mapping;
  15894. // no flipping for cube textures
  15895. // (also flipping doesn't work for compressed textures )
  15896. texture.flipY = false;
  15897. // can't generate mipmaps for compressed textures
  15898. // mips must be embedded in DDS files
  15899. texture.generateMipmaps = false;
  15900. var generateCubeFaceCallback = function ( rq, img ) {
  15901. return function () {
  15902. var buffer = rq.response;
  15903. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15904. img.format = dds.format;
  15905. img.mipmaps = dds.mipmaps;
  15906. img.width = dds.width;
  15907. img.height = dds.height;
  15908. images.loadCount += 1;
  15909. if ( images.loadCount === 6 ) {
  15910. texture.format = dds.format;
  15911. texture.needsUpdate = true;
  15912. if ( onLoad ) onLoad( texture );
  15913. }
  15914. }
  15915. }
  15916. // compressed cubemap textures as 6 separate DDS files
  15917. if ( array instanceof Array ) {
  15918. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15919. var cubeImage = {};
  15920. images[ i ] = cubeImage;
  15921. var request = new XMLHttpRequest();
  15922. request.onload = generateCubeFaceCallback( request, cubeImage );
  15923. request.onerror = onError;
  15924. var url = array[ i ];
  15925. request.open( 'GET', url, true );
  15926. request.responseType = "arraybuffer";
  15927. request.send( null );
  15928. }
  15929. // compressed cubemap texture stored in a single DDS file
  15930. } else {
  15931. var url = array;
  15932. var request = new XMLHttpRequest();
  15933. request.onload = function( ) {
  15934. var buffer = request.response;
  15935. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15936. if ( dds.isCubemap ) {
  15937. var faces = dds.mipmaps.length / dds.mipmapCount;
  15938. for ( var f = 0; f < faces; f ++ ) {
  15939. images[ f ] = { mipmaps : [] };
  15940. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15941. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15942. images[ f ].format = dds.format;
  15943. images[ f ].width = dds.width;
  15944. images[ f ].height = dds.height;
  15945. }
  15946. }
  15947. texture.format = dds.format;
  15948. texture.needsUpdate = true;
  15949. if ( onLoad ) onLoad( texture );
  15950. }
  15951. }
  15952. request.onerror = onError;
  15953. request.open( 'GET', url, true );
  15954. request.responseType = "arraybuffer";
  15955. request.send( null );
  15956. }
  15957. return texture;
  15958. },
  15959. parseDDS: function ( buffer, loadMipmaps ) {
  15960. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15961. // Adapted from @toji's DDS utils
  15962. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15963. // All values and structures referenced from:
  15964. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15965. var DDS_MAGIC = 0x20534444;
  15966. var DDSD_CAPS = 0x1,
  15967. DDSD_HEIGHT = 0x2,
  15968. DDSD_WIDTH = 0x4,
  15969. DDSD_PITCH = 0x8,
  15970. DDSD_PIXELFORMAT = 0x1000,
  15971. DDSD_MIPMAPCOUNT = 0x20000,
  15972. DDSD_LINEARSIZE = 0x80000,
  15973. DDSD_DEPTH = 0x800000;
  15974. var DDSCAPS_COMPLEX = 0x8,
  15975. DDSCAPS_MIPMAP = 0x400000,
  15976. DDSCAPS_TEXTURE = 0x1000;
  15977. var DDSCAPS2_CUBEMAP = 0x200,
  15978. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15979. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15980. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15981. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15982. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15983. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15984. DDSCAPS2_VOLUME = 0x200000;
  15985. var DDPF_ALPHAPIXELS = 0x1,
  15986. DDPF_ALPHA = 0x2,
  15987. DDPF_FOURCC = 0x4,
  15988. DDPF_RGB = 0x40,
  15989. DDPF_YUV = 0x200,
  15990. DDPF_LUMINANCE = 0x20000;
  15991. function fourCCToInt32( value ) {
  15992. return value.charCodeAt(0) +
  15993. (value.charCodeAt(1) << 8) +
  15994. (value.charCodeAt(2) << 16) +
  15995. (value.charCodeAt(3) << 24);
  15996. }
  15997. function int32ToFourCC( value ) {
  15998. return String.fromCharCode(
  15999. value & 0xff,
  16000. (value >> 8) & 0xff,
  16001. (value >> 16) & 0xff,
  16002. (value >> 24) & 0xff
  16003. );
  16004. }
  16005. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  16006. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  16007. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  16008. var headerLengthInt = 31; // The header length in 32 bit ints
  16009. // Offsets into the header array
  16010. var off_magic = 0;
  16011. var off_size = 1;
  16012. var off_flags = 2;
  16013. var off_height = 3;
  16014. var off_width = 4;
  16015. var off_mipmapCount = 7;
  16016. var off_pfFlags = 20;
  16017. var off_pfFourCC = 21;
  16018. var off_caps = 27;
  16019. var off_caps2 = 28;
  16020. var off_caps3 = 29;
  16021. var off_caps4 = 30;
  16022. // Parse header
  16023. var header = new Int32Array( buffer, 0, headerLengthInt );
  16024. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16025. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16026. return dds;
  16027. }
  16028. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16029. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16030. return dds;
  16031. }
  16032. var blockBytes;
  16033. var fourCC = header[ off_pfFourCC ];
  16034. switch ( fourCC ) {
  16035. case FOURCC_DXT1:
  16036. blockBytes = 8;
  16037. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16038. break;
  16039. case FOURCC_DXT3:
  16040. blockBytes = 16;
  16041. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16042. break;
  16043. case FOURCC_DXT5:
  16044. blockBytes = 16;
  16045. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16046. break;
  16047. default:
  16048. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16049. return dds;
  16050. }
  16051. dds.mipmapCount = 1;
  16052. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16053. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16054. }
  16055. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16056. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16057. dds.width = header[ off_width ];
  16058. dds.height = header[ off_height ];
  16059. var dataOffset = header[ off_size ] + 4;
  16060. // Extract mipmaps buffers
  16061. var width = dds.width;
  16062. var height = dds.height;
  16063. var faces = dds.isCubemap ? 6 : 1;
  16064. for ( var face = 0; face < faces; face ++ ) {
  16065. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16066. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16067. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16068. var mipmap = { "data": byteArray, "width": width, "height": height };
  16069. dds.mipmaps.push( mipmap );
  16070. dataOffset += dataLength;
  16071. width = Math.max( width * 0.5, 1 );
  16072. height = Math.max( height * 0.5, 1 );
  16073. }
  16074. width = dds.width;
  16075. height = dds.height;
  16076. }
  16077. return dds;
  16078. },
  16079. getNormalMap: function ( image, depth ) {
  16080. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16081. var cross = function ( a, b ) {
  16082. 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 ] ];
  16083. }
  16084. var subtract = function ( a, b ) {
  16085. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16086. }
  16087. var normalize = function ( a ) {
  16088. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16089. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16090. }
  16091. depth = depth | 1;
  16092. var width = image.width;
  16093. var height = image.height;
  16094. var canvas = document.createElement( 'canvas' );
  16095. canvas.width = width;
  16096. canvas.height = height;
  16097. var context = canvas.getContext( '2d' );
  16098. context.drawImage( image, 0, 0 );
  16099. var data = context.getImageData( 0, 0, width, height ).data;
  16100. var imageData = context.createImageData( width, height );
  16101. var output = imageData.data;
  16102. for ( var x = 0; x < width; x ++ ) {
  16103. for ( var y = 0; y < height; y ++ ) {
  16104. var ly = y - 1 < 0 ? 0 : y - 1;
  16105. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16106. var lx = x - 1 < 0 ? 0 : x - 1;
  16107. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16108. var points = [];
  16109. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16110. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16111. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16112. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16113. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16114. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16115. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16116. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16117. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16118. var normals = [];
  16119. var num_points = points.length;
  16120. for ( var i = 0; i < num_points; i ++ ) {
  16121. var v1 = points[ i ];
  16122. var v2 = points[ ( i + 1 ) % num_points ];
  16123. v1 = subtract( v1, origin );
  16124. v2 = subtract( v2, origin );
  16125. normals.push( normalize( cross( v1, v2 ) ) );
  16126. }
  16127. var normal = [ 0, 0, 0 ];
  16128. for ( var i = 0; i < normals.length; i ++ ) {
  16129. normal[ 0 ] += normals[ i ][ 0 ];
  16130. normal[ 1 ] += normals[ i ][ 1 ];
  16131. normal[ 2 ] += normals[ i ][ 2 ];
  16132. }
  16133. normal[ 0 ] /= normals.length;
  16134. normal[ 1 ] /= normals.length;
  16135. normal[ 2 ] /= normals.length;
  16136. var idx = ( y * width + x ) * 4;
  16137. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16138. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16139. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16140. output[ idx + 3 ] = 255;
  16141. }
  16142. }
  16143. context.putImageData( imageData, 0, 0 );
  16144. return canvas;
  16145. },
  16146. generateDataTexture: function ( width, height, color ) {
  16147. var size = width * height;
  16148. var data = new Uint8Array( 3 * size );
  16149. var r = Math.floor( color.r * 255 );
  16150. var g = Math.floor( color.g * 255 );
  16151. var b = Math.floor( color.b * 255 );
  16152. for ( var i = 0; i < size; i ++ ) {
  16153. data[ i * 3 ] = r;
  16154. data[ i * 3 + 1 ] = g;
  16155. data[ i * 3 + 2 ] = b;
  16156. }
  16157. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16158. texture.needsUpdate = true;
  16159. return texture;
  16160. }
  16161. };
  16162. /**
  16163. * @author alteredq / http://alteredqualia.com/
  16164. */
  16165. THREE.SceneUtils = {
  16166. createMultiMaterialObject: function ( geometry, materials ) {
  16167. var group = new THREE.Object3D();
  16168. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16169. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16170. }
  16171. return group;
  16172. },
  16173. detach : function ( child, parent, scene ) {
  16174. child.applyMatrix( parent.matrixWorld );
  16175. parent.remove( child );
  16176. scene.add( child );
  16177. },
  16178. attach: function ( child, scene, parent ) {
  16179. var matrixWorldInverse = new THREE.Matrix4();
  16180. matrixWorldInverse.getInverse( parent.matrixWorld );
  16181. child.applyMatrix( matrixWorldInverse );
  16182. scene.remove( child );
  16183. parent.add( child );
  16184. }
  16185. };
  16186. /**
  16187. * @author zz85 / http://www.lab4games.net/zz85/blog
  16188. * @author alteredq / http://alteredqualia.com/
  16189. *
  16190. * For Text operations in three.js (See TextGeometry)
  16191. *
  16192. * It uses techniques used in:
  16193. *
  16194. * typeface.js and canvastext
  16195. * For converting fonts and rendering with javascript
  16196. * http://typeface.neocracy.org
  16197. *
  16198. * Triangulation ported from AS3
  16199. * Simple Polygon Triangulation
  16200. * http://actionsnippet.com/?p=1462
  16201. *
  16202. * A Method to triangulate shapes with holes
  16203. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16204. *
  16205. */
  16206. THREE.FontUtils = {
  16207. faces : {},
  16208. // Just for now. face[weight][style]
  16209. face : "helvetiker",
  16210. weight: "normal",
  16211. style : "normal",
  16212. size : 150,
  16213. divisions : 10,
  16214. getFace : function() {
  16215. return this.faces[ this.face ][ this.weight ][ this.style ];
  16216. },
  16217. loadFace : function( data ) {
  16218. var family = data.familyName.toLowerCase();
  16219. var ThreeFont = this;
  16220. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16221. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16222. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16223. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16224. return data;
  16225. },
  16226. drawText : function( text ) {
  16227. var characterPts = [], allPts = [];
  16228. // RenderText
  16229. var i, p,
  16230. face = this.getFace(),
  16231. scale = this.size / face.resolution,
  16232. offset = 0,
  16233. chars = String( text ).split( '' ),
  16234. length = chars.length;
  16235. var fontPaths = [];
  16236. for ( i = 0; i < length; i ++ ) {
  16237. var path = new THREE.Path();
  16238. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16239. offset += ret.offset;
  16240. fontPaths.push( ret.path );
  16241. }
  16242. // get the width
  16243. var width = offset / 2;
  16244. //
  16245. // for ( p = 0; p < allPts.length; p++ ) {
  16246. //
  16247. // allPts[ p ].x -= width;
  16248. //
  16249. // }
  16250. //var extract = this.extractPoints( allPts, characterPts );
  16251. //extract.contour = allPts;
  16252. //extract.paths = fontPaths;
  16253. //extract.offset = width;
  16254. return { paths : fontPaths, offset : width };
  16255. },
  16256. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16257. var pts = [];
  16258. var i, i2, divisions,
  16259. outline, action, length,
  16260. scaleX, scaleY,
  16261. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16262. laste,
  16263. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16264. if ( !glyph ) return;
  16265. if ( glyph.o ) {
  16266. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16267. length = outline.length;
  16268. scaleX = scale;
  16269. scaleY = scale;
  16270. for ( i = 0; i < length; ) {
  16271. action = outline[ i ++ ];
  16272. //console.log( action );
  16273. switch( action ) {
  16274. case 'm':
  16275. // Move To
  16276. x = outline[ i++ ] * scaleX + offset;
  16277. y = outline[ i++ ] * scaleY;
  16278. path.moveTo( x, y );
  16279. break;
  16280. case 'l':
  16281. // Line To
  16282. x = outline[ i++ ] * scaleX + offset;
  16283. y = outline[ i++ ] * scaleY;
  16284. path.lineTo(x,y);
  16285. break;
  16286. case 'q':
  16287. // QuadraticCurveTo
  16288. cpx = outline[ i++ ] * scaleX + offset;
  16289. cpy = outline[ i++ ] * scaleY;
  16290. cpx1 = outline[ i++ ] * scaleX + offset;
  16291. cpy1 = outline[ i++ ] * scaleY;
  16292. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16293. laste = pts[ pts.length - 1 ];
  16294. if ( laste ) {
  16295. cpx0 = laste.x;
  16296. cpy0 = laste.y;
  16297. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16298. var t = i2 / divisions;
  16299. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16300. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16301. }
  16302. }
  16303. break;
  16304. case 'b':
  16305. // Cubic Bezier Curve
  16306. cpx = outline[ i++ ] * scaleX + offset;
  16307. cpy = outline[ i++ ] * scaleY;
  16308. cpx1 = outline[ i++ ] * scaleX + offset;
  16309. cpy1 = outline[ i++ ] * -scaleY;
  16310. cpx2 = outline[ i++ ] * scaleX + offset;
  16311. cpy2 = outline[ i++ ] * -scaleY;
  16312. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16313. laste = pts[ pts.length - 1 ];
  16314. if ( laste ) {
  16315. cpx0 = laste.x;
  16316. cpy0 = laste.y;
  16317. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16318. var t = i2 / divisions;
  16319. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16320. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16321. }
  16322. }
  16323. break;
  16324. }
  16325. }
  16326. }
  16327. return { offset: glyph.ha*scale, path:path};
  16328. }
  16329. };
  16330. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16331. // Parameters
  16332. parameters = parameters || {};
  16333. var size = parameters.size !== undefined ? parameters.size : 100;
  16334. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16335. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16336. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16337. var style = parameters.style !== undefined ? parameters.style : "normal";
  16338. THREE.FontUtils.size = size;
  16339. THREE.FontUtils.divisions = curveSegments;
  16340. THREE.FontUtils.face = font;
  16341. THREE.FontUtils.weight = weight;
  16342. THREE.FontUtils.style = style;
  16343. // Get a Font data json object
  16344. var data = THREE.FontUtils.drawText( text );
  16345. var paths = data.paths;
  16346. var shapes = [];
  16347. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16348. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16349. }
  16350. return shapes;
  16351. };
  16352. /**
  16353. * This code is a quick port of code written in C++ which was submitted to
  16354. * flipcode.com by John W. Ratcliff // July 22, 2000
  16355. * See original code and more information here:
  16356. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16357. *
  16358. * ported to actionscript by Zevan Rosser
  16359. * www.actionsnippet.com
  16360. *
  16361. * ported to javascript by Joshua Koo
  16362. * http://www.lab4games.net/zz85/blog
  16363. *
  16364. */
  16365. ( function( namespace ) {
  16366. var EPSILON = 0.0000000001;
  16367. // takes in an contour array and returns
  16368. var process = function( contour, indices ) {
  16369. var n = contour.length;
  16370. if ( n < 3 ) return null;
  16371. var result = [],
  16372. verts = [],
  16373. vertIndices = [];
  16374. /* we want a counter-clockwise polygon in verts */
  16375. var u, v, w;
  16376. if ( area( contour ) > 0.0 ) {
  16377. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16378. } else {
  16379. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16380. }
  16381. var nv = n;
  16382. /* remove nv - 2 vertices, creating 1 triangle every time */
  16383. var count = 2 * nv; /* error detection */
  16384. for( v = nv - 1; nv > 2; ) {
  16385. /* if we loop, it is probably a non-simple polygon */
  16386. if ( ( count-- ) <= 0 ) {
  16387. //** Triangulate: ERROR - probable bad polygon!
  16388. //throw ( "Warning, unable to triangulate polygon!" );
  16389. //return null;
  16390. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16391. console.log( "Warning, unable to triangulate polygon!" );
  16392. if ( indices ) return vertIndices;
  16393. return result;
  16394. }
  16395. /* three consecutive vertices in current polygon, <u,v,w> */
  16396. u = v; if ( nv <= u ) u = 0; /* previous */
  16397. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16398. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16399. if ( snip( contour, u, v, w, nv, verts ) ) {
  16400. var a, b, c, s, t;
  16401. /* true names of the vertices */
  16402. a = verts[ u ];
  16403. b = verts[ v ];
  16404. c = verts[ w ];
  16405. /* output Triangle */
  16406. result.push( [ contour[ a ],
  16407. contour[ b ],
  16408. contour[ c ] ] );
  16409. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16410. /* remove v from the remaining polygon */
  16411. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16412. verts[ s ] = verts[ t ];
  16413. }
  16414. nv--;
  16415. /* reset error detection counter */
  16416. count = 2 * nv;
  16417. }
  16418. }
  16419. if ( indices ) return vertIndices;
  16420. return result;
  16421. };
  16422. // calculate area of the contour polygon
  16423. var area = function ( contour ) {
  16424. var n = contour.length;
  16425. var a = 0.0;
  16426. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16427. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16428. }
  16429. return a * 0.5;
  16430. };
  16431. var snip = function ( contour, u, v, w, n, verts ) {
  16432. var p;
  16433. var ax, ay, bx, by;
  16434. var cx, cy, px, py;
  16435. ax = contour[ verts[ u ] ].x;
  16436. ay = contour[ verts[ u ] ].y;
  16437. bx = contour[ verts[ v ] ].x;
  16438. by = contour[ verts[ v ] ].y;
  16439. cx = contour[ verts[ w ] ].x;
  16440. cy = contour[ verts[ w ] ].y;
  16441. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16442. var aX, aY, bX, bY, cX, cY;
  16443. var apx, apy, bpx, bpy, cpx, cpy;
  16444. var cCROSSap, bCROSScp, aCROSSbp;
  16445. aX = cx - bx; aY = cy - by;
  16446. bX = ax - cx; bY = ay - cy;
  16447. cX = bx - ax; cY = by - ay;
  16448. for ( p = 0; p < n; p++ ) {
  16449. if( (p === u) || (p === v) || (p === w) ) continue;
  16450. px = contour[ verts[ p ] ].x
  16451. py = contour[ verts[ p ] ].y
  16452. apx = px - ax; apy = py - ay;
  16453. bpx = px - bx; bpy = py - by;
  16454. cpx = px - cx; cpy = py - cy;
  16455. // see if p is inside triangle abc
  16456. aCROSSbp = aX*bpy - aY*bpx;
  16457. cCROSSap = cX*apy - cY*apx;
  16458. bCROSScp = bX*cpy - bY*cpx;
  16459. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16460. }
  16461. return true;
  16462. };
  16463. namespace.Triangulate = process;
  16464. namespace.Triangulate.area = area;
  16465. return namespace;
  16466. })(THREE.FontUtils);
  16467. // To use the typeface.js face files, hook up the API
  16468. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16469. THREE.typeface_js = self._typeface_js;
  16470. /**
  16471. * @author zz85 / http://www.lab4games.net/zz85/blog
  16472. * Extensible curve object
  16473. *
  16474. * Some common of Curve methods
  16475. * .getPoint(t), getTangent(t)
  16476. * .getPointAt(u), getTagentAt(u)
  16477. * .getPoints(), .getSpacedPoints()
  16478. * .getLength()
  16479. * .updateArcLengths()
  16480. *
  16481. * This following classes subclasses THREE.Curve:
  16482. *
  16483. * -- 2d classes --
  16484. * THREE.LineCurve
  16485. * THREE.QuadraticBezierCurve
  16486. * THREE.CubicBezierCurve
  16487. * THREE.SplineCurve
  16488. * THREE.ArcCurve
  16489. * THREE.EllipseCurve
  16490. *
  16491. * -- 3d classes --
  16492. * THREE.LineCurve3
  16493. * THREE.QuadraticBezierCurve3
  16494. * THREE.CubicBezierCurve3
  16495. * THREE.SplineCurve3
  16496. * THREE.ClosedSplineCurve3
  16497. *
  16498. * A series of curves can be represented as a THREE.CurvePath
  16499. *
  16500. **/
  16501. /**************************************************************
  16502. * Abstract Curve base class
  16503. **************************************************************/
  16504. THREE.Curve = function () {
  16505. };
  16506. // Virtual base class method to overwrite and implement in subclasses
  16507. // - t [0 .. 1]
  16508. THREE.Curve.prototype.getPoint = function ( t ) {
  16509. console.log( "Warning, getPoint() not implemented!" );
  16510. return null;
  16511. };
  16512. // Get point at relative position in curve according to arc length
  16513. // - u [0 .. 1]
  16514. THREE.Curve.prototype.getPointAt = function ( u ) {
  16515. var t = this.getUtoTmapping( u );
  16516. return this.getPoint( t );
  16517. };
  16518. // Get sequence of points using getPoint( t )
  16519. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16520. if ( !divisions ) divisions = 5;
  16521. var d, pts = [];
  16522. for ( d = 0; d <= divisions; d ++ ) {
  16523. pts.push( this.getPoint( d / divisions ) );
  16524. }
  16525. return pts;
  16526. };
  16527. // Get sequence of points using getPointAt( u )
  16528. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16529. if ( !divisions ) divisions = 5;
  16530. var d, pts = [];
  16531. for ( d = 0; d <= divisions; d ++ ) {
  16532. pts.push( this.getPointAt( d / divisions ) );
  16533. }
  16534. return pts;
  16535. };
  16536. // Get total curve arc length
  16537. THREE.Curve.prototype.getLength = function () {
  16538. var lengths = this.getLengths();
  16539. return lengths[ lengths.length - 1 ];
  16540. };
  16541. // Get list of cumulative segment lengths
  16542. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16543. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16544. if ( this.cacheArcLengths
  16545. && ( this.cacheArcLengths.length == divisions + 1 )
  16546. && !this.needsUpdate) {
  16547. //console.log( "cached", this.cacheArcLengths );
  16548. return this.cacheArcLengths;
  16549. }
  16550. this.needsUpdate = false;
  16551. var cache = [];
  16552. var current, last = this.getPoint( 0 );
  16553. var p, sum = 0;
  16554. cache.push( 0 );
  16555. for ( p = 1; p <= divisions; p ++ ) {
  16556. current = this.getPoint ( p / divisions );
  16557. sum += current.distanceTo( last );
  16558. cache.push( sum );
  16559. last = current;
  16560. }
  16561. this.cacheArcLengths = cache;
  16562. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16563. };
  16564. THREE.Curve.prototype.updateArcLengths = function() {
  16565. this.needsUpdate = true;
  16566. this.getLengths();
  16567. };
  16568. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16569. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16570. var arcLengths = this.getLengths();
  16571. var i = 0, il = arcLengths.length;
  16572. var targetArcLength; // The targeted u distance value to get
  16573. if ( distance ) {
  16574. targetArcLength = distance;
  16575. } else {
  16576. targetArcLength = u * arcLengths[ il - 1 ];
  16577. }
  16578. //var time = Date.now();
  16579. // binary search for the index with largest value smaller than target u distance
  16580. var low = 0, high = il - 1, comparison;
  16581. while ( low <= high ) {
  16582. 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
  16583. comparison = arcLengths[ i ] - targetArcLength;
  16584. if ( comparison < 0 ) {
  16585. low = i + 1;
  16586. continue;
  16587. } else if ( comparison > 0 ) {
  16588. high = i - 1;
  16589. continue;
  16590. } else {
  16591. high = i;
  16592. break;
  16593. // DONE
  16594. }
  16595. }
  16596. i = high;
  16597. //console.log('b' , i, low, high, Date.now()- time);
  16598. if ( arcLengths[ i ] == targetArcLength ) {
  16599. var t = i / ( il - 1 );
  16600. return t;
  16601. }
  16602. // we could get finer grain at lengths, or use simple interpolatation between two points
  16603. var lengthBefore = arcLengths[ i ];
  16604. var lengthAfter = arcLengths[ i + 1 ];
  16605. var segmentLength = lengthAfter - lengthBefore;
  16606. // determine where we are between the 'before' and 'after' points
  16607. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16608. // add that fractional amount to t
  16609. var t = ( i + segmentFraction ) / ( il -1 );
  16610. return t;
  16611. };
  16612. // Returns a unit vector tangent at t
  16613. // In case any sub curve does not implement its tangent derivation,
  16614. // 2 points a small delta apart will be used to find its gradient
  16615. // which seems to give a reasonable approximation
  16616. THREE.Curve.prototype.getTangent = function( t ) {
  16617. var delta = 0.0001;
  16618. var t1 = t - delta;
  16619. var t2 = t + delta;
  16620. // Capping in case of danger
  16621. if ( t1 < 0 ) t1 = 0;
  16622. if ( t2 > 1 ) t2 = 1;
  16623. var pt1 = this.getPoint( t1 );
  16624. var pt2 = this.getPoint( t2 );
  16625. var vec = pt2.clone().sub(pt1);
  16626. return vec.normalize();
  16627. };
  16628. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16629. var t = this.getUtoTmapping( u );
  16630. return this.getTangent( t );
  16631. };
  16632. /**************************************************************
  16633. * Utils
  16634. **************************************************************/
  16635. THREE.Curve.Utils = {
  16636. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16637. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16638. },
  16639. // Puay Bing, thanks for helping with this derivative!
  16640. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16641. return -3 * p0 * (1 - t) * (1 - t) +
  16642. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16643. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16644. 3 * t * t * p3;
  16645. },
  16646. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16647. // To check if my formulas are correct
  16648. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16649. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16650. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16651. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16652. return h00 + h10 + h01 + h11;
  16653. },
  16654. // Catmull-Rom
  16655. interpolate: function( p0, p1, p2, p3, t ) {
  16656. var v0 = ( p2 - p0 ) * 0.5;
  16657. var v1 = ( p3 - p1 ) * 0.5;
  16658. var t2 = t * t;
  16659. var t3 = t * t2;
  16660. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16661. }
  16662. };
  16663. // TODO: Transformation for Curves?
  16664. /**************************************************************
  16665. * 3D Curves
  16666. **************************************************************/
  16667. // A Factory method for creating new curve subclasses
  16668. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16669. constructor.prototype = Object.create( THREE.Curve.prototype );
  16670. constructor.prototype.getPoint = getPointFunc;
  16671. return constructor;
  16672. };
  16673. /**
  16674. * @author zz85 / http://www.lab4games.net/zz85/blog
  16675. *
  16676. **/
  16677. /**************************************************************
  16678. * Curved Path - a curve path is simply a array of connected
  16679. * curves, but retains the api of a curve
  16680. **************************************************************/
  16681. THREE.CurvePath = function () {
  16682. this.curves = [];
  16683. this.bends = [];
  16684. this.autoClose = false; // Automatically closes the path
  16685. };
  16686. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16687. THREE.CurvePath.prototype.add = function ( curve ) {
  16688. this.curves.push( curve );
  16689. };
  16690. THREE.CurvePath.prototype.checkConnection = function() {
  16691. // TODO
  16692. // If the ending of curve is not connected to the starting
  16693. // or the next curve, then, this is not a real path
  16694. };
  16695. THREE.CurvePath.prototype.closePath = function() {
  16696. // TODO Test
  16697. // and verify for vector3 (needs to implement equals)
  16698. // Add a line curve if start and end of lines are not connected
  16699. var startPoint = this.curves[0].getPoint(0);
  16700. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16701. if (!startPoint.equals(endPoint)) {
  16702. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16703. }
  16704. };
  16705. // To get accurate point with reference to
  16706. // entire path distance at time t,
  16707. // following has to be done:
  16708. // 1. Length of each sub path have to be known
  16709. // 2. Locate and identify type of curve
  16710. // 3. Get t for the curve
  16711. // 4. Return curve.getPointAt(t')
  16712. THREE.CurvePath.prototype.getPoint = function( t ) {
  16713. var d = t * this.getLength();
  16714. var curveLengths = this.getCurveLengths();
  16715. var i = 0, diff, curve;
  16716. // To think about boundaries points.
  16717. while ( i < curveLengths.length ) {
  16718. if ( curveLengths[ i ] >= d ) {
  16719. diff = curveLengths[ i ] - d;
  16720. curve = this.curves[ i ];
  16721. var u = 1 - diff / curve.getLength();
  16722. return curve.getPointAt( u );
  16723. break;
  16724. }
  16725. i ++;
  16726. }
  16727. return null;
  16728. // loop where sum != 0, sum > d , sum+1 <d
  16729. };
  16730. /*
  16731. THREE.CurvePath.prototype.getTangent = function( t ) {
  16732. };*/
  16733. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16734. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16735. // getPoint() depends on getLength
  16736. THREE.CurvePath.prototype.getLength = function() {
  16737. var lens = this.getCurveLengths();
  16738. return lens[ lens.length - 1 ];
  16739. };
  16740. // Compute lengths and cache them
  16741. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16742. THREE.CurvePath.prototype.getCurveLengths = function() {
  16743. // We use cache values if curves and cache array are same length
  16744. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16745. return this.cacheLengths;
  16746. };
  16747. // Get length of subsurve
  16748. // Push sums into cached array
  16749. var lengths = [], sums = 0;
  16750. var i, il = this.curves.length;
  16751. for ( i = 0; i < il; i ++ ) {
  16752. sums += this.curves[ i ].getLength();
  16753. lengths.push( sums );
  16754. }
  16755. this.cacheLengths = lengths;
  16756. return lengths;
  16757. };
  16758. // Returns min and max coordinates, as well as centroid
  16759. THREE.CurvePath.prototype.getBoundingBox = function () {
  16760. var points = this.getPoints();
  16761. var maxX, maxY, maxZ;
  16762. var minX, minY, minZ;
  16763. maxX = maxY = Number.NEGATIVE_INFINITY;
  16764. minX = minY = Number.POSITIVE_INFINITY;
  16765. var p, i, il, sum;
  16766. var v3 = points[0] instanceof THREE.Vector3;
  16767. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16768. for ( i = 0, il = points.length; i < il; i ++ ) {
  16769. p = points[ i ];
  16770. if ( p.x > maxX ) maxX = p.x;
  16771. else if ( p.x < minX ) minX = p.x;
  16772. if ( p.y > maxY ) maxY = p.y;
  16773. else if ( p.y < minY ) minY = p.y;
  16774. if ( v3 ) {
  16775. if ( p.z > maxZ ) maxZ = p.z;
  16776. else if ( p.z < minZ ) minZ = p.z;
  16777. }
  16778. sum.add( p );
  16779. }
  16780. var ret = {
  16781. minX: minX,
  16782. minY: minY,
  16783. maxX: maxX,
  16784. maxY: maxY,
  16785. centroid: sum.divideScalar( il )
  16786. };
  16787. if ( v3 ) {
  16788. ret.maxZ = maxZ;
  16789. ret.minZ = minZ;
  16790. }
  16791. return ret;
  16792. };
  16793. /**************************************************************
  16794. * Create Geometries Helpers
  16795. **************************************************************/
  16796. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16797. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16798. var pts = this.getPoints( divisions, true );
  16799. return this.createGeometry( pts );
  16800. };
  16801. // Generate geometry from equidistance sampling along the path
  16802. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16803. var pts = this.getSpacedPoints( divisions, true );
  16804. return this.createGeometry( pts );
  16805. };
  16806. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16807. var geometry = new THREE.Geometry();
  16808. for ( var i = 0; i < points.length; i ++ ) {
  16809. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16810. }
  16811. return geometry;
  16812. };
  16813. /**************************************************************
  16814. * Bend / Wrap Helper Methods
  16815. **************************************************************/
  16816. // Wrap path / Bend modifiers?
  16817. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16818. this.bends.push( bendpath );
  16819. };
  16820. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16821. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16822. var i, il;
  16823. if ( !bends ) {
  16824. bends = this.bends;
  16825. }
  16826. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16827. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16828. }
  16829. return oldPts;
  16830. };
  16831. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16832. var oldPts = this.getSpacedPoints( segments );
  16833. var i, il;
  16834. if ( !bends ) {
  16835. bends = this.bends;
  16836. }
  16837. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16838. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16839. }
  16840. return oldPts;
  16841. };
  16842. // This returns getPoints() bend/wrapped around the contour of a path.
  16843. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16844. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16845. var bounds = this.getBoundingBox();
  16846. var i, il, p, oldX, oldY, xNorm;
  16847. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16848. p = oldPts[ i ];
  16849. oldX = p.x;
  16850. oldY = p.y;
  16851. xNorm = oldX / bounds.maxX;
  16852. // If using actual distance, for length > path, requires line extrusions
  16853. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16854. xNorm = path.getUtoTmapping( xNorm, oldX );
  16855. // check for out of bounds?
  16856. var pathPt = path.getPoint( xNorm );
  16857. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16858. p.x = pathPt.x + normal.x;
  16859. p.y = pathPt.y + normal.y;
  16860. }
  16861. return oldPts;
  16862. };
  16863. /**
  16864. * @author alteredq / http://alteredqualia.com/
  16865. */
  16866. THREE.Gyroscope = function () {
  16867. THREE.Object3D.call( this );
  16868. };
  16869. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16870. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16871. this.matrixAutoUpdate && this.updateMatrix();
  16872. // update matrixWorld
  16873. if ( this.matrixWorldNeedsUpdate || force ) {
  16874. if ( this.parent ) {
  16875. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16876. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16877. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16878. this.matrixWorld.makeFromPositionQuaternionScale( this.translationWorld, this.rotationObject, this.scaleWorld );
  16879. } else {
  16880. this.matrixWorld.copy( this.matrix );
  16881. }
  16882. this.matrixWorldNeedsUpdate = false;
  16883. force = true;
  16884. }
  16885. // update children
  16886. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16887. this.children[ i ].updateMatrixWorld( force );
  16888. }
  16889. };
  16890. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16891. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16892. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16893. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16894. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16895. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16896. /**
  16897. * @author zz85 / http://www.lab4games.net/zz85/blog
  16898. * Creates free form 2d path using series of points, lines or curves.
  16899. *
  16900. **/
  16901. THREE.Path = function ( points ) {
  16902. THREE.CurvePath.call(this);
  16903. this.actions = [];
  16904. if ( points ) {
  16905. this.fromPoints( points );
  16906. }
  16907. };
  16908. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16909. THREE.PathActions = {
  16910. MOVE_TO: 'moveTo',
  16911. LINE_TO: 'lineTo',
  16912. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16913. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16914. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16915. ARC: 'arc', // Circle
  16916. ELLIPSE: 'ellipse'
  16917. };
  16918. // TODO Clean up PATH API
  16919. // Create path using straight lines to connect all points
  16920. // - vectors: array of Vector2
  16921. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16922. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16923. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16924. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16925. };
  16926. };
  16927. // startPath() endPath()?
  16928. THREE.Path.prototype.moveTo = function ( x, y ) {
  16929. var args = Array.prototype.slice.call( arguments );
  16930. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16931. };
  16932. THREE.Path.prototype.lineTo = function ( x, y ) {
  16933. var args = Array.prototype.slice.call( arguments );
  16934. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16935. var x0 = lastargs[ lastargs.length - 2 ];
  16936. var y0 = lastargs[ lastargs.length - 1 ];
  16937. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16938. this.curves.push( curve );
  16939. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16940. };
  16941. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16942. var args = Array.prototype.slice.call( arguments );
  16943. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16944. var x0 = lastargs[ lastargs.length - 2 ];
  16945. var y0 = lastargs[ lastargs.length - 1 ];
  16946. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16947. new THREE.Vector2( aCPx, aCPy ),
  16948. new THREE.Vector2( aX, aY ) );
  16949. this.curves.push( curve );
  16950. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16951. };
  16952. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16953. aCP2x, aCP2y,
  16954. aX, aY ) {
  16955. var args = Array.prototype.slice.call( arguments );
  16956. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16957. var x0 = lastargs[ lastargs.length - 2 ];
  16958. var y0 = lastargs[ lastargs.length - 1 ];
  16959. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16960. new THREE.Vector2( aCP1x, aCP1y ),
  16961. new THREE.Vector2( aCP2x, aCP2y ),
  16962. new THREE.Vector2( aX, aY ) );
  16963. this.curves.push( curve );
  16964. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16965. };
  16966. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16967. var args = Array.prototype.slice.call( arguments );
  16968. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16969. var x0 = lastargs[ lastargs.length - 2 ];
  16970. var y0 = lastargs[ lastargs.length - 1 ];
  16971. //---
  16972. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16973. Array.prototype.push.apply( npts, pts );
  16974. var curve = new THREE.SplineCurve( npts );
  16975. this.curves.push( curve );
  16976. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16977. };
  16978. // FUTURE: Change the API or follow canvas API?
  16979. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16980. aStartAngle, aEndAngle, aClockwise ) {
  16981. var lastargs = this.actions[ this.actions.length - 1].args;
  16982. var x0 = lastargs[ lastargs.length - 2 ];
  16983. var y0 = lastargs[ lastargs.length - 1 ];
  16984. this.absarc(aX + x0, aY + y0, aRadius,
  16985. aStartAngle, aEndAngle, aClockwise );
  16986. };
  16987. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16988. aStartAngle, aEndAngle, aClockwise ) {
  16989. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16990. };
  16991. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16992. aStartAngle, aEndAngle, aClockwise ) {
  16993. var lastargs = this.actions[ this.actions.length - 1].args;
  16994. var x0 = lastargs[ lastargs.length - 2 ];
  16995. var y0 = lastargs[ lastargs.length - 1 ];
  16996. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16997. aStartAngle, aEndAngle, aClockwise );
  16998. };
  16999. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17000. aStartAngle, aEndAngle, aClockwise ) {
  17001. var args = Array.prototype.slice.call( arguments );
  17002. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17003. aStartAngle, aEndAngle, aClockwise );
  17004. this.curves.push( curve );
  17005. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17006. args.push(lastPoint.x);
  17007. args.push(lastPoint.y);
  17008. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17009. };
  17010. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17011. if ( ! divisions ) divisions = 40;
  17012. var points = [];
  17013. for ( var i = 0; i < divisions; i ++ ) {
  17014. points.push( this.getPoint( i / divisions ) );
  17015. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17016. }
  17017. // if ( closedPath ) {
  17018. //
  17019. // points.push( points[ 0 ] );
  17020. //
  17021. // }
  17022. return points;
  17023. };
  17024. /* Return an array of vectors based on contour of the path */
  17025. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17026. if (this.useSpacedPoints) {
  17027. console.log('tata');
  17028. return this.getSpacedPoints( divisions, closedPath );
  17029. }
  17030. divisions = divisions || 12;
  17031. var points = [];
  17032. var i, il, item, action, args;
  17033. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17034. laste, j,
  17035. t, tx, ty;
  17036. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17037. item = this.actions[ i ];
  17038. action = item.action;
  17039. args = item.args;
  17040. switch( action ) {
  17041. case THREE.PathActions.MOVE_TO:
  17042. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17043. break;
  17044. case THREE.PathActions.LINE_TO:
  17045. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17046. break;
  17047. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17048. cpx = args[ 2 ];
  17049. cpy = args[ 3 ];
  17050. cpx1 = args[ 0 ];
  17051. cpy1 = args[ 1 ];
  17052. if ( points.length > 0 ) {
  17053. laste = points[ points.length - 1 ];
  17054. cpx0 = laste.x;
  17055. cpy0 = laste.y;
  17056. } else {
  17057. laste = this.actions[ i - 1 ].args;
  17058. cpx0 = laste[ laste.length - 2 ];
  17059. cpy0 = laste[ laste.length - 1 ];
  17060. }
  17061. for ( j = 1; j <= divisions; j ++ ) {
  17062. t = j / divisions;
  17063. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17064. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17065. points.push( new THREE.Vector2( tx, ty ) );
  17066. }
  17067. break;
  17068. case THREE.PathActions.BEZIER_CURVE_TO:
  17069. cpx = args[ 4 ];
  17070. cpy = args[ 5 ];
  17071. cpx1 = args[ 0 ];
  17072. cpy1 = args[ 1 ];
  17073. cpx2 = args[ 2 ];
  17074. cpy2 = args[ 3 ];
  17075. if ( points.length > 0 ) {
  17076. laste = points[ points.length - 1 ];
  17077. cpx0 = laste.x;
  17078. cpy0 = laste.y;
  17079. } else {
  17080. laste = this.actions[ i - 1 ].args;
  17081. cpx0 = laste[ laste.length - 2 ];
  17082. cpy0 = laste[ laste.length - 1 ];
  17083. }
  17084. for ( j = 1; j <= divisions; j ++ ) {
  17085. t = j / divisions;
  17086. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17087. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17088. points.push( new THREE.Vector2( tx, ty ) );
  17089. }
  17090. break;
  17091. case THREE.PathActions.CSPLINE_THRU:
  17092. laste = this.actions[ i - 1 ].args;
  17093. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17094. var spts = [ last ];
  17095. var n = divisions * args[ 0 ].length;
  17096. spts = spts.concat( args[ 0 ] );
  17097. var spline = new THREE.SplineCurve( spts );
  17098. for ( j = 1; j <= n; j ++ ) {
  17099. points.push( spline.getPointAt( j / n ) ) ;
  17100. }
  17101. break;
  17102. case THREE.PathActions.ARC:
  17103. var aX = args[ 0 ], aY = args[ 1 ],
  17104. aRadius = args[ 2 ],
  17105. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17106. aClockwise = !!args[ 5 ];
  17107. var deltaAngle = aEndAngle - aStartAngle;
  17108. var angle;
  17109. var tdivisions = divisions * 2;
  17110. for ( j = 1; j <= tdivisions; j ++ ) {
  17111. t = j / tdivisions;
  17112. if ( ! aClockwise ) {
  17113. t = 1 - t;
  17114. }
  17115. angle = aStartAngle + t * deltaAngle;
  17116. tx = aX + aRadius * Math.cos( angle );
  17117. ty = aY + aRadius * Math.sin( angle );
  17118. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17119. points.push( new THREE.Vector2( tx, ty ) );
  17120. }
  17121. //console.log(points);
  17122. break;
  17123. case THREE.PathActions.ELLIPSE:
  17124. var aX = args[ 0 ], aY = args[ 1 ],
  17125. xRadius = args[ 2 ],
  17126. yRadius = args[ 3 ],
  17127. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17128. aClockwise = !!args[ 6 ];
  17129. var deltaAngle = aEndAngle - aStartAngle;
  17130. var angle;
  17131. var tdivisions = divisions * 2;
  17132. for ( j = 1; j <= tdivisions; j ++ ) {
  17133. t = j / tdivisions;
  17134. if ( ! aClockwise ) {
  17135. t = 1 - t;
  17136. }
  17137. angle = aStartAngle + t * deltaAngle;
  17138. tx = aX + xRadius * Math.cos( angle );
  17139. ty = aY + yRadius * Math.sin( angle );
  17140. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17141. points.push( new THREE.Vector2( tx, ty ) );
  17142. }
  17143. //console.log(points);
  17144. break;
  17145. } // end switch
  17146. }
  17147. // Normalize to remove the closing point by default.
  17148. var lastPoint = points[ points.length - 1];
  17149. var EPSILON = 0.0000000001;
  17150. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17151. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17152. points.splice( points.length - 1, 1);
  17153. if ( closedPath ) {
  17154. points.push( points[ 0 ] );
  17155. }
  17156. return points;
  17157. };
  17158. // Breaks path into shapes
  17159. THREE.Path.prototype.toShapes = function() {
  17160. var i, il, item, action, args;
  17161. var subPaths = [], lastPath = new THREE.Path();
  17162. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17163. item = this.actions[ i ];
  17164. args = item.args;
  17165. action = item.action;
  17166. if ( action == THREE.PathActions.MOVE_TO ) {
  17167. if ( lastPath.actions.length != 0 ) {
  17168. subPaths.push( lastPath );
  17169. lastPath = new THREE.Path();
  17170. }
  17171. }
  17172. lastPath[ action ].apply( lastPath, args );
  17173. }
  17174. if ( lastPath.actions.length != 0 ) {
  17175. subPaths.push( lastPath );
  17176. }
  17177. // console.log(subPaths);
  17178. if ( subPaths.length == 0 ) return [];
  17179. var tmpPath, tmpShape, shapes = [];
  17180. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17181. // console.log("Holes first", holesFirst);
  17182. if ( subPaths.length == 1) {
  17183. tmpPath = subPaths[0];
  17184. tmpShape = new THREE.Shape();
  17185. tmpShape.actions = tmpPath.actions;
  17186. tmpShape.curves = tmpPath.curves;
  17187. shapes.push( tmpShape );
  17188. return shapes;
  17189. };
  17190. if ( holesFirst ) {
  17191. tmpShape = new THREE.Shape();
  17192. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17193. tmpPath = subPaths[ i ];
  17194. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17195. tmpShape.actions = tmpPath.actions;
  17196. tmpShape.curves = tmpPath.curves;
  17197. shapes.push( tmpShape );
  17198. tmpShape = new THREE.Shape();
  17199. //console.log('cw', i);
  17200. } else {
  17201. tmpShape.holes.push( tmpPath );
  17202. //console.log('ccw', i);
  17203. }
  17204. }
  17205. } else {
  17206. // Shapes first
  17207. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17208. tmpPath = subPaths[ i ];
  17209. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17210. if ( tmpShape ) shapes.push( tmpShape );
  17211. tmpShape = new THREE.Shape();
  17212. tmpShape.actions = tmpPath.actions;
  17213. tmpShape.curves = tmpPath.curves;
  17214. } else {
  17215. tmpShape.holes.push( tmpPath );
  17216. }
  17217. }
  17218. shapes.push( tmpShape );
  17219. }
  17220. //console.log("shape", shapes);
  17221. return shapes;
  17222. };
  17223. /**
  17224. * @author zz85 / http://www.lab4games.net/zz85/blog
  17225. * Defines a 2d shape plane using paths.
  17226. **/
  17227. // STEP 1 Create a path.
  17228. // STEP 2 Turn path into shape.
  17229. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17230. // STEP 3a - Extract points from each shape, turn to vertices
  17231. // STEP 3b - Triangulate each shape, add faces.
  17232. THREE.Shape = function () {
  17233. THREE.Path.apply( this, arguments );
  17234. this.holes = [];
  17235. };
  17236. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17237. // Convenience method to return ExtrudeGeometry
  17238. THREE.Shape.prototype.extrude = function ( options ) {
  17239. var extruded = new THREE.ExtrudeGeometry( this, options );
  17240. return extruded;
  17241. };
  17242. // Convenience method to return ShapeGeometry
  17243. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17244. var geometry = new THREE.ShapeGeometry( this, options );
  17245. return geometry;
  17246. };
  17247. // Get points of holes
  17248. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17249. var i, il = this.holes.length, holesPts = [];
  17250. for ( i = 0; i < il; i ++ ) {
  17251. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17252. }
  17253. return holesPts;
  17254. };
  17255. // Get points of holes (spaced by regular distance)
  17256. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17257. var i, il = this.holes.length, holesPts = [];
  17258. for ( i = 0; i < il; i ++ ) {
  17259. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17260. }
  17261. return holesPts;
  17262. };
  17263. // Get points of shape and holes (keypoints based on segments parameter)
  17264. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17265. return {
  17266. shape: this.getTransformedPoints( divisions ),
  17267. holes: this.getPointsHoles( divisions )
  17268. };
  17269. };
  17270. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17271. if (this.useSpacedPoints) {
  17272. return this.extractAllSpacedPoints(divisions);
  17273. }
  17274. return this.extractAllPoints(divisions);
  17275. };
  17276. //
  17277. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17278. //
  17279. // return {
  17280. //
  17281. // shape: this.transform( bend, divisions ),
  17282. // holes: this.getPointsHoles( divisions, bend )
  17283. //
  17284. // };
  17285. //
  17286. // };
  17287. // Get points of shape and holes (spaced by regular distance)
  17288. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17289. return {
  17290. shape: this.getTransformedSpacedPoints( divisions ),
  17291. holes: this.getSpacedPointsHoles( divisions )
  17292. };
  17293. };
  17294. /**************************************************************
  17295. * Utils
  17296. **************************************************************/
  17297. THREE.Shape.Utils = {
  17298. /*
  17299. contour - array of vector2 for contour
  17300. holes - array of array of vector2
  17301. */
  17302. removeHoles: function ( contour, holes ) {
  17303. var shape = contour.concat(); // work on this shape
  17304. var allpoints = shape.concat();
  17305. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17306. var prevShapeVert, nextShapeVert,
  17307. prevHoleVert, nextHoleVert,
  17308. holeIndex, shapeIndex,
  17309. shapeId, shapeGroup,
  17310. h, h2,
  17311. hole, shortest, d,
  17312. p, pts1, pts2,
  17313. tmpShape1, tmpShape2,
  17314. tmpHole1, tmpHole2,
  17315. verts = [];
  17316. for ( h = 0; h < holes.length; h ++ ) {
  17317. hole = holes[ h ];
  17318. /*
  17319. shapeholes[ h ].concat(); // preserves original
  17320. holes.push( hole );
  17321. */
  17322. Array.prototype.push.apply( allpoints, hole );
  17323. shortest = Number.POSITIVE_INFINITY;
  17324. // Find the shortest pair of pts between shape and hole
  17325. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17326. // Using distanceToSquared() intead of distanceTo() should speed a little
  17327. // since running square roots operations are reduced.
  17328. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17329. pts1 = hole[ h2 ];
  17330. var dist = [];
  17331. for ( p = 0; p < shape.length; p++ ) {
  17332. pts2 = shape[ p ];
  17333. d = pts1.distanceToSquared( pts2 );
  17334. dist.push( d );
  17335. if ( d < shortest ) {
  17336. shortest = d;
  17337. holeIndex = h2;
  17338. shapeIndex = p;
  17339. }
  17340. }
  17341. }
  17342. //console.log("shortest", shortest, dist);
  17343. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17344. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17345. var areaapts = [
  17346. hole[ holeIndex ],
  17347. shape[ shapeIndex ],
  17348. shape[ prevShapeVert ]
  17349. ];
  17350. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17351. var areabpts = [
  17352. hole[ holeIndex ],
  17353. hole[ prevHoleVert ],
  17354. shape[ shapeIndex ]
  17355. ];
  17356. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17357. var shapeOffset = 1;
  17358. var holeOffset = -1;
  17359. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17360. shapeIndex += shapeOffset;
  17361. holeIndex += holeOffset;
  17362. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17363. shapeIndex %= shape.length;
  17364. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17365. holeIndex %= hole.length;
  17366. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17367. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17368. areaapts = [
  17369. hole[ holeIndex ],
  17370. shape[ shapeIndex ],
  17371. shape[ prevShapeVert ]
  17372. ];
  17373. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17374. areabpts = [
  17375. hole[ holeIndex ],
  17376. hole[ prevHoleVert ],
  17377. shape[ shapeIndex ]
  17378. ];
  17379. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17380. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17381. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17382. // In case areas are not correct.
  17383. //console.log("USE THIS");
  17384. shapeIndex = oldShapeIndex;
  17385. holeIndex = oldHoleIndex ;
  17386. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17387. shapeIndex %= shape.length;
  17388. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17389. holeIndex %= hole.length;
  17390. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17391. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17392. } else {
  17393. //console.log("USE THAT ")
  17394. }
  17395. tmpShape1 = shape.slice( 0, shapeIndex );
  17396. tmpShape2 = shape.slice( shapeIndex );
  17397. tmpHole1 = hole.slice( holeIndex );
  17398. tmpHole2 = hole.slice( 0, holeIndex );
  17399. // Should check orders here again?
  17400. var trianglea = [
  17401. hole[ holeIndex ],
  17402. shape[ shapeIndex ],
  17403. shape[ prevShapeVert ]
  17404. ];
  17405. var triangleb = [
  17406. hole[ holeIndex ] ,
  17407. hole[ prevHoleVert ],
  17408. shape[ shapeIndex ]
  17409. ];
  17410. verts.push( trianglea );
  17411. verts.push( triangleb );
  17412. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17413. }
  17414. return {
  17415. shape:shape, /* shape with no holes */
  17416. isolatedPts: verts, /* isolated faces */
  17417. allpoints: allpoints
  17418. }
  17419. },
  17420. triangulateShape: function ( contour, holes ) {
  17421. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17422. var shape = shapeWithoutHoles.shape,
  17423. allpoints = shapeWithoutHoles.allpoints,
  17424. isolatedPts = shapeWithoutHoles.isolatedPts;
  17425. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17426. // 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.
  17427. //console.log( "triangles",triangles, triangles.length );
  17428. //console.log( "allpoints",allpoints, allpoints.length );
  17429. var i, il, f, face,
  17430. key, index,
  17431. allPointsMap = {},
  17432. isolatedPointsMap = {};
  17433. // prepare all points map
  17434. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17435. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17436. if ( allPointsMap[ key ] !== undefined ) {
  17437. console.log( "Duplicate point", key );
  17438. }
  17439. allPointsMap[ key ] = i;
  17440. }
  17441. // check all face vertices against all points map
  17442. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17443. face = triangles[ i ];
  17444. for ( f = 0; f < 3; f ++ ) {
  17445. key = face[ f ].x + ":" + face[ f ].y;
  17446. index = allPointsMap[ key ];
  17447. if ( index !== undefined ) {
  17448. face[ f ] = index;
  17449. }
  17450. }
  17451. }
  17452. // check isolated points vertices against all points map
  17453. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17454. face = isolatedPts[ i ];
  17455. for ( f = 0; f < 3; f ++ ) {
  17456. key = face[ f ].x + ":" + face[ f ].y;
  17457. index = allPointsMap[ key ];
  17458. if ( index !== undefined ) {
  17459. face[ f ] = index;
  17460. }
  17461. }
  17462. }
  17463. return triangles.concat( isolatedPts );
  17464. }, // end triangulate shapes
  17465. /*
  17466. triangulate2 : function( pts, holes ) {
  17467. // For use with Poly2Tri.js
  17468. var allpts = pts.concat();
  17469. var shape = [];
  17470. for (var p in pts) {
  17471. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17472. }
  17473. var swctx = new js.poly2tri.SweepContext(shape);
  17474. for (var h in holes) {
  17475. var aHole = holes[h];
  17476. var newHole = []
  17477. for (i in aHole) {
  17478. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17479. allpts.push(aHole[i]);
  17480. }
  17481. swctx.AddHole(newHole);
  17482. }
  17483. var find;
  17484. var findIndexForPt = function (pt) {
  17485. find = new THREE.Vector2(pt.x, pt.y);
  17486. var p;
  17487. for (p=0, pl = allpts.length; p<pl; p++) {
  17488. if (allpts[p].equals(find)) return p;
  17489. }
  17490. return -1;
  17491. };
  17492. // triangulate
  17493. js.poly2tri.sweep.Triangulate(swctx);
  17494. var triangles = swctx.GetTriangles();
  17495. var tr ;
  17496. var facesPts = [];
  17497. for (var t in triangles) {
  17498. tr = triangles[t];
  17499. facesPts.push([
  17500. findIndexForPt(tr.GetPoint(0)),
  17501. findIndexForPt(tr.GetPoint(1)),
  17502. findIndexForPt(tr.GetPoint(2))
  17503. ]);
  17504. }
  17505. // console.log(facesPts);
  17506. // console.log("triangles", triangles.length, triangles);
  17507. // Returns array of faces with 3 element each
  17508. return facesPts;
  17509. },
  17510. */
  17511. isClockWise: function ( pts ) {
  17512. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17513. },
  17514. // Bezier Curves formulas obtained from
  17515. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17516. // Quad Bezier Functions
  17517. b2p0: function ( t, p ) {
  17518. var k = 1 - t;
  17519. return k * k * p;
  17520. },
  17521. b2p1: function ( t, p ) {
  17522. return 2 * ( 1 - t ) * t * p;
  17523. },
  17524. b2p2: function ( t, p ) {
  17525. return t * t * p;
  17526. },
  17527. b2: function ( t, p0, p1, p2 ) {
  17528. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17529. },
  17530. // Cubic Bezier Functions
  17531. b3p0: function ( t, p ) {
  17532. var k = 1 - t;
  17533. return k * k * k * p;
  17534. },
  17535. b3p1: function ( t, p ) {
  17536. var k = 1 - t;
  17537. return 3 * k * k * t * p;
  17538. },
  17539. b3p2: function ( t, p ) {
  17540. var k = 1 - t;
  17541. return 3 * k * t * t * p;
  17542. },
  17543. b3p3: function ( t, p ) {
  17544. return t * t * t * p;
  17545. },
  17546. b3: function ( t, p0, p1, p2, p3 ) {
  17547. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17548. }
  17549. };
  17550. /**************************************************************
  17551. * Line
  17552. **************************************************************/
  17553. THREE.LineCurve = function ( v1, v2 ) {
  17554. this.v1 = v1;
  17555. this.v2 = v2;
  17556. };
  17557. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17558. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17559. var point = this.v2.clone().sub(this.v1);
  17560. point.multiplyScalar( t ).add( this.v1 );
  17561. return point;
  17562. };
  17563. // Line curve is linear, so we can overwrite default getPointAt
  17564. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17565. return this.getPoint( u );
  17566. };
  17567. THREE.LineCurve.prototype.getTangent = function( t ) {
  17568. var tangent = this.v2.clone().sub(this.v1);
  17569. return tangent.normalize();
  17570. };
  17571. /**************************************************************
  17572. * Quadratic Bezier curve
  17573. **************************************************************/
  17574. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17575. this.v0 = v0;
  17576. this.v1 = v1;
  17577. this.v2 = v2;
  17578. };
  17579. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17580. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17581. var tx, ty;
  17582. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17583. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17584. return new THREE.Vector2( tx, ty );
  17585. };
  17586. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17587. var tx, ty;
  17588. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17589. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17590. // returns unit vector
  17591. var tangent = new THREE.Vector2( tx, ty );
  17592. tangent.normalize();
  17593. return tangent;
  17594. };
  17595. /**************************************************************
  17596. * Cubic Bezier curve
  17597. **************************************************************/
  17598. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17599. this.v0 = v0;
  17600. this.v1 = v1;
  17601. this.v2 = v2;
  17602. this.v3 = v3;
  17603. };
  17604. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17605. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17606. var tx, ty;
  17607. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17608. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17609. return new THREE.Vector2( tx, ty );
  17610. };
  17611. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17612. var tx, ty;
  17613. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17614. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17615. var tangent = new THREE.Vector2( tx, ty );
  17616. tangent.normalize();
  17617. return tangent;
  17618. };
  17619. /**************************************************************
  17620. * Spline curve
  17621. **************************************************************/
  17622. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17623. this.points = (points == undefined) ? [] : points;
  17624. };
  17625. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17626. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17627. var v = new THREE.Vector2();
  17628. var c = [];
  17629. var points = this.points, point, intPoint, weight;
  17630. point = ( points.length - 1 ) * t;
  17631. intPoint = Math.floor( point );
  17632. weight = point - intPoint;
  17633. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17634. c[ 1 ] = intPoint;
  17635. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  17636. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  17637. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17638. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17639. return v;
  17640. };
  17641. /**************************************************************
  17642. * Ellipse curve
  17643. **************************************************************/
  17644. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  17645. aStartAngle, aEndAngle,
  17646. aClockwise ) {
  17647. this.aX = aX;
  17648. this.aY = aY;
  17649. this.xRadius = xRadius;
  17650. this.yRadius = yRadius;
  17651. this.aStartAngle = aStartAngle;
  17652. this.aEndAngle = aEndAngle;
  17653. this.aClockwise = aClockwise;
  17654. };
  17655. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17656. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17657. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17658. if ( !this.aClockwise ) {
  17659. t = 1 - t;
  17660. }
  17661. var angle = this.aStartAngle + t * deltaAngle;
  17662. var tx = this.aX + this.xRadius * Math.cos( angle );
  17663. var ty = this.aY + this.yRadius * Math.sin( angle );
  17664. return new THREE.Vector2( tx, ty );
  17665. };
  17666. /**************************************************************
  17667. * Arc curve
  17668. **************************************************************/
  17669. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17670. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17671. };
  17672. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17673. /**************************************************************
  17674. * Line3D
  17675. **************************************************************/
  17676. THREE.LineCurve3 = THREE.Curve.create(
  17677. function ( v1, v2 ) {
  17678. this.v1 = v1;
  17679. this.v2 = v2;
  17680. },
  17681. function ( t ) {
  17682. var r = new THREE.Vector3();
  17683. r.subVectors( this.v2, this.v1 ); // diff
  17684. r.multiplyScalar( t );
  17685. r.add( this.v1 );
  17686. return r;
  17687. }
  17688. );
  17689. /**************************************************************
  17690. * Quadratic Bezier 3D curve
  17691. **************************************************************/
  17692. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17693. function ( v0, v1, v2 ) {
  17694. this.v0 = v0;
  17695. this.v1 = v1;
  17696. this.v2 = v2;
  17697. },
  17698. function ( t ) {
  17699. var tx, ty, tz;
  17700. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17701. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17702. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17703. return new THREE.Vector3( tx, ty, tz );
  17704. }
  17705. );
  17706. /**************************************************************
  17707. * Cubic Bezier 3D curve
  17708. **************************************************************/
  17709. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17710. function ( v0, v1, v2, v3 ) {
  17711. this.v0 = v0;
  17712. this.v1 = v1;
  17713. this.v2 = v2;
  17714. this.v3 = v3;
  17715. },
  17716. function ( t ) {
  17717. var tx, ty, tz;
  17718. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17719. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17720. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17721. return new THREE.Vector3( tx, ty, tz );
  17722. }
  17723. );
  17724. /**************************************************************
  17725. * Spline 3D curve
  17726. **************************************************************/
  17727. THREE.SplineCurve3 = THREE.Curve.create(
  17728. function ( points /* array of Vector3 */) {
  17729. this.points = (points == undefined) ? [] : points;
  17730. },
  17731. function ( t ) {
  17732. var v = new THREE.Vector3();
  17733. var c = [];
  17734. var points = this.points, point, intPoint, weight;
  17735. point = ( points.length - 1 ) * t;
  17736. intPoint = Math.floor( point );
  17737. weight = point - intPoint;
  17738. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17739. c[ 1 ] = intPoint;
  17740. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17741. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17742. var pt0 = points[ c[0] ],
  17743. pt1 = points[ c[1] ],
  17744. pt2 = points[ c[2] ],
  17745. pt3 = points[ c[3] ];
  17746. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  17747. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  17748. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  17749. return v;
  17750. }
  17751. );
  17752. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  17753. // var v = new THREE.Vector3();
  17754. // var c = [];
  17755. // var points = this.points, point, intPoint, weight;
  17756. // point = ( points.length - 1 ) * t;
  17757. // intPoint = Math.floor( point );
  17758. // weight = point - intPoint;
  17759. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17760. // c[ 1 ] = intPoint;
  17761. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17762. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17763. // var pt0 = points[ c[0] ],
  17764. // pt1 = points[ c[1] ],
  17765. // pt2 = points[ c[2] ],
  17766. // pt3 = points[ c[3] ];
  17767. // // t = weight;
  17768. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  17769. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  17770. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  17771. // return v;
  17772. // }
  17773. /**************************************************************
  17774. * Closed Spline 3D curve
  17775. **************************************************************/
  17776. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17777. function ( points /* array of Vector3 */) {
  17778. this.points = (points == undefined) ? [] : points;
  17779. },
  17780. function ( t ) {
  17781. var v = new THREE.Vector3();
  17782. var c = [];
  17783. var points = this.points, point, intPoint, weight;
  17784. point = ( points.length - 0 ) * t;
  17785. // This needs to be from 0-length +1
  17786. intPoint = Math.floor( point );
  17787. weight = point - intPoint;
  17788. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17789. c[ 0 ] = ( intPoint - 1 ) % points.length;
  17790. c[ 1 ] = ( intPoint ) % points.length;
  17791. c[ 2 ] = ( intPoint + 1 ) % points.length;
  17792. c[ 3 ] = ( intPoint + 2 ) % points.length;
  17793. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17794. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17795. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  17796. return v;
  17797. }
  17798. );
  17799. /**
  17800. * @author mikael emtinger / http://gomo.se/
  17801. */
  17802. THREE.AnimationHandler = (function() {
  17803. var playing = [];
  17804. var library = {};
  17805. var that = {};
  17806. //--- update ---
  17807. that.update = function( deltaTimeMS ) {
  17808. for( var i = 0; i < playing.length; i ++ )
  17809. playing[ i ].update( deltaTimeMS );
  17810. };
  17811. //--- add ---
  17812. that.addToUpdate = function( animation ) {
  17813. if ( playing.indexOf( animation ) === -1 )
  17814. playing.push( animation );
  17815. };
  17816. //--- remove ---
  17817. that.removeFromUpdate = function( animation ) {
  17818. var index = playing.indexOf( animation );
  17819. if( index !== -1 )
  17820. playing.splice( index, 1 );
  17821. };
  17822. //--- add ---
  17823. that.add = function( data ) {
  17824. if ( library[ data.name ] !== undefined )
  17825. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17826. library[ data.name ] = data;
  17827. initData( data );
  17828. };
  17829. //--- get ---
  17830. that.get = function( name ) {
  17831. if ( typeof name === "string" ) {
  17832. if ( library[ name ] ) {
  17833. return library[ name ];
  17834. } else {
  17835. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17836. return null;
  17837. }
  17838. } else {
  17839. // todo: add simple tween library
  17840. }
  17841. };
  17842. //--- parse ---
  17843. that.parse = function( root ) {
  17844. // setup hierarchy
  17845. var hierarchy = [];
  17846. if ( root instanceof THREE.SkinnedMesh ) {
  17847. for( var b = 0; b < root.bones.length; b++ ) {
  17848. hierarchy.push( root.bones[ b ] );
  17849. }
  17850. } else {
  17851. parseRecurseHierarchy( root, hierarchy );
  17852. }
  17853. return hierarchy;
  17854. };
  17855. var parseRecurseHierarchy = function( root, hierarchy ) {
  17856. hierarchy.push( root );
  17857. for( var c = 0; c < root.children.length; c++ )
  17858. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17859. }
  17860. //--- init data ---
  17861. var initData = function( data ) {
  17862. if( data.initialized === true )
  17863. return;
  17864. // loop through all keys
  17865. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17866. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17867. // remove minus times
  17868. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17869. data.hierarchy[ h ].keys[ k ].time = 0;
  17870. // create quaternions
  17871. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17872. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17873. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17874. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17875. }
  17876. }
  17877. // prepare morph target keys
  17878. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17879. // get all used
  17880. var usedMorphTargets = {};
  17881. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17882. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17883. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17884. usedMorphTargets[ morphTargetName ] = -1;
  17885. }
  17886. }
  17887. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17888. // set all used on all frames
  17889. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17890. var influences = {};
  17891. for ( var morphTargetName in usedMorphTargets ) {
  17892. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17893. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17894. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17895. break;
  17896. }
  17897. }
  17898. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17899. influences[ morphTargetName ] = 0;
  17900. }
  17901. }
  17902. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17903. }
  17904. }
  17905. // remove all keys that are on the same time
  17906. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17907. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17908. data.hierarchy[ h ].keys.splice( k, 1 );
  17909. k --;
  17910. }
  17911. }
  17912. // set index
  17913. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17914. data.hierarchy[ h ].keys[ k ].index = k;
  17915. }
  17916. }
  17917. // JIT
  17918. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17919. data.JIT = {};
  17920. data.JIT.hierarchy = [];
  17921. for( var h = 0; h < data.hierarchy.length; h ++ )
  17922. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17923. // done
  17924. data.initialized = true;
  17925. };
  17926. // interpolation types
  17927. that.LINEAR = 0;
  17928. that.CATMULLROM = 1;
  17929. that.CATMULLROM_FORWARD = 2;
  17930. return that;
  17931. }());
  17932. /**
  17933. * @author mikael emtinger / http://gomo.se/
  17934. * @author mrdoob / http://mrdoob.com/
  17935. * @author alteredq / http://alteredqualia.com/
  17936. */
  17937. THREE.Animation = function ( root, name, interpolationType ) {
  17938. this.root = root;
  17939. this.data = THREE.AnimationHandler.get( name );
  17940. this.hierarchy = THREE.AnimationHandler.parse( root );
  17941. this.currentTime = 0;
  17942. this.timeScale = 1;
  17943. this.isPlaying = false;
  17944. this.isPaused = true;
  17945. this.loop = true;
  17946. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17947. this.points = [];
  17948. this.target = new THREE.Vector3();
  17949. };
  17950. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17951. if ( this.isPlaying === false ) {
  17952. this.isPlaying = true;
  17953. this.loop = loop !== undefined ? loop : true;
  17954. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17955. // reset key cache
  17956. var h, hl = this.hierarchy.length,
  17957. object;
  17958. for ( h = 0; h < hl; h ++ ) {
  17959. object = this.hierarchy[ h ];
  17960. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17961. object.useQuaternion = true;
  17962. }
  17963. object.matrixAutoUpdate = true;
  17964. if ( object.animationCache === undefined ) {
  17965. object.animationCache = {};
  17966. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17967. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17968. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17969. }
  17970. var prevKey = object.animationCache.prevKey;
  17971. var nextKey = object.animationCache.nextKey;
  17972. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17973. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17974. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17975. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17976. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17977. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17978. }
  17979. this.update( 0 );
  17980. }
  17981. this.isPaused = false;
  17982. THREE.AnimationHandler.addToUpdate( this );
  17983. };
  17984. THREE.Animation.prototype.pause = function() {
  17985. if ( this.isPaused === true ) {
  17986. THREE.AnimationHandler.addToUpdate( this );
  17987. } else {
  17988. THREE.AnimationHandler.removeFromUpdate( this );
  17989. }
  17990. this.isPaused = !this.isPaused;
  17991. };
  17992. THREE.Animation.prototype.stop = function() {
  17993. this.isPlaying = false;
  17994. this.isPaused = false;
  17995. THREE.AnimationHandler.removeFromUpdate( this );
  17996. };
  17997. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17998. // early out
  17999. if ( this.isPlaying === false ) return;
  18000. // vars
  18001. var types = [ "pos", "rot", "scl" ];
  18002. var type;
  18003. var scale;
  18004. var vector;
  18005. var prevXYZ, nextXYZ;
  18006. var prevKey, nextKey;
  18007. var object;
  18008. var animationCache;
  18009. var frame;
  18010. var JIThierarchy = this.data.JIT.hierarchy;
  18011. var currentTime, unloopedCurrentTime;
  18012. var currentPoint, forwardPoint, angle;
  18013. this.currentTime += deltaTimeMS * this.timeScale;
  18014. unloopedCurrentTime = this.currentTime;
  18015. currentTime = this.currentTime = this.currentTime % this.data.length;
  18016. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18017. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18018. object = this.hierarchy[ h ];
  18019. animationCache = object.animationCache;
  18020. // loop through pos/rot/scl
  18021. for ( var t = 0; t < 3; t ++ ) {
  18022. // get keys
  18023. type = types[ t ];
  18024. prevKey = animationCache.prevKey[ type ];
  18025. nextKey = animationCache.nextKey[ type ];
  18026. // switch keys?
  18027. if ( nextKey.time <= unloopedCurrentTime ) {
  18028. // did we loop?
  18029. if ( currentTime < unloopedCurrentTime ) {
  18030. if ( this.loop ) {
  18031. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18032. nextKey = this.getNextKeyWith( type, h, 1 );
  18033. while( nextKey.time < currentTime ) {
  18034. prevKey = nextKey;
  18035. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18036. }
  18037. } else {
  18038. this.stop();
  18039. return;
  18040. }
  18041. } else {
  18042. do {
  18043. prevKey = nextKey;
  18044. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18045. } while( nextKey.time < currentTime )
  18046. }
  18047. animationCache.prevKey[ type ] = prevKey;
  18048. animationCache.nextKey[ type ] = nextKey;
  18049. }
  18050. object.matrixAutoUpdate = true;
  18051. object.matrixWorldNeedsUpdate = true;
  18052. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18053. prevXYZ = prevKey[ type ];
  18054. nextXYZ = nextKey[ type ];
  18055. // check scale error
  18056. if ( scale < 0 || scale > 1 ) {
  18057. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18058. scale = scale < 0 ? 0 : 1;
  18059. }
  18060. // interpolate
  18061. if ( type === "pos" ) {
  18062. vector = object.position;
  18063. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18064. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18065. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18066. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18067. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18068. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18069. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18070. this.points[ 1 ] = prevXYZ;
  18071. this.points[ 2 ] = nextXYZ;
  18072. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18073. scale = scale * 0.33 + 0.33;
  18074. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18075. vector.x = currentPoint[ 0 ];
  18076. vector.y = currentPoint[ 1 ];
  18077. vector.z = currentPoint[ 2 ];
  18078. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18079. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18080. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18081. this.target.sub( vector );
  18082. this.target.y = 0;
  18083. this.target.normalize();
  18084. angle = Math.atan2( this.target.x, this.target.z );
  18085. object.rotation.set( 0, angle, 0 );
  18086. }
  18087. }
  18088. } else if ( type === "rot" ) {
  18089. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18090. } else if ( type === "scl" ) {
  18091. vector = object.scale;
  18092. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18093. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18094. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18095. }
  18096. }
  18097. }
  18098. };
  18099. // Catmull-Rom spline
  18100. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18101. var c = [], v3 = [],
  18102. point, intPoint, weight, w2, w3,
  18103. pa, pb, pc, pd;
  18104. point = ( points.length - 1 ) * scale;
  18105. intPoint = Math.floor( point );
  18106. weight = point - intPoint;
  18107. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18108. c[ 1 ] = intPoint;
  18109. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18110. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18111. pa = points[ c[ 0 ] ];
  18112. pb = points[ c[ 1 ] ];
  18113. pc = points[ c[ 2 ] ];
  18114. pd = points[ c[ 3 ] ];
  18115. w2 = weight * weight;
  18116. w3 = weight * w2;
  18117. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18118. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18119. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18120. return v3;
  18121. };
  18122. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18123. var v0 = ( p2 - p0 ) * 0.5,
  18124. v1 = ( p3 - p1 ) * 0.5;
  18125. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18126. };
  18127. // Get next key with
  18128. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18129. var keys = this.data.hierarchy[ h ].keys;
  18130. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18131. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18132. key = key < keys.length - 1 ? key : keys.length - 1;
  18133. } else {
  18134. key = key % keys.length;
  18135. }
  18136. for ( ; key < keys.length; key++ ) {
  18137. if ( keys[ key ][ type ] !== undefined ) {
  18138. return keys[ key ];
  18139. }
  18140. }
  18141. return this.data.hierarchy[ h ].keys[ 0 ];
  18142. };
  18143. // Get previous key with
  18144. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18145. var keys = this.data.hierarchy[ h ].keys;
  18146. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18147. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18148. key = key > 0 ? key : 0;
  18149. } else {
  18150. key = key >= 0 ? key : key + keys.length;
  18151. }
  18152. for ( ; key >= 0; key -- ) {
  18153. if ( keys[ key ][ type ] !== undefined ) {
  18154. return keys[ key ];
  18155. }
  18156. }
  18157. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18158. };
  18159. /**
  18160. * @author mikael emtinger / http://gomo.se/
  18161. * @author mrdoob / http://mrdoob.com/
  18162. * @author alteredq / http://alteredqualia.com/
  18163. * @author khang duong
  18164. * @author erik kitson
  18165. */
  18166. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18167. this.root = root;
  18168. this.data = THREE.AnimationHandler.get( data );
  18169. this.hierarchy = THREE.AnimationHandler.parse( root );
  18170. this.currentTime = 0;
  18171. this.timeScale = 0.001;
  18172. this.isPlaying = false;
  18173. this.isPaused = true;
  18174. this.loop = true;
  18175. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18176. // initialize to first keyframes
  18177. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18178. var keys = this.data.hierarchy[h].keys,
  18179. sids = this.data.hierarchy[h].sids,
  18180. obj = this.hierarchy[h];
  18181. if ( keys.length && sids ) {
  18182. for ( var s = 0; s < sids.length; s++ ) {
  18183. var sid = sids[ s ],
  18184. next = this.getNextKeyWith( sid, h, 0 );
  18185. if ( next ) {
  18186. next.apply( sid );
  18187. }
  18188. }
  18189. obj.matrixAutoUpdate = false;
  18190. this.data.hierarchy[h].node.updateMatrix();
  18191. obj.matrixWorldNeedsUpdate = true;
  18192. }
  18193. }
  18194. };
  18195. // Play
  18196. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18197. if( !this.isPlaying ) {
  18198. this.isPlaying = true;
  18199. this.loop = loop !== undefined ? loop : true;
  18200. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18201. this.startTimeMs = startTimeMS;
  18202. this.startTime = 10000000;
  18203. this.endTime = -this.startTime;
  18204. // reset key cache
  18205. var h, hl = this.hierarchy.length,
  18206. object,
  18207. node;
  18208. for ( h = 0; h < hl; h++ ) {
  18209. object = this.hierarchy[ h ];
  18210. node = this.data.hierarchy[ h ];
  18211. object.useQuaternion = true;
  18212. if ( node.animationCache === undefined ) {
  18213. node.animationCache = {};
  18214. node.animationCache.prevKey = null;
  18215. node.animationCache.nextKey = null;
  18216. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18217. }
  18218. var keys = this.data.hierarchy[h].keys;
  18219. if (keys.length) {
  18220. node.animationCache.prevKey = keys[ 0 ];
  18221. node.animationCache.nextKey = keys[ 1 ];
  18222. this.startTime = Math.min( keys[0].time, this.startTime );
  18223. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18224. }
  18225. }
  18226. this.update( 0 );
  18227. }
  18228. this.isPaused = false;
  18229. THREE.AnimationHandler.addToUpdate( this );
  18230. };
  18231. // Pause
  18232. THREE.KeyFrameAnimation.prototype.pause = function() {
  18233. if( this.isPaused ) {
  18234. THREE.AnimationHandler.addToUpdate( this );
  18235. } else {
  18236. THREE.AnimationHandler.removeFromUpdate( this );
  18237. }
  18238. this.isPaused = !this.isPaused;
  18239. };
  18240. // Stop
  18241. THREE.KeyFrameAnimation.prototype.stop = function() {
  18242. this.isPlaying = false;
  18243. this.isPaused = false;
  18244. THREE.AnimationHandler.removeFromUpdate( this );
  18245. // reset JIT matrix and remove cache
  18246. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18247. var obj = this.hierarchy[ h ];
  18248. var node = this.data.hierarchy[ h ];
  18249. if ( node.animationCache !== undefined ) {
  18250. var original = node.animationCache.originalMatrix;
  18251. if( obj instanceof THREE.Bone ) {
  18252. original.copy( obj.skinMatrix );
  18253. obj.skinMatrix = original;
  18254. } else {
  18255. original.copy( obj.matrix );
  18256. obj.matrix = original;
  18257. }
  18258. delete node.animationCache;
  18259. }
  18260. }
  18261. };
  18262. // Update
  18263. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18264. // early out
  18265. if( !this.isPlaying ) return;
  18266. // vars
  18267. var prevKey, nextKey;
  18268. var object;
  18269. var node;
  18270. var frame;
  18271. var JIThierarchy = this.data.JIT.hierarchy;
  18272. var currentTime, unloopedCurrentTime;
  18273. var looped;
  18274. // update
  18275. this.currentTime += deltaTimeMS * this.timeScale;
  18276. unloopedCurrentTime = this.currentTime;
  18277. currentTime = this.currentTime = this.currentTime % this.data.length;
  18278. // if looped around, the current time should be based on the startTime
  18279. if ( currentTime < this.startTimeMs ) {
  18280. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18281. }
  18282. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18283. looped = currentTime < unloopedCurrentTime;
  18284. if ( looped && !this.loop ) {
  18285. // Set the animation to the last keyframes and stop
  18286. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18287. var keys = this.data.hierarchy[h].keys,
  18288. sids = this.data.hierarchy[h].sids,
  18289. end = keys.length-1,
  18290. obj = this.hierarchy[h];
  18291. if ( keys.length ) {
  18292. for ( var s = 0; s < sids.length; s++ ) {
  18293. var sid = sids[ s ],
  18294. prev = this.getPrevKeyWith( sid, h, end );
  18295. if ( prev ) {
  18296. prev.apply( sid );
  18297. }
  18298. }
  18299. this.data.hierarchy[h].node.updateMatrix();
  18300. obj.matrixWorldNeedsUpdate = true;
  18301. }
  18302. }
  18303. this.stop();
  18304. return;
  18305. }
  18306. // check pre-infinity
  18307. if ( currentTime < this.startTime ) {
  18308. return;
  18309. }
  18310. // update
  18311. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18312. object = this.hierarchy[ h ];
  18313. node = this.data.hierarchy[ h ];
  18314. var keys = node.keys,
  18315. animationCache = node.animationCache;
  18316. // use JIT?
  18317. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18318. if( object instanceof THREE.Bone ) {
  18319. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18320. object.matrixWorldNeedsUpdate = false;
  18321. } else {
  18322. object.matrix = JIThierarchy[ h ][ frame ];
  18323. object.matrixWorldNeedsUpdate = true;
  18324. }
  18325. // use interpolation
  18326. } else if ( keys.length ) {
  18327. // make sure so original matrix and not JIT matrix is set
  18328. if ( this.JITCompile && animationCache ) {
  18329. if( object instanceof THREE.Bone ) {
  18330. object.skinMatrix = animationCache.originalMatrix;
  18331. } else {
  18332. object.matrix = animationCache.originalMatrix;
  18333. }
  18334. }
  18335. prevKey = animationCache.prevKey;
  18336. nextKey = animationCache.nextKey;
  18337. if ( prevKey && nextKey ) {
  18338. // switch keys?
  18339. if ( nextKey.time <= unloopedCurrentTime ) {
  18340. // did we loop?
  18341. if ( looped && this.loop ) {
  18342. prevKey = keys[ 0 ];
  18343. nextKey = keys[ 1 ];
  18344. while ( nextKey.time < currentTime ) {
  18345. prevKey = nextKey;
  18346. nextKey = keys[ prevKey.index + 1 ];
  18347. }
  18348. } else if ( !looped ) {
  18349. var lastIndex = keys.length - 1;
  18350. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18351. prevKey = nextKey;
  18352. nextKey = keys[ prevKey.index + 1 ];
  18353. }
  18354. }
  18355. animationCache.prevKey = prevKey;
  18356. animationCache.nextKey = nextKey;
  18357. }
  18358. if(nextKey.time >= currentTime)
  18359. prevKey.interpolate( nextKey, currentTime );
  18360. else
  18361. prevKey.interpolate( nextKey, nextKey.time);
  18362. }
  18363. this.data.hierarchy[h].node.updateMatrix();
  18364. object.matrixWorldNeedsUpdate = true;
  18365. }
  18366. }
  18367. // update JIT?
  18368. if ( this.JITCompile ) {
  18369. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18370. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18371. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18372. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18373. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18374. } else {
  18375. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18376. }
  18377. }
  18378. }
  18379. }
  18380. };
  18381. // Get next key with
  18382. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18383. var keys = this.data.hierarchy[ h ].keys;
  18384. key = key % keys.length;
  18385. for ( ; key < keys.length; key++ ) {
  18386. if ( keys[ key ].hasTarget( sid ) ) {
  18387. return keys[ key ];
  18388. }
  18389. }
  18390. return keys[ 0 ];
  18391. };
  18392. // Get previous key with
  18393. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18394. var keys = this.data.hierarchy[ h ].keys;
  18395. key = key >= 0 ? key : key + keys.length;
  18396. for ( ; key >= 0; key-- ) {
  18397. if ( keys[ key ].hasTarget( sid ) ) {
  18398. return keys[ key ];
  18399. }
  18400. }
  18401. return keys[ keys.length - 1 ];
  18402. };
  18403. /**
  18404. * Camera for rendering cube maps
  18405. * - renders scene into axis-aligned cube
  18406. *
  18407. * @author alteredq / http://alteredqualia.com/
  18408. */
  18409. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18410. THREE.Object3D.call( this );
  18411. var fov = 90, aspect = 1;
  18412. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18413. cameraPX.up.set( 0, -1, 0 );
  18414. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18415. this.add( cameraPX );
  18416. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18417. cameraNX.up.set( 0, -1, 0 );
  18418. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18419. this.add( cameraNX );
  18420. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18421. cameraPY.up.set( 0, 0, 1 );
  18422. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18423. this.add( cameraPY );
  18424. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18425. cameraNY.up.set( 0, 0, -1 );
  18426. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18427. this.add( cameraNY );
  18428. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18429. cameraPZ.up.set( 0, -1, 0 );
  18430. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18431. this.add( cameraPZ );
  18432. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18433. cameraNZ.up.set( 0, -1, 0 );
  18434. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18435. this.add( cameraNZ );
  18436. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18437. this.updateCubeMap = function ( renderer, scene ) {
  18438. var renderTarget = this.renderTarget;
  18439. var generateMipmaps = renderTarget.generateMipmaps;
  18440. renderTarget.generateMipmaps = false;
  18441. renderTarget.activeCubeFace = 0;
  18442. renderer.render( scene, cameraPX, renderTarget );
  18443. renderTarget.activeCubeFace = 1;
  18444. renderer.render( scene, cameraNX, renderTarget );
  18445. renderTarget.activeCubeFace = 2;
  18446. renderer.render( scene, cameraPY, renderTarget );
  18447. renderTarget.activeCubeFace = 3;
  18448. renderer.render( scene, cameraNY, renderTarget );
  18449. renderTarget.activeCubeFace = 4;
  18450. renderer.render( scene, cameraPZ, renderTarget );
  18451. renderTarget.generateMipmaps = generateMipmaps;
  18452. renderTarget.activeCubeFace = 5;
  18453. renderer.render( scene, cameraNZ, renderTarget );
  18454. };
  18455. };
  18456. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18457. /*
  18458. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18459. *
  18460. * A general perpose camera, for setting FOV, Lens Focal Length,
  18461. * and switching between perspective and orthographic views easily.
  18462. * Use this only if you do not wish to manage
  18463. * both a Orthographic and Perspective Camera
  18464. *
  18465. */
  18466. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18467. THREE.Camera.call( this );
  18468. this.fov = fov;
  18469. this.left = -width / 2;
  18470. this.right = width / 2
  18471. this.top = height / 2;
  18472. this.bottom = -height / 2;
  18473. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18474. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18475. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18476. this.zoom = 1;
  18477. this.toPerspective();
  18478. var aspect = width/height;
  18479. };
  18480. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18481. THREE.CombinedCamera.prototype.toPerspective = function () {
  18482. // Switches to the Perspective Camera
  18483. this.near = this.cameraP.near;
  18484. this.far = this.cameraP.far;
  18485. this.cameraP.fov = this.fov / this.zoom ;
  18486. this.cameraP.updateProjectionMatrix();
  18487. this.projectionMatrix = this.cameraP.projectionMatrix;
  18488. this.inPerspectiveMode = true;
  18489. this.inOrthographicMode = false;
  18490. };
  18491. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18492. // Switches to the Orthographic camera estimating viewport from Perspective
  18493. var fov = this.fov;
  18494. var aspect = this.cameraP.aspect;
  18495. var near = this.cameraP.near;
  18496. var far = this.cameraP.far;
  18497. // The size that we set is the mid plane of the viewing frustum
  18498. var hyperfocus = ( near + far ) / 2;
  18499. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18500. var planeHeight = 2 * halfHeight;
  18501. var planeWidth = planeHeight * aspect;
  18502. var halfWidth = planeWidth / 2;
  18503. halfHeight /= this.zoom;
  18504. halfWidth /= this.zoom;
  18505. this.cameraO.left = -halfWidth;
  18506. this.cameraO.right = halfWidth;
  18507. this.cameraO.top = halfHeight;
  18508. this.cameraO.bottom = -halfHeight;
  18509. // this.cameraO.left = -farHalfWidth;
  18510. // this.cameraO.right = farHalfWidth;
  18511. // this.cameraO.top = farHalfHeight;
  18512. // this.cameraO.bottom = -farHalfHeight;
  18513. // this.cameraO.left = this.left / this.zoom;
  18514. // this.cameraO.right = this.right / this.zoom;
  18515. // this.cameraO.top = this.top / this.zoom;
  18516. // this.cameraO.bottom = this.bottom / this.zoom;
  18517. this.cameraO.updateProjectionMatrix();
  18518. this.near = this.cameraO.near;
  18519. this.far = this.cameraO.far;
  18520. this.projectionMatrix = this.cameraO.projectionMatrix;
  18521. this.inPerspectiveMode = false;
  18522. this.inOrthographicMode = true;
  18523. };
  18524. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18525. this.cameraP.aspect = width / height;
  18526. this.left = -width / 2;
  18527. this.right = width / 2
  18528. this.top = height / 2;
  18529. this.bottom = -height / 2;
  18530. };
  18531. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18532. this.fov = fov;
  18533. if ( this.inPerspectiveMode ) {
  18534. this.toPerspective();
  18535. } else {
  18536. this.toOrthographic();
  18537. }
  18538. };
  18539. // For mantaining similar API with PerspectiveCamera
  18540. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18541. if ( this.inPerspectiveMode ) {
  18542. this.toPerspective();
  18543. } else {
  18544. this.toPerspective();
  18545. this.toOrthographic();
  18546. }
  18547. };
  18548. /*
  18549. * Uses Focal Length (in mm) to estimate and set FOV
  18550. * 35mm (fullframe) camera is used if frame size is not specified;
  18551. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18552. */
  18553. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18554. if ( frameHeight === undefined ) frameHeight = 24;
  18555. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18556. this.setFov( fov );
  18557. return fov;
  18558. };
  18559. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18560. this.zoom = zoom;
  18561. if ( this.inPerspectiveMode ) {
  18562. this.toPerspective();
  18563. } else {
  18564. this.toOrthographic();
  18565. }
  18566. };
  18567. THREE.CombinedCamera.prototype.toFrontView = function() {
  18568. this.rotation.x = 0;
  18569. this.rotation.y = 0;
  18570. this.rotation.z = 0;
  18571. // should we be modifing the matrix instead?
  18572. this.rotationAutoUpdate = false;
  18573. };
  18574. THREE.CombinedCamera.prototype.toBackView = function() {
  18575. this.rotation.x = 0;
  18576. this.rotation.y = Math.PI;
  18577. this.rotation.z = 0;
  18578. this.rotationAutoUpdate = false;
  18579. };
  18580. THREE.CombinedCamera.prototype.toLeftView = function() {
  18581. this.rotation.x = 0;
  18582. this.rotation.y = - Math.PI / 2;
  18583. this.rotation.z = 0;
  18584. this.rotationAutoUpdate = false;
  18585. };
  18586. THREE.CombinedCamera.prototype.toRightView = function() {
  18587. this.rotation.x = 0;
  18588. this.rotation.y = Math.PI / 2;
  18589. this.rotation.z = 0;
  18590. this.rotationAutoUpdate = false;
  18591. };
  18592. THREE.CombinedCamera.prototype.toTopView = function() {
  18593. this.rotation.x = - Math.PI / 2;
  18594. this.rotation.y = 0;
  18595. this.rotation.z = 0;
  18596. this.rotationAutoUpdate = false;
  18597. };
  18598. THREE.CombinedCamera.prototype.toBottomView = function() {
  18599. this.rotation.x = Math.PI / 2;
  18600. this.rotation.y = 0;
  18601. this.rotation.z = 0;
  18602. this.rotationAutoUpdate = false;
  18603. };
  18604. /**
  18605. * @author hughes
  18606. */
  18607. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18608. THREE.Geometry.call( this );
  18609. radius = radius || 50;
  18610. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18611. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18612. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18613. var i, uvs = [],
  18614. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18615. this.vertices.push(center);
  18616. uvs.push( centerUV );
  18617. for ( i = 0; i <= segments; i ++ ) {
  18618. var vertex = new THREE.Vector3();
  18619. var segment = thetaStart + i / segments * thetaLength;
  18620. vertex.x = radius * Math.cos( segment );
  18621. vertex.y = radius * Math.sin( segment );
  18622. this.vertices.push( vertex );
  18623. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18624. }
  18625. var n = new THREE.Vector3( 0, 0, 1 );
  18626. for ( i = 1; i <= segments; i ++ ) {
  18627. var v1 = i;
  18628. var v2 = i + 1 ;
  18629. var v3 = 0;
  18630. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18631. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18632. }
  18633. this.computeCentroids();
  18634. this.computeFaceNormals();
  18635. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18636. };
  18637. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18638. /**
  18639. * @author mrdoob / http://mrdoob.com/
  18640. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18641. */
  18642. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18643. THREE.Geometry.call( this );
  18644. var scope = this;
  18645. this.width = width;
  18646. this.height = height;
  18647. this.depth = depth;
  18648. this.widthSegments = widthSegments || 1;
  18649. this.heightSegments = heightSegments || 1;
  18650. this.depthSegments = depthSegments || 1;
  18651. var width_half = this.width / 2;
  18652. var height_half = this.height / 2;
  18653. var depth_half = this.depth / 2;
  18654. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18655. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18656. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18657. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18658. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18659. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18660. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18661. var w, ix, iy,
  18662. gridX = scope.widthSegments,
  18663. gridY = scope.heightSegments,
  18664. width_half = width / 2,
  18665. height_half = height / 2,
  18666. offset = scope.vertices.length;
  18667. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18668. w = 'z';
  18669. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18670. w = 'y';
  18671. gridY = scope.depthSegments;
  18672. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18673. w = 'x';
  18674. gridX = scope.depthSegments;
  18675. }
  18676. var gridX1 = gridX + 1,
  18677. gridY1 = gridY + 1,
  18678. segment_width = width / gridX,
  18679. segment_height = height / gridY,
  18680. normal = new THREE.Vector3();
  18681. normal[ w ] = depth > 0 ? 1 : - 1;
  18682. for ( iy = 0; iy < gridY1; iy ++ ) {
  18683. for ( ix = 0; ix < gridX1; ix ++ ) {
  18684. var vector = new THREE.Vector3();
  18685. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18686. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18687. vector[ w ] = depth;
  18688. scope.vertices.push( vector );
  18689. }
  18690. }
  18691. for ( iy = 0; iy < gridY; iy++ ) {
  18692. for ( ix = 0; ix < gridX; ix++ ) {
  18693. var a = ix + gridX1 * iy;
  18694. var b = ix + gridX1 * ( iy + 1 );
  18695. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18696. var d = ( ix + 1 ) + gridX1 * iy;
  18697. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18698. face.normal.copy( normal );
  18699. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18700. face.materialIndex = materialIndex;
  18701. scope.faces.push( face );
  18702. scope.faceVertexUvs[ 0 ].push( [
  18703. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18704. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18705. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18706. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18707. ] );
  18708. }
  18709. }
  18710. }
  18711. this.computeCentroids();
  18712. this.mergeVertices();
  18713. };
  18714. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18715. /**
  18716. * @author mrdoob / http://mrdoob.com/
  18717. */
  18718. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  18719. THREE.Geometry.call( this );
  18720. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18721. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18722. this.height = height = height !== undefined ? height : 100;
  18723. this.radialSegments = radialSegments = radialSegments || 8;
  18724. this.heightSegments = heightSegments = heightSegments || 1;
  18725. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  18726. var heightHalf = height / 2;
  18727. var x, y, vertices = [], uvs = [];
  18728. for ( y = 0; y <= heightSegments; y ++ ) {
  18729. var verticesRow = [];
  18730. var uvsRow = [];
  18731. var v = y / heightSegments;
  18732. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18733. for ( x = 0; x <= radialSegments; x ++ ) {
  18734. var u = x / radialSegments;
  18735. var vertex = new THREE.Vector3();
  18736. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18737. vertex.y = - v * height + heightHalf;
  18738. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18739. this.vertices.push( vertex );
  18740. verticesRow.push( this.vertices.length - 1 );
  18741. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18742. }
  18743. vertices.push( verticesRow );
  18744. uvs.push( uvsRow );
  18745. }
  18746. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18747. var na, nb;
  18748. for ( x = 0; x < radialSegments; x ++ ) {
  18749. if ( radiusTop !== 0 ) {
  18750. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18751. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18752. } else {
  18753. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18754. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18755. }
  18756. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18757. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18758. for ( y = 0; y < heightSegments; y ++ ) {
  18759. var v1 = vertices[ y ][ x ];
  18760. var v2 = vertices[ y + 1 ][ x ];
  18761. var v3 = vertices[ y + 1 ][ x + 1 ];
  18762. var v4 = vertices[ y ][ x + 1 ];
  18763. var n1 = na.clone();
  18764. var n2 = na.clone();
  18765. var n3 = nb.clone();
  18766. var n4 = nb.clone();
  18767. var uv1 = uvs[ y ][ x ].clone();
  18768. var uv2 = uvs[ y + 1 ][ x ].clone();
  18769. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18770. var uv4 = uvs[ y ][ x + 1 ].clone();
  18771. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18772. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18773. }
  18774. }
  18775. // top cap
  18776. if ( openEnded === false && radiusTop > 0 ) {
  18777. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18778. for ( x = 0; x < radialSegments; x ++ ) {
  18779. var v1 = vertices[ 0 ][ x ];
  18780. var v2 = vertices[ 0 ][ x + 1 ];
  18781. var v3 = this.vertices.length - 1;
  18782. var n1 = new THREE.Vector3( 0, 1, 0 );
  18783. var n2 = new THREE.Vector3( 0, 1, 0 );
  18784. var n3 = new THREE.Vector3( 0, 1, 0 );
  18785. var uv1 = uvs[ 0 ][ x ].clone();
  18786. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18787. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18788. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18789. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18790. }
  18791. }
  18792. // bottom cap
  18793. if ( openEnded === false && radiusBottom > 0 ) {
  18794. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18795. for ( x = 0; x < radialSegments; x ++ ) {
  18796. var v1 = vertices[ y ][ x + 1 ];
  18797. var v2 = vertices[ y ][ x ];
  18798. var v3 = this.vertices.length - 1;
  18799. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18800. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18801. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18802. var uv1 = uvs[ y ][ x + 1 ].clone();
  18803. var uv2 = uvs[ y ][ x ].clone();
  18804. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18805. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18806. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18807. }
  18808. }
  18809. this.computeCentroids();
  18810. this.computeFaceNormals();
  18811. }
  18812. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18813. /**
  18814. * @author zz85 / http://www.lab4games.net/zz85/blog
  18815. *
  18816. * Creates extruded geometry from a path shape.
  18817. *
  18818. * parameters = {
  18819. *
  18820. * size: <float>, // size of the text
  18821. * height: <float>, // thickness to extrude text
  18822. * curveSegments: <int>, // number of points on the curves
  18823. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18824. * amount: <int>, // Amount
  18825. *
  18826. * bevelEnabled: <bool>, // turn on bevel
  18827. * bevelThickness: <float>, // how deep into text bevel goes
  18828. * bevelSize: <float>, // how far from text outline is bevel
  18829. * bevelSegments: <int>, // number of bevel layers
  18830. *
  18831. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18832. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18833. *
  18834. * material: <int> // material index for front and back faces
  18835. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18836. * uvGenerator: <Object> // object that provides UV generator functions
  18837. *
  18838. * }
  18839. **/
  18840. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18841. if ( typeof( shapes ) === "undefined" ) {
  18842. shapes = [];
  18843. return;
  18844. }
  18845. THREE.Geometry.call( this );
  18846. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18847. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18848. this.addShapeList( shapes, options );
  18849. this.computeCentroids();
  18850. this.computeFaceNormals();
  18851. // can't really use automatic vertex normals
  18852. // as then front and back sides get smoothed too
  18853. // should do separate smoothing just for sides
  18854. //this.computeVertexNormals();
  18855. //console.log( "took", ( Date.now() - startTime ) );
  18856. };
  18857. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18858. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18859. var sl = shapes.length;
  18860. for ( var s = 0; s < sl; s ++ ) {
  18861. var shape = shapes[ s ];
  18862. this.addShape( shape, options );
  18863. }
  18864. };
  18865. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18866. var amount = options.amount !== undefined ? options.amount : 100;
  18867. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18868. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18869. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18870. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18871. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18872. var steps = options.steps !== undefined ? options.steps : 1;
  18873. var extrudePath = options.extrudePath;
  18874. var extrudePts, extrudeByPath = false;
  18875. var material = options.material;
  18876. var extrudeMaterial = options.extrudeMaterial;
  18877. // Use default WorldUVGenerator if no UV generators are specified.
  18878. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18879. var shapebb = this.shapebb;
  18880. //shapebb = shape.getBoundingBox();
  18881. var splineTube, binormal, normal, position2;
  18882. if ( extrudePath ) {
  18883. extrudePts = extrudePath.getSpacedPoints( steps );
  18884. extrudeByPath = true;
  18885. bevelEnabled = false; // bevels not supported for path extrusion
  18886. // SETUP TNB variables
  18887. // Reuse TNB from TubeGeomtry for now.
  18888. // TODO1 - have a .isClosed in spline?
  18889. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18890. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18891. binormal = new THREE.Vector3();
  18892. normal = new THREE.Vector3();
  18893. position2 = new THREE.Vector3();
  18894. }
  18895. // Safeguards if bevels are not enabled
  18896. if ( ! bevelEnabled ) {
  18897. bevelSegments = 0;
  18898. bevelThickness = 0;
  18899. bevelSize = 0;
  18900. }
  18901. // Variables initalization
  18902. var ahole, h, hl; // looping of holes
  18903. var scope = this;
  18904. var bevelPoints = [];
  18905. var shapesOffset = this.vertices.length;
  18906. var shapePoints = shape.extractPoints( curveSegments );
  18907. var vertices = shapePoints.shape;
  18908. var holes = shapePoints.holes;
  18909. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18910. if ( reverse ) {
  18911. vertices = vertices.reverse();
  18912. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18913. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18914. ahole = holes[ h ];
  18915. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18916. holes[ h ] = ahole.reverse();
  18917. }
  18918. }
  18919. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18920. }
  18921. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18922. /* Vertices */
  18923. var contour = vertices; // vertices has all points but contour has only points of circumference
  18924. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18925. ahole = holes[ h ];
  18926. vertices = vertices.concat( ahole );
  18927. }
  18928. function scalePt2 ( pt, vec, size ) {
  18929. if ( !vec ) console.log( "die" );
  18930. return vec.clone().multiplyScalar( size ).add( pt );
  18931. }
  18932. var b, bs, t, z,
  18933. vert, vlen = vertices.length,
  18934. face, flen = faces.length,
  18935. cont, clen = contour.length;
  18936. // Find directions for point movement
  18937. var RAD_TO_DEGREES = 180 / Math.PI;
  18938. function getBevelVec( pt_i, pt_j, pt_k ) {
  18939. // Algorithm 2
  18940. return getBevelVec2( pt_i, pt_j, pt_k );
  18941. }
  18942. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18943. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18944. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18945. if ( anglea > angleb ) {
  18946. angleb += Math.PI * 2;
  18947. }
  18948. var anglec = ( anglea + angleb ) / 2;
  18949. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18950. var x = - Math.cos( anglec );
  18951. var y = - Math.sin( anglec );
  18952. var vec = new THREE.Vector2( x, y ); //.normalize();
  18953. return vec;
  18954. }
  18955. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18956. var a = THREE.ExtrudeGeometry.__v1,
  18957. b = THREE.ExtrudeGeometry.__v2,
  18958. v_hat = THREE.ExtrudeGeometry.__v3,
  18959. w_hat = THREE.ExtrudeGeometry.__v4,
  18960. p = THREE.ExtrudeGeometry.__v5,
  18961. q = THREE.ExtrudeGeometry.__v6,
  18962. v, w,
  18963. v_dot_w_hat, q_sub_p_dot_w_hat,
  18964. s, intersection;
  18965. // good reading for line-line intersection
  18966. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18967. // define a as vector j->i
  18968. // define b as vectot k->i
  18969. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18970. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18971. // get unit vectors
  18972. v = a.normalize();
  18973. w = b.normalize();
  18974. // normals from pt i
  18975. v_hat.set( -v.y, v.x );
  18976. w_hat.set( w.y, -w.x );
  18977. // pts from i
  18978. p.copy( pt_i ).add( v_hat );
  18979. q.copy( pt_i ).add( w_hat );
  18980. if ( p.equals( q ) ) {
  18981. //console.log("Warning: lines are straight");
  18982. return w_hat.clone();
  18983. }
  18984. // Points from j, k. helps prevents points cross overover most of the time
  18985. p.copy( pt_j ).add( v_hat );
  18986. q.copy( pt_k ).add( w_hat );
  18987. v_dot_w_hat = v.dot( w_hat );
  18988. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18989. // We should not reach these conditions
  18990. if ( v_dot_w_hat === 0 ) {
  18991. console.log( "Either infinite or no solutions!" );
  18992. if ( q_sub_p_dot_w_hat === 0 ) {
  18993. console.log( "Its finite solutions." );
  18994. } else {
  18995. console.log( "Too bad, no solutions." );
  18996. }
  18997. }
  18998. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18999. if ( s < 0 ) {
  19000. // in case of emergecy, revert to algorithm 1.
  19001. return getBevelVec1( pt_i, pt_j, pt_k );
  19002. }
  19003. intersection = v.multiplyScalar( s ).add( p );
  19004. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  19005. }
  19006. var contourMovements = [];
  19007. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19008. if ( j === il ) j = 0;
  19009. if ( k === il ) k = 0;
  19010. // (j)---(i)---(k)
  19011. // console.log('i,j,k', i, j , k)
  19012. var pt_i = contour[ i ];
  19013. var pt_j = contour[ j ];
  19014. var pt_k = contour[ k ];
  19015. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19016. }
  19017. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19018. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19019. ahole = holes[ h ];
  19020. oneHoleMovements = [];
  19021. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19022. if ( j === il ) j = 0;
  19023. if ( k === il ) k = 0;
  19024. // (j)---(i)---(k)
  19025. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19026. }
  19027. holesMovements.push( oneHoleMovements );
  19028. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19029. }
  19030. // Loop bevelSegments, 1 for the front, 1 for the back
  19031. for ( b = 0; b < bevelSegments; b ++ ) {
  19032. //for ( b = bevelSegments; b > 0; b -- ) {
  19033. t = b / bevelSegments;
  19034. z = bevelThickness * ( 1 - t );
  19035. //z = bevelThickness * t;
  19036. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19037. //bs = bevelSize * t ; // linear
  19038. // contract shape
  19039. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19040. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19041. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19042. v( vert.x, vert.y, - z );
  19043. }
  19044. // expand holes
  19045. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19046. ahole = holes[ h ];
  19047. oneHoleMovements = holesMovements[ h ];
  19048. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19049. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19050. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19051. v( vert.x, vert.y, -z );
  19052. }
  19053. }
  19054. }
  19055. bs = bevelSize;
  19056. // Back facing vertices
  19057. for ( i = 0; i < vlen; i ++ ) {
  19058. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19059. if ( !extrudeByPath ) {
  19060. v( vert.x, vert.y, 0 );
  19061. } else {
  19062. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19063. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19064. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19065. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19066. v( position2.x, position2.y, position2.z );
  19067. }
  19068. }
  19069. // Add stepped vertices...
  19070. // Including front facing vertices
  19071. var s;
  19072. for ( s = 1; s <= steps; s ++ ) {
  19073. for ( i = 0; i < vlen; i ++ ) {
  19074. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19075. if ( !extrudeByPath ) {
  19076. v( vert.x, vert.y, amount / steps * s );
  19077. } else {
  19078. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19079. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19080. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19081. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19082. v( position2.x, position2.y, position2.z );
  19083. }
  19084. }
  19085. }
  19086. // Add bevel segments planes
  19087. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19088. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19089. t = b / bevelSegments;
  19090. z = bevelThickness * ( 1 - t );
  19091. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19092. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19093. // contract shape
  19094. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19095. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19096. v( vert.x, vert.y, amount + z );
  19097. }
  19098. // expand holes
  19099. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19100. ahole = holes[ h ];
  19101. oneHoleMovements = holesMovements[ h ];
  19102. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19103. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19104. if ( !extrudeByPath ) {
  19105. v( vert.x, vert.y, amount + z );
  19106. } else {
  19107. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19108. }
  19109. }
  19110. }
  19111. }
  19112. /* Faces */
  19113. // Top and bottom faces
  19114. buildLidFaces();
  19115. // Sides faces
  19116. buildSideFaces();
  19117. ///// Internal functions
  19118. function buildLidFaces() {
  19119. if ( bevelEnabled ) {
  19120. var layer = 0 ; // steps + 1
  19121. var offset = vlen * layer;
  19122. // Bottom faces
  19123. for ( i = 0; i < flen; i ++ ) {
  19124. face = faces[ i ];
  19125. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19126. }
  19127. layer = steps + bevelSegments * 2;
  19128. offset = vlen * layer;
  19129. // Top faces
  19130. for ( i = 0; i < flen; i ++ ) {
  19131. face = faces[ i ];
  19132. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19133. }
  19134. } else {
  19135. // Bottom faces
  19136. for ( i = 0; i < flen; i++ ) {
  19137. face = faces[ i ];
  19138. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19139. }
  19140. // Top faces
  19141. for ( i = 0; i < flen; i ++ ) {
  19142. face = faces[ i ];
  19143. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19144. }
  19145. }
  19146. }
  19147. // Create faces for the z-sides of the shape
  19148. function buildSideFaces() {
  19149. var layeroffset = 0;
  19150. sidewalls( contour, layeroffset );
  19151. layeroffset += contour.length;
  19152. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19153. ahole = holes[ h ];
  19154. sidewalls( ahole, layeroffset );
  19155. //, true
  19156. layeroffset += ahole.length;
  19157. }
  19158. }
  19159. function sidewalls( contour, layeroffset ) {
  19160. var j, k;
  19161. i = contour.length;
  19162. while ( --i >= 0 ) {
  19163. j = i;
  19164. k = i - 1;
  19165. if ( k < 0 ) k = contour.length - 1;
  19166. //console.log('b', i,j, i-1, k,vertices.length);
  19167. var s = 0, sl = steps + bevelSegments * 2;
  19168. for ( s = 0; s < sl; s ++ ) {
  19169. var slen1 = vlen * s;
  19170. var slen2 = vlen * ( s + 1 );
  19171. var a = layeroffset + j + slen1,
  19172. b = layeroffset + k + slen1,
  19173. c = layeroffset + k + slen2,
  19174. d = layeroffset + j + slen2;
  19175. f4( a, b, c, d, contour, s, sl, j, k );
  19176. }
  19177. }
  19178. }
  19179. function v( x, y, z ) {
  19180. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19181. }
  19182. function f3( a, b, c, isBottom ) {
  19183. a += shapesOffset;
  19184. b += shapesOffset;
  19185. c += shapesOffset;
  19186. // normal, color, material
  19187. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19188. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19189. scope.faceVertexUvs[ 0 ].push( uvs );
  19190. }
  19191. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19192. a += shapesOffset;
  19193. b += shapesOffset;
  19194. c += shapesOffset;
  19195. d += shapesOffset;
  19196. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19197. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19198. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19199. scope.faceVertexUvs[ 0 ].push( uvs );
  19200. }
  19201. };
  19202. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19203. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19204. var ax = geometry.vertices[ indexA ].x,
  19205. ay = geometry.vertices[ indexA ].y,
  19206. bx = geometry.vertices[ indexB ].x,
  19207. by = geometry.vertices[ indexB ].y,
  19208. cx = geometry.vertices[ indexC ].x,
  19209. cy = geometry.vertices[ indexC ].y;
  19210. return [
  19211. new THREE.Vector2( ax, ay ),
  19212. new THREE.Vector2( bx, by ),
  19213. new THREE.Vector2( cx, cy )
  19214. ];
  19215. },
  19216. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19217. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19218. },
  19219. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19220. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19221. contourIndex1, contourIndex2 ) {
  19222. var ax = geometry.vertices[ indexA ].x,
  19223. ay = geometry.vertices[ indexA ].y,
  19224. az = geometry.vertices[ indexA ].z,
  19225. bx = geometry.vertices[ indexB ].x,
  19226. by = geometry.vertices[ indexB ].y,
  19227. bz = geometry.vertices[ indexB ].z,
  19228. cx = geometry.vertices[ indexC ].x,
  19229. cy = geometry.vertices[ indexC ].y,
  19230. cz = geometry.vertices[ indexC ].z,
  19231. dx = geometry.vertices[ indexD ].x,
  19232. dy = geometry.vertices[ indexD ].y,
  19233. dz = geometry.vertices[ indexD ].z;
  19234. if ( Math.abs( ay - by ) < 0.01 ) {
  19235. return [
  19236. new THREE.Vector2( ax, 1 - az ),
  19237. new THREE.Vector2( bx, 1 - bz ),
  19238. new THREE.Vector2( cx, 1 - cz ),
  19239. new THREE.Vector2( dx, 1 - dz )
  19240. ];
  19241. } else {
  19242. return [
  19243. new THREE.Vector2( ay, 1 - az ),
  19244. new THREE.Vector2( by, 1 - bz ),
  19245. new THREE.Vector2( cy, 1 - cz ),
  19246. new THREE.Vector2( dy, 1 - dz )
  19247. ];
  19248. }
  19249. }
  19250. };
  19251. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19252. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19253. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19254. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19255. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19256. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19257. /**
  19258. * @author jonobr1 / http://jonobr1.com
  19259. *
  19260. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19261. * ExtrudeGeometry.
  19262. *
  19263. * parameters = {
  19264. *
  19265. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19266. *
  19267. * material: <int> // material index for front and back faces
  19268. * uvGenerator: <Object> // object that provides UV generator functions
  19269. *
  19270. * }
  19271. **/
  19272. THREE.ShapeGeometry = function ( shapes, options ) {
  19273. THREE.Geometry.call( this );
  19274. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19275. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19276. this.addShapeList( shapes, options );
  19277. this.computeCentroids();
  19278. this.computeFaceNormals();
  19279. };
  19280. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19281. /**
  19282. * Add an array of shapes to THREE.ShapeGeometry.
  19283. */
  19284. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19285. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19286. this.addShape( shapes[ i ], options );
  19287. }
  19288. return this;
  19289. };
  19290. /**
  19291. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19292. */
  19293. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19294. if ( options === undefined ) options = {};
  19295. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19296. var material = options.material;
  19297. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19298. var shapebb = this.shapebb;
  19299. //
  19300. var i, l, hole, s;
  19301. var shapesOffset = this.vertices.length;
  19302. var shapePoints = shape.extractPoints( curveSegments );
  19303. var vertices = shapePoints.shape;
  19304. var holes = shapePoints.holes;
  19305. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19306. if ( reverse ) {
  19307. vertices = vertices.reverse();
  19308. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19309. for ( i = 0, l = holes.length; i < l; i++ ) {
  19310. hole = holes[ i ];
  19311. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19312. holes[ i ] = hole.reverse();
  19313. }
  19314. }
  19315. reverse = false;
  19316. }
  19317. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19318. // Vertices
  19319. var contour = vertices;
  19320. for ( i = 0, l = holes.length; i < l; i++ ) {
  19321. hole = holes[ i ];
  19322. vertices = vertices.concat( hole );
  19323. }
  19324. //
  19325. var vert, vlen = vertices.length;
  19326. var face, flen = faces.length;
  19327. var cont, clen = contour.length;
  19328. for ( i = 0; i < vlen; i++ ) {
  19329. vert = vertices[ i ];
  19330. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19331. }
  19332. for ( i = 0; i < flen; i++ ) {
  19333. face = faces[ i ];
  19334. var a = face[ 0 ] + shapesOffset;
  19335. var b = face[ 1 ] + shapesOffset;
  19336. var c = face[ 2 ] + shapesOffset;
  19337. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19338. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19339. }
  19340. };
  19341. /**
  19342. * @author astrodud / http://astrodud.isgreat.org/
  19343. * @author zz85 / https://github.com/zz85
  19344. * @author bhouston / http://exocortex.com
  19345. */
  19346. // points - to create a closed torus, one must use a set of points
  19347. // like so: [ a, b, c, d, a ], see first is the same as last.
  19348. // segments - the number of circumference segments to create
  19349. // phiStart - the starting radian
  19350. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19351. // 2*pi is a closed lathe, less than 2PI is a portion.
  19352. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19353. THREE.Geometry.call( this );
  19354. segments = segments || 12;
  19355. phiStart = phiStart || 0;
  19356. phiLength = phiLength || 2 * Math.PI;
  19357. var inversePointLength = 1.0 / ( points.length - 1 );
  19358. var inverseSegments = 1.0 / segments;
  19359. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19360. var phi = phiStart + i * inverseSegments * phiLength;
  19361. var c = Math.cos( phi ),
  19362. s = Math.sin( phi );
  19363. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19364. var pt = points[ j ];
  19365. var vertex = new THREE.Vector3();
  19366. vertex.x = c * pt.x - s * pt.y;
  19367. vertex.y = s * pt.x + c * pt.y;
  19368. vertex.z = pt.z;
  19369. this.vertices.push( vertex );
  19370. }
  19371. }
  19372. var np = points.length;
  19373. for ( var i = 0, il = segments; i < il; i ++ ) {
  19374. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19375. var base = j + np * i;
  19376. var a = base;
  19377. var b = base + np;
  19378. var c = base + 1 + np;
  19379. var d = base + 1;
  19380. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19381. var u0 = i * inverseSegments;
  19382. var v0 = j * inversePointLength;
  19383. var u1 = u0 + inverseSegments;
  19384. var v1 = v0 + inversePointLength;
  19385. this.faceVertexUvs[ 0 ].push( [
  19386. new THREE.Vector2( u0, v0 ),
  19387. new THREE.Vector2( u1, v0 ),
  19388. new THREE.Vector2( u1, v1 ),
  19389. new THREE.Vector2( u0, v1 )
  19390. ] );
  19391. }
  19392. }
  19393. this.mergeVertices();
  19394. this.computeCentroids();
  19395. this.computeFaceNormals();
  19396. this.computeVertexNormals();
  19397. };
  19398. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19399. /**
  19400. * @author mrdoob / http://mrdoob.com/
  19401. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19402. */
  19403. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19404. THREE.Geometry.call( this );
  19405. this.width = width;
  19406. this.height = height;
  19407. this.widthSegments = widthSegments || 1;
  19408. this.heightSegments = heightSegments || 1;
  19409. var ix, iz;
  19410. var width_half = width / 2;
  19411. var height_half = height / 2;
  19412. var gridX = this.widthSegments;
  19413. var gridZ = this.heightSegments;
  19414. var gridX1 = gridX + 1;
  19415. var gridZ1 = gridZ + 1;
  19416. var segment_width = this.width / gridX;
  19417. var segment_height = this.height / gridZ;
  19418. var normal = new THREE.Vector3( 0, 0, 1 );
  19419. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19420. for ( ix = 0; ix < gridX1; ix ++ ) {
  19421. var x = ix * segment_width - width_half;
  19422. var y = iz * segment_height - height_half;
  19423. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19424. }
  19425. }
  19426. for ( iz = 0; iz < gridZ; iz ++ ) {
  19427. for ( ix = 0; ix < gridX; ix ++ ) {
  19428. var a = ix + gridX1 * iz;
  19429. var b = ix + gridX1 * ( iz + 1 );
  19430. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19431. var d = ( ix + 1 ) + gridX1 * iz;
  19432. var face = new THREE.Face4( a, b, c, d );
  19433. face.normal.copy( normal );
  19434. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19435. this.faces.push( face );
  19436. this.faceVertexUvs[ 0 ].push( [
  19437. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19438. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19439. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19440. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19441. ] );
  19442. }
  19443. }
  19444. this.computeCentroids();
  19445. };
  19446. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19447. /**
  19448. * @author Kaleb Murphy
  19449. */
  19450. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19451. THREE.Geometry.call( this );
  19452. innerRadius = innerRadius || 0;
  19453. outerRadius = outerRadius || 50;
  19454. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19455. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19456. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19457. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19458. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19459. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19460. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19461. var vertex = new THREE.Vector3();
  19462. var segment = thetaStart + o / thetaSegments * thetaLength;
  19463. vertex.x = radius * Math.cos( segment );
  19464. vertex.y = radius * Math.sin( segment );
  19465. this.vertices.push( vertex );
  19466. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  19467. }
  19468. radius += radiusStep;
  19469. }
  19470. var n = new THREE.Vector3( 0, 0, 1 );
  19471. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19472. var thetaSegment = i * thetaSegments;
  19473. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19474. var segment = o + thetaSegment;
  19475. var v1 = segment + i;
  19476. var v2 = segment + thetaSegments + i;
  19477. var v3 = segment + thetaSegments + 1 + i;
  19478. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19479. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19480. v1 = segment + i;
  19481. v2 = segment + thetaSegments + 1 + i;
  19482. v3 = segment + 1 + i;
  19483. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19484. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19485. }
  19486. }
  19487. this.computeCentroids();
  19488. this.computeFaceNormals();
  19489. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19490. };
  19491. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19492. /**
  19493. * @author mrdoob / http://mrdoob.com/
  19494. */
  19495. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19496. THREE.Geometry.call( this );
  19497. this.radius = radius = radius || 50;
  19498. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19499. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19500. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19501. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19502. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19503. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19504. var x, y, vertices = [], uvs = [];
  19505. for ( y = 0; y <= heightSegments; y ++ ) {
  19506. var verticesRow = [];
  19507. var uvsRow = [];
  19508. for ( x = 0; x <= widthSegments; x ++ ) {
  19509. var u = x / widthSegments;
  19510. var v = y / heightSegments;
  19511. var vertex = new THREE.Vector3();
  19512. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19513. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19514. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19515. this.vertices.push( vertex );
  19516. verticesRow.push( this.vertices.length - 1 );
  19517. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19518. }
  19519. vertices.push( verticesRow );
  19520. uvs.push( uvsRow );
  19521. }
  19522. for ( y = 0; y < this.heightSegments; y ++ ) {
  19523. for ( x = 0; x < this.widthSegments; x ++ ) {
  19524. var v1 = vertices[ y ][ x + 1 ];
  19525. var v2 = vertices[ y ][ x ];
  19526. var v3 = vertices[ y + 1 ][ x ];
  19527. var v4 = vertices[ y + 1 ][ x + 1 ];
  19528. var n1 = this.vertices[ v1 ].clone().normalize();
  19529. var n2 = this.vertices[ v2 ].clone().normalize();
  19530. var n3 = this.vertices[ v3 ].clone().normalize();
  19531. var n4 = this.vertices[ v4 ].clone().normalize();
  19532. var uv1 = uvs[ y ][ x + 1 ].clone();
  19533. var uv2 = uvs[ y ][ x ].clone();
  19534. var uv3 = uvs[ y + 1 ][ x ].clone();
  19535. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19536. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19537. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19538. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19539. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19540. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19541. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19542. } else {
  19543. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19544. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19545. }
  19546. }
  19547. }
  19548. this.computeCentroids();
  19549. this.computeFaceNormals();
  19550. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19551. };
  19552. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19553. /**
  19554. * @author zz85 / http://www.lab4games.net/zz85/blog
  19555. * @author alteredq / http://alteredqualia.com/
  19556. *
  19557. * For creating 3D text geometry in three.js
  19558. *
  19559. * Text = 3D Text
  19560. *
  19561. * parameters = {
  19562. * size: <float>, // size of the text
  19563. * height: <float>, // thickness to extrude text
  19564. * curveSegments: <int>, // number of points on the curves
  19565. *
  19566. * font: <string>, // font name
  19567. * weight: <string>, // font weight (normal, bold)
  19568. * style: <string>, // font style (normal, italics)
  19569. *
  19570. * bevelEnabled: <bool>, // turn on bevel
  19571. * bevelThickness: <float>, // how deep into text bevel goes
  19572. * bevelSize: <float>, // how far from text outline is bevel
  19573. * }
  19574. *
  19575. */
  19576. /* Usage Examples
  19577. // TextGeometry wrapper
  19578. var text3d = new TextGeometry( text, options );
  19579. // Complete manner
  19580. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19581. var text3d = new ExtrudeGeometry( textShapes, options );
  19582. */
  19583. THREE.TextGeometry = function ( text, parameters ) {
  19584. parameters = parameters || {};
  19585. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19586. // translate parameters to ExtrudeGeometry API
  19587. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19588. // defaults
  19589. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19590. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19591. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19592. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19593. };
  19594. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19595. /**
  19596. * @author oosmoxiecode
  19597. * @author mrdoob / http://mrdoob.com/
  19598. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19599. */
  19600. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19601. THREE.Geometry.call( this );
  19602. var scope = this;
  19603. this.radius = radius || 100;
  19604. this.tube = tube || 40;
  19605. this.radialSegments = radialSegments || 8;
  19606. this.tubularSegments = tubularSegments || 6;
  19607. this.arc = arc || Math.PI * 2;
  19608. var center = new THREE.Vector3(), uvs = [], normals = [];
  19609. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19610. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19611. var u = i / this.tubularSegments * this.arc;
  19612. var v = j / this.radialSegments * Math.PI * 2;
  19613. center.x = this.radius * Math.cos( u );
  19614. center.y = this.radius * Math.sin( u );
  19615. var vertex = new THREE.Vector3();
  19616. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19617. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19618. vertex.z = this.tube * Math.sin( v );
  19619. this.vertices.push( vertex );
  19620. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19621. normals.push( vertex.clone().sub( center ).normalize() );
  19622. }
  19623. }
  19624. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19625. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19626. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19627. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19628. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19629. var d = ( this.tubularSegments + 1 ) * j + i;
  19630. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19631. face.normal.add( normals[ a ] );
  19632. face.normal.add( normals[ b ] );
  19633. face.normal.add( normals[ c ] );
  19634. face.normal.add( normals[ d ] );
  19635. face.normal.normalize();
  19636. this.faces.push( face );
  19637. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19638. }
  19639. }
  19640. this.computeCentroids();
  19641. };
  19642. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19643. /**
  19644. * @author oosmoxiecode
  19645. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19646. */
  19647. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19648. THREE.Geometry.call( this );
  19649. var scope = this;
  19650. this.radius = radius || 100;
  19651. this.tube = tube || 40;
  19652. this.radialSegments = radialSegments || 64;
  19653. this.tubularSegments = tubularSegments || 8;
  19654. this.p = p || 2;
  19655. this.q = q || 3;
  19656. this.heightScale = heightScale || 1;
  19657. this.grid = new Array( this.radialSegments );
  19658. var tang = new THREE.Vector3();
  19659. var n = new THREE.Vector3();
  19660. var bitan = new THREE.Vector3();
  19661. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19662. this.grid[ i ] = new Array( this.tubularSegments );
  19663. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19664. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19665. var v = j / this.tubularSegments * 2 * Math.PI;
  19666. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19667. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19668. var cx, cy;
  19669. tang.subVectors( p2, p1 );
  19670. n.addVectors( p2, p1 );
  19671. bitan.crossVectors( tang, n );
  19672. n.crossVectors( bitan, tang );
  19673. bitan.normalize();
  19674. n.normalize();
  19675. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19676. cy = this.tube * Math.sin( v );
  19677. p1.x += cx * n.x + cy * bitan.x;
  19678. p1.y += cx * n.y + cy * bitan.y;
  19679. p1.z += cx * n.z + cy * bitan.z;
  19680. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19681. }
  19682. }
  19683. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19684. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19685. var ip = ( i + 1 ) % this.radialSegments;
  19686. var jp = ( j + 1 ) % this.tubularSegments;
  19687. var a = this.grid[ i ][ j ];
  19688. var b = this.grid[ ip ][ j ];
  19689. var c = this.grid[ ip ][ jp ];
  19690. var d = this.grid[ i ][ jp ];
  19691. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19692. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19693. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19694. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19695. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19696. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19697. }
  19698. }
  19699. this.computeCentroids();
  19700. this.computeFaceNormals();
  19701. this.computeVertexNormals();
  19702. function vert( x, y, z ) {
  19703. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19704. }
  19705. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19706. var cu = Math.cos( u );
  19707. var cv = Math.cos( v );
  19708. var su = Math.sin( u );
  19709. var quOverP = in_q / in_p * u;
  19710. var cs = Math.cos( quOverP );
  19711. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19712. var ty = radius * ( 2 + cs ) * su * 0.5;
  19713. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19714. return new THREE.Vector3( tx, ty, tz );
  19715. }
  19716. };
  19717. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19718. /**
  19719. * @author WestLangley / https://github.com/WestLangley
  19720. * @author zz85 / https://github.com/zz85
  19721. * @author miningold / https://github.com/miningold
  19722. *
  19723. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19724. *
  19725. * Creates a tube which extrudes along a 3d spline
  19726. *
  19727. * Uses parallel transport frames as described in
  19728. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19729. */
  19730. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed, debug ) {
  19731. THREE.Geometry.call( this );
  19732. this.path = path;
  19733. this.segments = segments || 64;
  19734. this.radius = radius || 1;
  19735. this.radialSegments = radialSegments || 8;
  19736. this.closed = closed || false;
  19737. if ( debug ) this.debug = new THREE.Object3D();
  19738. this.grid = [];
  19739. var scope = this,
  19740. tangent,
  19741. normal,
  19742. binormal,
  19743. numpoints = this.segments + 1,
  19744. x, y, z,
  19745. tx, ty, tz,
  19746. u, v,
  19747. cx, cy,
  19748. pos, pos2 = new THREE.Vector3(),
  19749. i, j,
  19750. ip, jp,
  19751. a, b, c, d,
  19752. uva, uvb, uvc, uvd;
  19753. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19754. tangents = frames.tangents,
  19755. normals = frames.normals,
  19756. binormals = frames.binormals;
  19757. // proxy internals
  19758. this.tangents = tangents;
  19759. this.normals = normals;
  19760. this.binormals = binormals;
  19761. function vert( x, y, z ) {
  19762. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19763. }
  19764. // consruct the grid
  19765. for ( i = 0; i < numpoints; i++ ) {
  19766. this.grid[ i ] = [];
  19767. u = i / ( numpoints - 1 );
  19768. pos = path.getPointAt( u );
  19769. tangent = tangents[ i ];
  19770. normal = normals[ i ];
  19771. binormal = binormals[ i ];
  19772. if ( this.debug ) {
  19773. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19774. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19775. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19776. }
  19777. for ( j = 0; j < this.radialSegments; j++ ) {
  19778. v = j / this.radialSegments * 2 * Math.PI;
  19779. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19780. cy = this.radius * Math.sin( v );
  19781. pos2.copy( pos );
  19782. pos2.x += cx * normal.x + cy * binormal.x;
  19783. pos2.y += cx * normal.y + cy * binormal.y;
  19784. pos2.z += cx * normal.z + cy * binormal.z;
  19785. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19786. }
  19787. }
  19788. // construct the mesh
  19789. for ( i = 0; i < this.segments; i++ ) {
  19790. for ( j = 0; j < this.radialSegments; j++ ) {
  19791. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19792. jp = (j + 1) % this.radialSegments;
  19793. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19794. b = this.grid[ ip ][ j ];
  19795. c = this.grid[ ip ][ jp ];
  19796. d = this.grid[ i ][ jp ];
  19797. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  19798. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  19799. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  19800. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  19801. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19802. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19803. }
  19804. }
  19805. this.computeCentroids();
  19806. this.computeFaceNormals();
  19807. this.computeVertexNormals();
  19808. };
  19809. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19810. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19811. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19812. var tangent = new THREE.Vector3(),
  19813. normal = new THREE.Vector3(),
  19814. binormal = new THREE.Vector3(),
  19815. tangents = [],
  19816. normals = [],
  19817. binormals = [],
  19818. vec = new THREE.Vector3(),
  19819. mat = new THREE.Matrix4(),
  19820. numpoints = segments + 1,
  19821. theta,
  19822. epsilon = 0.0001,
  19823. smallest,
  19824. tx, ty, tz,
  19825. i, u, v;
  19826. // expose internals
  19827. this.tangents = tangents;
  19828. this.normals = normals;
  19829. this.binormals = binormals;
  19830. // compute the tangent vectors for each segment on the path
  19831. for ( i = 0; i < numpoints; i++ ) {
  19832. u = i / ( numpoints - 1 );
  19833. tangents[ i ] = path.getTangentAt( u );
  19834. tangents[ i ].normalize();
  19835. }
  19836. initialNormal3();
  19837. function initialNormal1(lastBinormal) {
  19838. // fixed start binormal. Has dangers of 0 vectors
  19839. normals[ 0 ] = new THREE.Vector3();
  19840. binormals[ 0 ] = new THREE.Vector3();
  19841. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19842. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19843. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19844. }
  19845. function initialNormal2() {
  19846. // This uses the Frenet-Serret formula for deriving binormal
  19847. var t2 = path.getTangentAt( epsilon );
  19848. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19849. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19850. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19851. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19852. }
  19853. function initialNormal3() {
  19854. // select an initial normal vector perpenicular to the first tangent vector,
  19855. // and in the direction of the smallest tangent xyz component
  19856. normals[ 0 ] = new THREE.Vector3();
  19857. binormals[ 0 ] = new THREE.Vector3();
  19858. smallest = Number.MAX_VALUE;
  19859. tx = Math.abs( tangents[ 0 ].x );
  19860. ty = Math.abs( tangents[ 0 ].y );
  19861. tz = Math.abs( tangents[ 0 ].z );
  19862. if ( tx <= smallest ) {
  19863. smallest = tx;
  19864. normal.set( 1, 0, 0 );
  19865. }
  19866. if ( ty <= smallest ) {
  19867. smallest = ty;
  19868. normal.set( 0, 1, 0 );
  19869. }
  19870. if ( tz <= smallest ) {
  19871. normal.set( 0, 0, 1 );
  19872. }
  19873. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19874. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19875. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19876. }
  19877. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19878. for ( i = 1; i < numpoints; i++ ) {
  19879. normals[ i ] = normals[ i-1 ].clone();
  19880. binormals[ i ] = binormals[ i-1 ].clone();
  19881. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19882. if ( vec.length() > epsilon ) {
  19883. vec.normalize();
  19884. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19885. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19886. }
  19887. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19888. }
  19889. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19890. if ( closed ) {
  19891. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19892. theta /= ( numpoints - 1 );
  19893. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19894. theta = -theta;
  19895. }
  19896. for ( i = 1; i < numpoints; i++ ) {
  19897. // twist a little...
  19898. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19899. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19900. }
  19901. }
  19902. };
  19903. /**
  19904. * @author clockworkgeek / https://github.com/clockworkgeek
  19905. * @author timothypratley / https://github.com/timothypratley
  19906. * @author WestLangley / http://github.com/WestLangley
  19907. */
  19908. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19909. THREE.Geometry.call( this );
  19910. radius = radius || 1;
  19911. detail = detail || 0;
  19912. var that = this;
  19913. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19914. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19915. }
  19916. var midpoints = [], p = this.vertices;
  19917. var f = [];
  19918. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19919. var v1 = p[ faces[ i ][ 0 ] ];
  19920. var v2 = p[ faces[ i ][ 1 ] ];
  19921. var v3 = p[ faces[ i ][ 2 ] ];
  19922. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19923. }
  19924. for ( var i = 0, l = f.length; i < l; i ++ ) {
  19925. subdivide(f[ i ], detail);
  19926. }
  19927. // Handle case when face straddles the seam
  19928. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19929. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19930. var x0 = uvs[ 0 ].x;
  19931. var x1 = uvs[ 1 ].x;
  19932. var x2 = uvs[ 2 ].x;
  19933. var max = Math.max( x0, Math.max( x1, x2 ) );
  19934. var min = Math.min( x0, Math.min( x1, x2 ) );
  19935. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19936. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19937. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19938. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19939. }
  19940. }
  19941. // Apply radius
  19942. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19943. this.vertices[ i ].multiplyScalar( radius );
  19944. }
  19945. // Merge vertices
  19946. this.mergeVertices();
  19947. this.computeCentroids();
  19948. this.computeFaceNormals();
  19949. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19950. // Project vector onto sphere's surface
  19951. function prepare( vector ) {
  19952. var vertex = vector.normalize().clone();
  19953. vertex.index = that.vertices.push( vertex ) - 1;
  19954. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19955. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19956. var v = inclination( vector ) / Math.PI + 0.5;
  19957. vertex.uv = new THREE.Vector2( u, 1 - v );
  19958. return vertex;
  19959. }
  19960. // Approximate a curved face with recursively sub-divided triangles.
  19961. function make( v1, v2, v3 ) {
  19962. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19963. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19964. that.faces.push( face );
  19965. var azi = azimuth( face.centroid );
  19966. that.faceVertexUvs[ 0 ].push( [
  19967. correctUV( v1.uv, v1, azi ),
  19968. correctUV( v2.uv, v2, azi ),
  19969. correctUV( v3.uv, v3, azi )
  19970. ] );
  19971. }
  19972. // Analytically subdivide a face to the required detail level.
  19973. function subdivide(face, detail ) {
  19974. var cols = Math.pow(2, detail);
  19975. var cells = Math.pow(4, detail);
  19976. var a = prepare( that.vertices[ face.a ] );
  19977. var b = prepare( that.vertices[ face.b ] );
  19978. var c = prepare( that.vertices[ face.c ] );
  19979. var v = [];
  19980. // Construct all of the vertices for this subdivision.
  19981. for ( var i = 0 ; i <= cols; i ++ ) {
  19982. v[ i ] = [];
  19983. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19984. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19985. var rows = cols - i;
  19986. for ( var j = 0; j <= rows; j ++) {
  19987. if ( j == 0 && i == cols ) {
  19988. v[ i ][ j ] = aj;
  19989. } else {
  19990. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19991. }
  19992. }
  19993. }
  19994. // Construct all of the faces.
  19995. for ( var i = 0; i < cols ; i ++ ) {
  19996. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19997. var k = Math.floor( j / 2 );
  19998. if ( j % 2 == 0 ) {
  19999. make(
  20000. v[ i ][ k + 1],
  20001. v[ i + 1 ][ k ],
  20002. v[ i ][ k ]
  20003. );
  20004. } else {
  20005. make(
  20006. v[ i ][ k + 1 ],
  20007. v[ i + 1][ k + 1],
  20008. v[ i + 1 ][ k ]
  20009. );
  20010. }
  20011. }
  20012. }
  20013. }
  20014. // Angle around the Y axis, counter-clockwise when looking from above.
  20015. function azimuth( vector ) {
  20016. return Math.atan2( vector.z, -vector.x );
  20017. }
  20018. // Angle above the XZ plane.
  20019. function inclination( vector ) {
  20020. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20021. }
  20022. // Texture fixing helper. Spheres have some odd behaviours.
  20023. function correctUV( uv, vector, azimuth ) {
  20024. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20025. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20026. return uv.clone();
  20027. }
  20028. };
  20029. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20030. /**
  20031. * @author timothypratley / https://github.com/timothypratley
  20032. */
  20033. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20034. this.radius = radius;
  20035. this.detail = detail;
  20036. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20037. var vertices = [
  20038. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20039. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20040. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20041. ];
  20042. var faces = [
  20043. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20044. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20045. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20046. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20047. ];
  20048. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20049. };
  20050. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20051. /**
  20052. * @author timothypratley / https://github.com/timothypratley
  20053. */
  20054. THREE.OctahedronGeometry = function ( radius, detail ) {
  20055. var vertices = [
  20056. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20057. ];
  20058. var faces = [
  20059. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20060. ];
  20061. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20062. };
  20063. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20064. /**
  20065. * @author timothypratley / https://github.com/timothypratley
  20066. */
  20067. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20068. var vertices = [
  20069. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20070. ];
  20071. var faces = [
  20072. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20073. ];
  20074. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20075. };
  20076. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20077. /**
  20078. * @author zz85 / https://github.com/zz85
  20079. * Parametric Surfaces Geometry
  20080. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20081. *
  20082. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  20083. *
  20084. */
  20085. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  20086. THREE.Geometry.call( this );
  20087. var verts = this.vertices;
  20088. var faces = this.faces;
  20089. var uvs = this.faceVertexUvs[ 0 ];
  20090. useTris = (useTris === undefined) ? false : useTris;
  20091. var i, il, j, p;
  20092. var u, v;
  20093. var stackCount = stacks + 1;
  20094. var sliceCount = slices + 1;
  20095. for ( i = 0; i <= stacks; i ++ ) {
  20096. v = i / stacks;
  20097. for ( j = 0; j <= slices; j ++ ) {
  20098. u = j / slices;
  20099. p = func( u, v );
  20100. verts.push( p );
  20101. }
  20102. }
  20103. var a, b, c, d;
  20104. var uva, uvb, uvc, uvd;
  20105. for ( i = 0; i < stacks; i ++ ) {
  20106. for ( j = 0; j < slices; j ++ ) {
  20107. a = i * sliceCount + j;
  20108. b = i * sliceCount + j + 1;
  20109. c = (i + 1) * sliceCount + j;
  20110. d = (i + 1) * sliceCount + j + 1;
  20111. uva = new THREE.Vector2( j / slices, i / stacks );
  20112. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20113. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20114. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20115. if ( useTris ) {
  20116. faces.push( new THREE.Face3( a, b, c ) );
  20117. faces.push( new THREE.Face3( b, d, c ) );
  20118. uvs.push( [ uva, uvb, uvc ] );
  20119. uvs.push( [ uvb, uvd, uvc ] );
  20120. } else {
  20121. faces.push( new THREE.Face4( a, b, d, c ) );
  20122. uvs.push( [ uva, uvb, uvd, uvc ] );
  20123. }
  20124. }
  20125. }
  20126. // console.log(this);
  20127. // magic bullet
  20128. // var diff = this.mergeVertices();
  20129. // console.log('removed ', diff, ' vertices by merging');
  20130. this.computeCentroids();
  20131. this.computeFaceNormals();
  20132. this.computeVertexNormals();
  20133. };
  20134. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20135. /**
  20136. * @author qiao / https://github.com/qiao
  20137. * @fileoverview This is a convex hull generator using the incremental method.
  20138. * The complexity is O(n^2) where n is the number of vertices.
  20139. * O(nlogn) algorithms do exist, but they are much more complicated.
  20140. *
  20141. * Benchmark:
  20142. *
  20143. * Platform: CPU: P7350 @2.00GHz Engine: V8
  20144. *
  20145. * Num Vertices Time(ms)
  20146. *
  20147. * 10 1
  20148. * 20 3
  20149. * 30 19
  20150. * 40 48
  20151. * 50 107
  20152. */
  20153. THREE.ConvexGeometry = function( vertices ) {
  20154. THREE.Geometry.call( this );
  20155. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  20156. for ( var i = 3; i < vertices.length; i++ ) {
  20157. addPoint( i );
  20158. }
  20159. function addPoint( vertexId ) {
  20160. var vertex = vertices[ vertexId ].clone();
  20161. var mag = vertex.length();
  20162. vertex.x += mag * randomOffset();
  20163. vertex.y += mag * randomOffset();
  20164. vertex.z += mag * randomOffset();
  20165. var hole = [];
  20166. for ( var f = 0; f < faces.length; ) {
  20167. var face = faces[ f ];
  20168. // for each face, if the vertex can see it,
  20169. // then we try to add the face's edges into the hole.
  20170. if ( visible( face, vertex ) ) {
  20171. for ( var e = 0; e < 3; e++ ) {
  20172. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  20173. var boundary = true;
  20174. // remove duplicated edges.
  20175. for ( var h = 0; h < hole.length; h++ ) {
  20176. if ( equalEdge( hole[ h ], edge ) ) {
  20177. hole[ h ] = hole[ hole.length - 1 ];
  20178. hole.pop();
  20179. boundary = false;
  20180. break;
  20181. }
  20182. }
  20183. if ( boundary ) {
  20184. hole.push( edge );
  20185. }
  20186. }
  20187. // remove faces[ f ]
  20188. faces[ f ] = faces[ faces.length - 1 ];
  20189. faces.pop();
  20190. } else { // not visible
  20191. f++;
  20192. }
  20193. }
  20194. // construct the new faces formed by the edges of the hole and the vertex
  20195. for ( var h = 0; h < hole.length; h++ ) {
  20196. faces.push( [
  20197. hole[ h ][ 0 ],
  20198. hole[ h ][ 1 ],
  20199. vertexId
  20200. ] );
  20201. }
  20202. }
  20203. /**
  20204. * Whether the face is visible from the vertex
  20205. */
  20206. function visible( face, vertex ) {
  20207. var va = vertices[ face[ 0 ] ];
  20208. var vb = vertices[ face[ 1 ] ];
  20209. var vc = vertices[ face[ 2 ] ];
  20210. var n = normal( va, vb, vc );
  20211. // distance from face to origin
  20212. var dist = n.dot( va );
  20213. return n.dot( vertex ) >= dist;
  20214. }
  20215. /**
  20216. * Face normal
  20217. */
  20218. function normal( va, vb, vc ) {
  20219. var cb = new THREE.Vector3();
  20220. var ab = new THREE.Vector3();
  20221. cb.subVectors( vc, vb );
  20222. ab.subVectors( va, vb );
  20223. cb.cross( ab );
  20224. cb.normalize();
  20225. return cb;
  20226. }
  20227. /**
  20228. * Detect whether two edges are equal.
  20229. * Note that when constructing the convex hull, two same edges can only
  20230. * be of the negative direction.
  20231. */
  20232. function equalEdge( ea, eb ) {
  20233. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20234. }
  20235. /**
  20236. * Create a random offset between -1e-6 and 1e-6.
  20237. */
  20238. function randomOffset() {
  20239. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20240. }
  20241. /**
  20242. * XXX: Not sure if this is the correct approach. Need someone to review.
  20243. */
  20244. function vertexUv( vertex ) {
  20245. var mag = vertex.length();
  20246. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  20247. }
  20248. // Push vertices into `this.vertices`, skipping those inside the hull
  20249. var id = 0;
  20250. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20251. for ( var i = 0; i < faces.length; i++ ) {
  20252. var face = faces[ i ];
  20253. for ( var j = 0; j < 3; j++ ) {
  20254. if ( newId[ face[ j ] ] === undefined ) {
  20255. newId[ face[ j ] ] = id++;
  20256. this.vertices.push( vertices[ face[ j ] ] );
  20257. }
  20258. face[ j ] = newId[ face[ j ] ];
  20259. }
  20260. }
  20261. // Convert faces into instances of THREE.Face3
  20262. for ( var i = 0; i < faces.length; i++ ) {
  20263. this.faces.push( new THREE.Face3(
  20264. faces[ i ][ 0 ],
  20265. faces[ i ][ 1 ],
  20266. faces[ i ][ 2 ]
  20267. ) );
  20268. }
  20269. // Compute UVs
  20270. for ( var i = 0; i < this.faces.length; i++ ) {
  20271. var face = this.faces[ i ];
  20272. this.faceVertexUvs[ 0 ].push( [
  20273. vertexUv( this.vertices[ face.a ] ),
  20274. vertexUv( this.vertices[ face.b ] ),
  20275. vertexUv( this.vertices[ face.c ])
  20276. ] );
  20277. }
  20278. this.computeCentroids();
  20279. this.computeFaceNormals();
  20280. this.computeVertexNormals();
  20281. };
  20282. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20283. /**
  20284. * @author sroucheray / http://sroucheray.org/
  20285. * @author mrdoob / http://mrdoob.com/
  20286. */
  20287. THREE.AxisHelper = function ( size ) {
  20288. size = size || 1;
  20289. var geometry = new THREE.Geometry();
  20290. geometry.vertices.push(
  20291. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20292. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20293. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20294. );
  20295. geometry.colors.push(
  20296. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20297. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20298. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20299. );
  20300. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20301. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20302. };
  20303. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20304. /**
  20305. * @author WestLangley / http://github.com/WestLangley
  20306. * @author zz85 / http://github.com/zz85
  20307. * @author bhouston / http://exocortex.com
  20308. *
  20309. * Creates an arrow for visualizing directions
  20310. *
  20311. * Parameters:
  20312. * dir - Vector3
  20313. * origin - Vector3
  20314. * length - Number
  20315. * hex - color in hex value
  20316. */
  20317. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20318. // dir is assumed to be normalized
  20319. THREE.Object3D.call( this );
  20320. if ( hex === undefined ) hex = 0xffff00;
  20321. if ( length === undefined ) length = 1;
  20322. this.position = origin;
  20323. this.useQuaternion = true;
  20324. var lineGeometry = new THREE.Geometry();
  20325. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20326. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20327. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20328. this.line.matrixAutoUpdate = false;
  20329. this.add( this.line );
  20330. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20331. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, 0.875, 0 ) );
  20332. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20333. this.cone.matrixAutoUpdate = false;
  20334. this.add( this.cone );
  20335. this.setDirection( dir );
  20336. this.setLength( length );
  20337. };
  20338. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20339. THREE.ArrowHelper.prototype.setDirection = function () {
  20340. var axis = new THREE.Vector3();
  20341. var radians;
  20342. return function ( dir ) {
  20343. // dir is assumed to be normalized
  20344. if ( dir.y > 0.999 ) {
  20345. this.quaternion.set( 0, 0, 0, 1 );
  20346. } else if ( dir.y < - 0.999 ) {
  20347. this.quaternion.set( 1, 0, 0, 0 );
  20348. } else {
  20349. axis.set( dir.z, 0, - dir.x ).normalize();
  20350. radians = Math.acos( dir.y );
  20351. this.quaternion.setFromAxisAngle( axis, radians );
  20352. }
  20353. };
  20354. }();
  20355. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20356. this.scale.set( length, length, length );
  20357. };
  20358. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20359. this.line.material.color.setHex( hex );
  20360. this.cone.material.color.setHex( hex );
  20361. };
  20362. /**
  20363. * @author mrdoob / http://mrdoob.com/
  20364. */
  20365. THREE.BoxHelper = function ( object ) {
  20366. // 5____4
  20367. // 1/___0/|
  20368. // | 6__|_7
  20369. // 2/___3/
  20370. var vertices = [
  20371. new THREE.Vector3( 1, 1, 1 ),
  20372. new THREE.Vector3( - 1, 1, 1 ),
  20373. new THREE.Vector3( - 1, - 1, 1 ),
  20374. new THREE.Vector3( 1, - 1, 1 ),
  20375. new THREE.Vector3( 1, 1, - 1 ),
  20376. new THREE.Vector3( - 1, 1, - 1 ),
  20377. new THREE.Vector3( - 1, - 1, - 1 ),
  20378. new THREE.Vector3( 1, - 1, - 1 )
  20379. ];
  20380. this.vertices = vertices;
  20381. // TODO: Wouldn't be nice if Line had .segments?
  20382. var geometry = new THREE.Geometry();
  20383. geometry.vertices.push(
  20384. vertices[ 0 ], vertices[ 1 ],
  20385. vertices[ 1 ], vertices[ 2 ],
  20386. vertices[ 2 ], vertices[ 3 ],
  20387. vertices[ 3 ], vertices[ 0 ],
  20388. vertices[ 4 ], vertices[ 5 ],
  20389. vertices[ 5 ], vertices[ 6 ],
  20390. vertices[ 6 ], vertices[ 7 ],
  20391. vertices[ 7 ], vertices[ 4 ],
  20392. vertices[ 0 ], vertices[ 4 ],
  20393. vertices[ 1 ], vertices[ 5 ],
  20394. vertices[ 2 ], vertices[ 6 ],
  20395. vertices[ 3 ], vertices[ 7 ]
  20396. );
  20397. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20398. if ( object !== undefined ) {
  20399. this.update( object );
  20400. }
  20401. };
  20402. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20403. THREE.BoxHelper.prototype.update = function ( object ) {
  20404. var geometry = object.geometry;
  20405. if ( geometry.boundingBox === null ) {
  20406. geometry.computeBoundingBox();
  20407. }
  20408. var min = geometry.boundingBox.min;
  20409. var max = geometry.boundingBox.max;
  20410. var vertices = this.vertices;
  20411. vertices[ 0 ].set( max.x, max.y, max.z );
  20412. vertices[ 1 ].set( min.x, max.y, max.z );
  20413. vertices[ 2 ].set( min.x, min.y, max.z );
  20414. vertices[ 3 ].set( max.x, min.y, max.z );
  20415. vertices[ 4 ].set( max.x, max.y, min.z );
  20416. vertices[ 5 ].set( min.x, max.y, min.z );
  20417. vertices[ 6 ].set( min.x, min.y, min.z );
  20418. vertices[ 7 ].set( max.x, min.y, min.z );
  20419. this.geometry.computeBoundingSphere();
  20420. this.geometry.verticesNeedUpdate = true;
  20421. this.matrixAutoUpdate = false;
  20422. this.matrixWorld = object.matrixWorld;
  20423. };
  20424. /**
  20425. * @author alteredq / http://alteredqualia.com/
  20426. *
  20427. * - shows frustum, line of sight and up of the camera
  20428. * - suitable for fast updates
  20429. * - based on frustum visualization in lightgl.js shadowmap example
  20430. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20431. */
  20432. THREE.CameraHelper = function ( camera ) {
  20433. THREE.Line.call( this );
  20434. var geometry = new THREE.Geometry();
  20435. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20436. var pointMap = {};
  20437. // colors
  20438. var hexFrustum = 0xffaa00;
  20439. var hexCone = 0xff0000;
  20440. var hexUp = 0x00aaff;
  20441. var hexTarget = 0xffffff;
  20442. var hexCross = 0x333333;
  20443. // near
  20444. addLine( "n1", "n2", hexFrustum );
  20445. addLine( "n2", "n4", hexFrustum );
  20446. addLine( "n4", "n3", hexFrustum );
  20447. addLine( "n3", "n1", hexFrustum );
  20448. // far
  20449. addLine( "f1", "f2", hexFrustum );
  20450. addLine( "f2", "f4", hexFrustum );
  20451. addLine( "f4", "f3", hexFrustum );
  20452. addLine( "f3", "f1", hexFrustum );
  20453. // sides
  20454. addLine( "n1", "f1", hexFrustum );
  20455. addLine( "n2", "f2", hexFrustum );
  20456. addLine( "n3", "f3", hexFrustum );
  20457. addLine( "n4", "f4", hexFrustum );
  20458. // cone
  20459. addLine( "p", "n1", hexCone );
  20460. addLine( "p", "n2", hexCone );
  20461. addLine( "p", "n3", hexCone );
  20462. addLine( "p", "n4", hexCone );
  20463. // up
  20464. addLine( "u1", "u2", hexUp );
  20465. addLine( "u2", "u3", hexUp );
  20466. addLine( "u3", "u1", hexUp );
  20467. // target
  20468. addLine( "c", "t", hexTarget );
  20469. addLine( "p", "c", hexCross );
  20470. // cross
  20471. addLine( "cn1", "cn2", hexCross );
  20472. addLine( "cn3", "cn4", hexCross );
  20473. addLine( "cf1", "cf2", hexCross );
  20474. addLine( "cf3", "cf4", hexCross );
  20475. function addLine( a, b, hex ) {
  20476. addPoint( a, hex );
  20477. addPoint( b, hex );
  20478. }
  20479. function addPoint( id, hex ) {
  20480. geometry.vertices.push( new THREE.Vector3() );
  20481. geometry.colors.push( new THREE.Color( hex ) );
  20482. if ( pointMap[ id ] === undefined ) {
  20483. pointMap[ id ] = [];
  20484. }
  20485. pointMap[ id ].push( geometry.vertices.length - 1 );
  20486. }
  20487. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20488. this.camera = camera;
  20489. this.matrixWorld = camera.matrixWorld;
  20490. this.matrixAutoUpdate = false;
  20491. this.pointMap = pointMap;
  20492. this.update();
  20493. };
  20494. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20495. THREE.CameraHelper.prototype.update = function () {
  20496. var vector = new THREE.Vector3();
  20497. var camera = new THREE.Camera();
  20498. var projector = new THREE.Projector();
  20499. return function () {
  20500. var scope = this;
  20501. var w = 1, h = 1;
  20502. // we need just camera projection matrix
  20503. // world matrix must be identity
  20504. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20505. // center / target
  20506. setPoint( "c", 0, 0, -1 );
  20507. setPoint( "t", 0, 0, 1 );
  20508. // near
  20509. setPoint( "n1", -w, -h, -1 );
  20510. setPoint( "n2", w, -h, -1 );
  20511. setPoint( "n3", -w, h, -1 );
  20512. setPoint( "n4", w, h, -1 );
  20513. // far
  20514. setPoint( "f1", -w, -h, 1 );
  20515. setPoint( "f2", w, -h, 1 );
  20516. setPoint( "f3", -w, h, 1 );
  20517. setPoint( "f4", w, h, 1 );
  20518. // up
  20519. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20520. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20521. setPoint( "u3", 0, h * 2, -1 );
  20522. // cross
  20523. setPoint( "cf1", -w, 0, 1 );
  20524. setPoint( "cf2", w, 0, 1 );
  20525. setPoint( "cf3", 0, -h, 1 );
  20526. setPoint( "cf4", 0, h, 1 );
  20527. setPoint( "cn1", -w, 0, -1 );
  20528. setPoint( "cn2", w, 0, -1 );
  20529. setPoint( "cn3", 0, -h, -1 );
  20530. setPoint( "cn4", 0, h, -1 );
  20531. function setPoint( point, x, y, z ) {
  20532. vector.set( x, y, z );
  20533. projector.unprojectVector( vector, camera );
  20534. var points = scope.pointMap[ point ];
  20535. if ( points !== undefined ) {
  20536. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20537. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20538. }
  20539. }
  20540. }
  20541. this.geometry.verticesNeedUpdate = true;
  20542. };
  20543. }();
  20544. /**
  20545. * @author alteredq / http://alteredqualia.com/
  20546. * @author mrdoob / http://mrdoob.com/
  20547. */
  20548. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  20549. THREE.Object3D.call( this );
  20550. this.matrixAutoUpdate = false;
  20551. this.light = light;
  20552. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20553. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20554. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20555. this.lightSphere = new THREE.Mesh( geometry, material );
  20556. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20557. this.lightSphere.matrixAutoUpdate = false;
  20558. this.add( this.lightSphere );
  20559. /*
  20560. this.targetSphere = new THREE.Mesh( geometry, material );
  20561. this.targetSphere.position = this.light.target.position;
  20562. this.add( this.targetSphere );
  20563. */
  20564. geometry = new THREE.Geometry();
  20565. geometry.vertices.push( this.light.position );
  20566. geometry.vertices.push( this.light.target.position );
  20567. geometry.computeLineDistances();
  20568. material = new THREE.LineDashedMaterial( { dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20569. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20570. this.targetLine = new THREE.Line( geometry, material );
  20571. this.add( this.targetLine );
  20572. }
  20573. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20574. THREE.DirectionalLightHelper.prototype.update = function () {
  20575. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20576. this.targetLine.geometry.computeLineDistances();
  20577. this.targetLine.geometry.verticesNeedUpdate = true;
  20578. this.targetLine.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20579. };
  20580. /**
  20581. * @author mrdoob / http://mrdoob.com/
  20582. * @author WestLangley / http://github.com/WestLangley
  20583. */
  20584. THREE.FaceNormalsHelper = function ( object, size, hex ) {
  20585. this.object = object;
  20586. this.size = size || 1;
  20587. var color = hex || 0x0000ff;
  20588. var geometry = new THREE.Geometry();
  20589. var faces = this.object.geometry.faces;
  20590. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20591. geometry.vertices.push( new THREE.Vector3() );
  20592. geometry.vertices.push( new THREE.Vector3() );
  20593. }
  20594. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20595. this.matrixAutoUpdate = false;
  20596. this.normalMatrix = new THREE.Matrix3();
  20597. this.update();
  20598. };
  20599. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20600. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  20601. var v1 = new THREE.Vector3();
  20602. return function( object ) {
  20603. this.object.updateMatrixWorld( true );
  20604. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20605. var vertices = this.geometry.vertices;
  20606. var faces = this.object.geometry.faces;
  20607. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20608. var face = faces[ i ];
  20609. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20610. var idx = 2 * i;
  20611. vertices[ idx ].copy( face.centroid ).applyMatrix4( this.object.matrixWorld );
  20612. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  20613. }
  20614. this.geometry.verticesNeedUpdate = true;
  20615. return this;
  20616. }
  20617. }());
  20618. /**
  20619. * @author mrdoob / http://mrdoob.com/
  20620. */
  20621. THREE.GridHelper = function ( size, step ) {
  20622. var geometry = new THREE.Geometry();
  20623. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20624. var color1 = new THREE.Color( 0x444444 ), color2 = new THREE.Color( 0x888888 );
  20625. for ( var i = - size; i <= size; i += step ) {
  20626. geometry.vertices.push(
  20627. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20628. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20629. );
  20630. var color = i === 0 ? color1 : color2;
  20631. geometry.colors.push( color, color, color, color );
  20632. }
  20633. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20634. };
  20635. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20636. /**
  20637. * @author alteredq / http://alteredqualia.com/
  20638. * @author mrdoob / http://mrdoob.com/
  20639. */
  20640. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20641. THREE.Object3D.call( this );
  20642. this.light = light;
  20643. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20644. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20645. for ( var i = 0, il = 8; i < il; i ++ ) {
  20646. geometry.faces[ i ].materialIndex = i < 4 ? 0 : 1;
  20647. }
  20648. var materialSky = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20649. materialSky.color.copy( light.color ).multiplyScalar( light.intensity );
  20650. var materialGround = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20651. materialGround.color.copy( light.groundColor ).multiplyScalar( light.intensity );
  20652. this.lightSphere = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( [ materialSky, materialGround ] ) );
  20653. this.lightSphere.position = light.position;
  20654. this.lightSphere.lookAt( new THREE.Vector3() );
  20655. this.add( this.lightSphere );
  20656. };
  20657. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20658. THREE.HemisphereLightHelper.prototype.update = function () {
  20659. this.lightSphere.lookAt( new THREE.Vector3() );
  20660. this.lightSphere.material.materials[ 0 ].color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20661. this.lightSphere.material.materials[ 1 ].color.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20662. };
  20663. /**
  20664. * @author alteredq / http://alteredqualia.com/
  20665. * @author mrdoob / http://mrdoob.com/
  20666. */
  20667. THREE.PointLightHelper = function ( light, sphereSize ) {
  20668. THREE.Object3D.call( this );
  20669. this.matrixAutoUpdate = false;
  20670. this.light = light;
  20671. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20672. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20673. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20674. this.lightSphere = new THREE.Mesh( geometry, material );
  20675. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20676. this.lightSphere.matrixAutoUpdate = false;
  20677. this.add( this.lightSphere );
  20678. /*
  20679. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20680. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20681. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20682. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20683. var d = light.distance;
  20684. if ( d === 0.0 ) {
  20685. this.lightDistance.visible = false;
  20686. } else {
  20687. this.lightDistance.scale.set( d, d, d );
  20688. }
  20689. this.add( this.lightDistance );
  20690. */
  20691. };
  20692. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20693. THREE.PointLightHelper.prototype.update = function () {
  20694. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20695. /*
  20696. this.lightDistance.material.color.copy( this.color );
  20697. var d = this.light.distance;
  20698. if ( d === 0.0 ) {
  20699. this.lightDistance.visible = false;
  20700. } else {
  20701. this.lightDistance.visible = true;
  20702. this.lightDistance.scale.set( d, d, d );
  20703. }
  20704. */
  20705. };
  20706. /**
  20707. * @author alteredq / http://alteredqualia.com/
  20708. * @author mrdoob / http://mrdoob.com/
  20709. * @author WestLangley / http://github.com/WestLangley
  20710. */
  20711. THREE.SpotLightHelper = function ( light ) {
  20712. // spotlight helper must be a child of the scene
  20713. this.light = light;
  20714. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20715. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  20716. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20717. var material = new THREE.MeshBasicMaterial( { wireframe: true, opacity: 0.3, transparent: true } );
  20718. THREE.Mesh.call( this, geometry, material );
  20719. this.update();
  20720. };
  20721. THREE.SpotLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20722. THREE.SpotLightHelper.prototype.update = ( function () {
  20723. var targetPosition = new THREE.Vector3();
  20724. return function() {
  20725. var coneLength = this.light.distance ? this.light.distance : 10000;
  20726. var coneWidth = coneLength * Math.tan( this.light.angle );
  20727. this.scale.set( coneWidth, coneWidth, coneLength );
  20728. this.light.updateMatrixWorld( true );
  20729. this.position.getPositionFromMatrix( this.light.matrixWorld );
  20730. this.light.target.updateMatrixWorld( true );
  20731. targetPosition.getPositionFromMatrix( this.light.target.matrixWorld );
  20732. this.lookAt( targetPosition );
  20733. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20734. }
  20735. }());
  20736. /**
  20737. * @author mrdoob / http://mrdoob.com/
  20738. * @author WestLangley / http://github.com/WestLangley
  20739. */
  20740. THREE.VertexNormalsHelper = function ( object, size, hex ) {
  20741. this.object = object;
  20742. this.size = size || 1;
  20743. var color = hex || 0xff0000;
  20744. var geometry = new THREE.Geometry();
  20745. var vertices = object.geometry.vertices;
  20746. var faces = object.geometry.faces;
  20747. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20748. var face = faces[ i ];
  20749. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20750. geometry.vertices.push( new THREE.Vector3() );
  20751. geometry.vertices.push( new THREE.Vector3() );
  20752. }
  20753. }
  20754. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20755. this.matrixAutoUpdate = false;
  20756. this.normalMatrix = new THREE.Matrix3();
  20757. this.update();
  20758. };
  20759. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20760. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20761. var v1 = new THREE.Vector3();
  20762. return function( object ) {
  20763. var keys = [ 'a', 'b', 'c', 'd' ];
  20764. this.object.updateMatrixWorld( true );
  20765. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20766. var vertices = this.geometry.vertices;
  20767. var verts = this.object.geometry.vertices;
  20768. var faces = this.object.geometry.faces;
  20769. var idx = 0;
  20770. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20771. var face = faces[ i ];
  20772. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20773. var vertexId = face[ keys[ j ] ];
  20774. var vertex = verts[ vertexId ];
  20775. var normal = face.vertexNormals[ j ];
  20776. vertices[ idx ].copy( vertex ).applyMatrix4( this.object.matrixWorld );
  20777. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20778. v1.add( vertices[ idx ] );
  20779. idx = idx + 1;
  20780. vertices[ idx ].copy( v1 );
  20781. idx = idx + 1;
  20782. }
  20783. }
  20784. this.geometry.verticesNeedUpdate = true;
  20785. return this;
  20786. }
  20787. }());
  20788. /**
  20789. * @author mrdoob / http://mrdoob.com/
  20790. */
  20791. THREE.WireframeHelper = function ( object ) {
  20792. var edge = [ 0, 0 ], hash = {};
  20793. var sortFunction = function ( a, b ) { return a - b };
  20794. var keys = [ 'a', 'b', 'c', 'd' ];
  20795. var geometry = new THREE.Geometry();
  20796. var vertices = object.geometry.vertices;
  20797. var faces = object.geometry.faces;
  20798. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20799. var face = faces[ i ];
  20800. var length = face instanceof THREE.Face4 ? 4 : 3;
  20801. for ( var j = 0; j < length; j ++ ) {
  20802. edge[ 0 ] = face[ keys[ j ] ];
  20803. edge[ 1 ] = face[ keys[ ( j + 1 ) % length ] ];
  20804. edge.sort( sortFunction );
  20805. var key = edge.toString();
  20806. if ( hash[ key ] === undefined ) {
  20807. geometry.vertices.push( vertices[ edge[ 0 ] ] );
  20808. geometry.vertices.push( vertices[ edge[ 1 ] ] );
  20809. hash[ key ] = true;
  20810. }
  20811. }
  20812. }
  20813. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffffff } ), THREE.LinePieces );
  20814. this.matrixAutoUpdate = false;
  20815. this.matrixWorld = object.matrixWorld;
  20816. };
  20817. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  20818. /**
  20819. * @author alteredq / http://alteredqualia.com/
  20820. */
  20821. THREE.ImmediateRenderObject = function () {
  20822. THREE.Object3D.call( this );
  20823. this.render = function ( renderCallback ) { };
  20824. };
  20825. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20826. /**
  20827. * @author mikael emtinger / http://gomo.se/
  20828. * @author alteredq / http://alteredqualia.com/
  20829. */
  20830. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20831. THREE.Object3D.call( this );
  20832. this.lensFlares = [];
  20833. this.positionScreen = new THREE.Vector3();
  20834. this.customUpdateCallback = undefined;
  20835. if( texture !== undefined ) {
  20836. this.add( texture, size, distance, blending, color );
  20837. }
  20838. };
  20839. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20840. /*
  20841. * Add: adds another flare
  20842. */
  20843. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20844. if( size === undefined ) size = -1;
  20845. if( distance === undefined ) distance = 0;
  20846. if( opacity === undefined ) opacity = 1;
  20847. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20848. if( blending === undefined ) blending = THREE.NormalBlending;
  20849. distance = Math.min( distance, Math.max( 0, distance ) );
  20850. this.lensFlares.push( { texture: texture, // THREE.Texture
  20851. size: size, // size in pixels (-1 = use texture.width)
  20852. distance: distance, // distance (0-1) from light source (0=at light source)
  20853. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20854. scale: 1, // scale
  20855. rotation: 1, // rotation
  20856. opacity: opacity, // opacity
  20857. color: color, // color
  20858. blending: blending } ); // blending
  20859. };
  20860. /*
  20861. * Update lens flares update positions on all flares based on the screen position
  20862. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20863. */
  20864. THREE.LensFlare.prototype.updateLensFlares = function () {
  20865. var f, fl = this.lensFlares.length;
  20866. var flare;
  20867. var vecX = -this.positionScreen.x * 2;
  20868. var vecY = -this.positionScreen.y * 2;
  20869. for( f = 0; f < fl; f ++ ) {
  20870. flare = this.lensFlares[ f ];
  20871. flare.x = this.positionScreen.x + vecX * flare.distance;
  20872. flare.y = this.positionScreen.y + vecY * flare.distance;
  20873. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20874. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20875. }
  20876. };
  20877. /**
  20878. * @author alteredq / http://alteredqualia.com/
  20879. */
  20880. THREE.MorphBlendMesh = function( geometry, material ) {
  20881. THREE.Mesh.call( this, geometry, material );
  20882. this.animationsMap = {};
  20883. this.animationsList = [];
  20884. // prepare default animation
  20885. // (all frames played together in 1 second)
  20886. var numFrames = this.geometry.morphTargets.length;
  20887. var name = "__default";
  20888. var startFrame = 0;
  20889. var endFrame = numFrames - 1;
  20890. var fps = numFrames / 1;
  20891. this.createAnimation( name, startFrame, endFrame, fps );
  20892. this.setAnimationWeight( name, 1 );
  20893. };
  20894. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20895. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20896. var animation = {
  20897. startFrame: start,
  20898. endFrame: end,
  20899. length: end - start + 1,
  20900. fps: fps,
  20901. duration: ( end - start ) / fps,
  20902. lastFrame: 0,
  20903. currentFrame: 0,
  20904. active: false,
  20905. time: 0,
  20906. direction: 1,
  20907. weight: 1,
  20908. directionBackwards: false,
  20909. mirroredLoop: false
  20910. };
  20911. this.animationsMap[ name ] = animation;
  20912. this.animationsList.push( animation );
  20913. };
  20914. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20915. var pattern = /([a-z]+)(\d+)/;
  20916. var firstAnimation, frameRanges = {};
  20917. var geometry = this.geometry;
  20918. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20919. var morph = geometry.morphTargets[ i ];
  20920. var chunks = morph.name.match( pattern );
  20921. if ( chunks && chunks.length > 1 ) {
  20922. var name = chunks[ 1 ];
  20923. var num = chunks[ 2 ];
  20924. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20925. var range = frameRanges[ name ];
  20926. if ( i < range.start ) range.start = i;
  20927. if ( i > range.end ) range.end = i;
  20928. if ( ! firstAnimation ) firstAnimation = name;
  20929. }
  20930. }
  20931. for ( var name in frameRanges ) {
  20932. var range = frameRanges[ name ];
  20933. this.createAnimation( name, range.start, range.end, fps );
  20934. }
  20935. this.firstAnimation = firstAnimation;
  20936. };
  20937. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20938. var animation = this.animationsMap[ name ];
  20939. if ( animation ) {
  20940. animation.direction = 1;
  20941. animation.directionBackwards = false;
  20942. }
  20943. };
  20944. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20945. var animation = this.animationsMap[ name ];
  20946. if ( animation ) {
  20947. animation.direction = -1;
  20948. animation.directionBackwards = true;
  20949. }
  20950. };
  20951. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20952. var animation = this.animationsMap[ name ];
  20953. if ( animation ) {
  20954. animation.fps = fps;
  20955. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20956. }
  20957. };
  20958. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20959. var animation = this.animationsMap[ name ];
  20960. if ( animation ) {
  20961. animation.duration = duration;
  20962. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20963. }
  20964. };
  20965. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20966. var animation = this.animationsMap[ name ];
  20967. if ( animation ) {
  20968. animation.weight = weight;
  20969. }
  20970. };
  20971. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20972. var animation = this.animationsMap[ name ];
  20973. if ( animation ) {
  20974. animation.time = time;
  20975. }
  20976. };
  20977. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20978. var time = 0;
  20979. var animation = this.animationsMap[ name ];
  20980. if ( animation ) {
  20981. time = animation.time;
  20982. }
  20983. return time;
  20984. };
  20985. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20986. var duration = -1;
  20987. var animation = this.animationsMap[ name ];
  20988. if ( animation ) {
  20989. duration = animation.duration;
  20990. }
  20991. return duration;
  20992. };
  20993. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20994. var animation = this.animationsMap[ name ];
  20995. if ( animation ) {
  20996. animation.time = 0;
  20997. animation.active = true;
  20998. } else {
  20999. console.warn( "animation[" + name + "] undefined" );
  21000. }
  21001. };
  21002. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21003. var animation = this.animationsMap[ name ];
  21004. if ( animation ) {
  21005. animation.active = false;
  21006. }
  21007. };
  21008. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21009. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21010. var animation = this.animationsList[ i ];
  21011. if ( ! animation.active ) continue;
  21012. var frameTime = animation.duration / animation.length;
  21013. animation.time += animation.direction * delta;
  21014. if ( animation.mirroredLoop ) {
  21015. if ( animation.time > animation.duration || animation.time < 0 ) {
  21016. animation.direction *= -1;
  21017. if ( animation.time > animation.duration ) {
  21018. animation.time = animation.duration;
  21019. animation.directionBackwards = true;
  21020. }
  21021. if ( animation.time < 0 ) {
  21022. animation.time = 0;
  21023. animation.directionBackwards = false;
  21024. }
  21025. }
  21026. } else {
  21027. animation.time = animation.time % animation.duration;
  21028. if ( animation.time < 0 ) animation.time += animation.duration;
  21029. }
  21030. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21031. var weight = animation.weight;
  21032. if ( keyframe !== animation.currentFrame ) {
  21033. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21034. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21035. this.morphTargetInfluences[ keyframe ] = 0;
  21036. animation.lastFrame = animation.currentFrame;
  21037. animation.currentFrame = keyframe;
  21038. }
  21039. var mix = ( animation.time % frameTime ) / frameTime;
  21040. if ( animation.directionBackwards ) mix = 1 - mix;
  21041. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21042. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21043. }
  21044. };
  21045. /**
  21046. * @author mikael emtinger / http://gomo.se/
  21047. * @author alteredq / http://alteredqualia.com/
  21048. */
  21049. THREE.LensFlarePlugin = function () {
  21050. var _gl, _renderer, _precision, _lensFlare = {};
  21051. this.init = function ( renderer ) {
  21052. _gl = renderer.context;
  21053. _renderer = renderer;
  21054. _precision = renderer.getPrecision();
  21055. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21056. _lensFlare.faces = new Uint16Array( 6 );
  21057. var i = 0;
  21058. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21059. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21060. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21061. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21062. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21063. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21064. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21065. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21066. i = 0;
  21067. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21068. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21069. // buffers
  21070. _lensFlare.vertexBuffer = _gl.createBuffer();
  21071. _lensFlare.elementBuffer = _gl.createBuffer();
  21072. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21073. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21074. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21075. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21076. // textures
  21077. _lensFlare.tempTexture = _gl.createTexture();
  21078. _lensFlare.occlusionTexture = _gl.createTexture();
  21079. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21080. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21081. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21082. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21083. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21084. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21085. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21086. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21087. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21088. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21089. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21090. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21091. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21092. _lensFlare.hasVertexTexture = false;
  21093. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21094. } else {
  21095. _lensFlare.hasVertexTexture = true;
  21096. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21097. }
  21098. _lensFlare.attributes = {};
  21099. _lensFlare.uniforms = {};
  21100. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21101. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21102. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21103. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21104. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21105. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21106. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21107. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21108. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21109. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21110. };
  21111. /*
  21112. * Render lens flares
  21113. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21114. * reads these back and calculates occlusion.
  21115. * Then _lensFlare.update_lensFlares() is called to re-position and
  21116. * update transparency of flares. Then they are rendered.
  21117. *
  21118. */
  21119. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21120. var flares = scene.__webglFlares,
  21121. nFlares = flares.length;
  21122. if ( ! nFlares ) return;
  21123. var tempPosition = new THREE.Vector3();
  21124. var invAspect = viewportHeight / viewportWidth,
  21125. halfViewportWidth = viewportWidth * 0.5,
  21126. halfViewportHeight = viewportHeight * 0.5;
  21127. var size = 16 / viewportHeight,
  21128. scale = new THREE.Vector2( size * invAspect, size );
  21129. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21130. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21131. var uniforms = _lensFlare.uniforms,
  21132. attributes = _lensFlare.attributes;
  21133. // set _lensFlare program and reset blending
  21134. _gl.useProgram( _lensFlare.program );
  21135. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21136. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21137. // loop through all lens flares to update their occlusion and positions
  21138. // setup gl and common used attribs/unforms
  21139. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21140. _gl.uniform1i( uniforms.map, 1 );
  21141. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21142. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21143. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21144. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21145. _gl.disable( _gl.CULL_FACE );
  21146. _gl.depthMask( false );
  21147. var i, j, jl, flare, sprite;
  21148. for ( i = 0; i < nFlares; i ++ ) {
  21149. size = 16 / viewportHeight;
  21150. scale.set( size * invAspect, size );
  21151. // calc object screen position
  21152. flare = flares[ i ];
  21153. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21154. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21155. tempPosition.applyProjection( camera.projectionMatrix );
  21156. // setup arrays for gl programs
  21157. screenPosition.copy( tempPosition )
  21158. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21159. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21160. // screen cull
  21161. if ( _lensFlare.hasVertexTexture || (
  21162. screenPositionPixels.x > 0 &&
  21163. screenPositionPixels.x < viewportWidth &&
  21164. screenPositionPixels.y > 0 &&
  21165. screenPositionPixels.y < viewportHeight ) ) {
  21166. // save current RGB to temp texture
  21167. _gl.activeTexture( _gl.TEXTURE1 );
  21168. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21169. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21170. // render pink quad
  21171. _gl.uniform1i( uniforms.renderType, 0 );
  21172. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21173. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21174. _gl.disable( _gl.BLEND );
  21175. _gl.enable( _gl.DEPTH_TEST );
  21176. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21177. // copy result to occlusionMap
  21178. _gl.activeTexture( _gl.TEXTURE0 );
  21179. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21180. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21181. // restore graphics
  21182. _gl.uniform1i( uniforms.renderType, 1 );
  21183. _gl.disable( _gl.DEPTH_TEST );
  21184. _gl.activeTexture( _gl.TEXTURE1 );
  21185. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21186. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21187. // update object positions
  21188. flare.positionScreen.copy( screenPosition )
  21189. if ( flare.customUpdateCallback ) {
  21190. flare.customUpdateCallback( flare );
  21191. } else {
  21192. flare.updateLensFlares();
  21193. }
  21194. // render flares
  21195. _gl.uniform1i( uniforms.renderType, 2 );
  21196. _gl.enable( _gl.BLEND );
  21197. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21198. sprite = flare.lensFlares[ j ];
  21199. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21200. screenPosition.x = sprite.x;
  21201. screenPosition.y = sprite.y;
  21202. screenPosition.z = sprite.z;
  21203. size = sprite.size * sprite.scale / viewportHeight;
  21204. scale.x = size * invAspect;
  21205. scale.y = size;
  21206. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21207. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21208. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21209. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21210. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21211. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21212. _renderer.setTexture( sprite.texture, 1 );
  21213. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21214. }
  21215. }
  21216. }
  21217. }
  21218. // restore gl
  21219. _gl.enable( _gl.CULL_FACE );
  21220. _gl.enable( _gl.DEPTH_TEST );
  21221. _gl.depthMask( true );
  21222. };
  21223. function createProgram ( shader, precision ) {
  21224. var program = _gl.createProgram();
  21225. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21226. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21227. var prefix = "precision " + precision + " float;\n";
  21228. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21229. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21230. _gl.compileShader( fragmentShader );
  21231. _gl.compileShader( vertexShader );
  21232. _gl.attachShader( program, fragmentShader );
  21233. _gl.attachShader( program, vertexShader );
  21234. _gl.linkProgram( program );
  21235. return program;
  21236. };
  21237. };
  21238. /**
  21239. * @author alteredq / http://alteredqualia.com/
  21240. */
  21241. THREE.ShadowMapPlugin = function () {
  21242. var _gl,
  21243. _renderer,
  21244. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21245. _frustum = new THREE.Frustum(),
  21246. _projScreenMatrix = new THREE.Matrix4(),
  21247. _min = new THREE.Vector3(),
  21248. _max = new THREE.Vector3(),
  21249. _matrixPosition = new THREE.Vector3();
  21250. this.init = function ( renderer ) {
  21251. _gl = renderer.context;
  21252. _renderer = renderer;
  21253. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21254. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21255. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21256. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21257. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21258. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21259. _depthMaterial._shadowPass = true;
  21260. _depthMaterialMorph._shadowPass = true;
  21261. _depthMaterialSkin._shadowPass = true;
  21262. _depthMaterialMorphSkin._shadowPass = true;
  21263. };
  21264. this.render = function ( scene, camera ) {
  21265. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21266. this.update( scene, camera );
  21267. };
  21268. this.update = function ( scene, camera ) {
  21269. var i, il, j, jl, n,
  21270. shadowMap, shadowMatrix, shadowCamera,
  21271. program, buffer, material,
  21272. webglObject, object, light,
  21273. renderList,
  21274. lights = [],
  21275. k = 0,
  21276. fog = null;
  21277. // set GL state for depth map
  21278. _gl.clearColor( 1, 1, 1, 1 );
  21279. _gl.disable( _gl.BLEND );
  21280. _gl.enable( _gl.CULL_FACE );
  21281. _gl.frontFace( _gl.CCW );
  21282. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21283. _gl.cullFace( _gl.FRONT );
  21284. } else {
  21285. _gl.cullFace( _gl.BACK );
  21286. }
  21287. _renderer.setDepthTest( true );
  21288. // preprocess lights
  21289. // - skip lights that are not casting shadows
  21290. // - create virtual lights for cascaded shadow maps
  21291. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21292. light = scene.__lights[ i ];
  21293. if ( ! light.castShadow ) continue;
  21294. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21295. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21296. var virtualLight;
  21297. if ( ! light.shadowCascadeArray[ n ] ) {
  21298. virtualLight = createVirtualLight( light, n );
  21299. virtualLight.originalCamera = camera;
  21300. var gyro = new THREE.Gyroscope();
  21301. gyro.position = light.shadowCascadeOffset;
  21302. gyro.add( virtualLight );
  21303. gyro.add( virtualLight.target );
  21304. camera.add( gyro );
  21305. light.shadowCascadeArray[ n ] = virtualLight;
  21306. console.log( "Created virtualLight", virtualLight );
  21307. } else {
  21308. virtualLight = light.shadowCascadeArray[ n ];
  21309. }
  21310. updateVirtualLight( light, n );
  21311. lights[ k ] = virtualLight;
  21312. k ++;
  21313. }
  21314. } else {
  21315. lights[ k ] = light;
  21316. k ++;
  21317. }
  21318. }
  21319. // render depth map
  21320. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21321. light = lights[ i ];
  21322. if ( ! light.shadowMap ) {
  21323. var shadowFilter = THREE.LinearFilter;
  21324. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21325. shadowFilter = THREE.NearestFilter;
  21326. }
  21327. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21328. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21329. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21330. light.shadowMatrix = new THREE.Matrix4();
  21331. }
  21332. if ( ! light.shadowCamera ) {
  21333. if ( light instanceof THREE.SpotLight ) {
  21334. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21335. } else if ( light instanceof THREE.DirectionalLight ) {
  21336. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21337. } else {
  21338. console.error( "Unsupported light type for shadow" );
  21339. continue;
  21340. }
  21341. scene.add( light.shadowCamera );
  21342. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21343. }
  21344. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21345. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21346. light.shadowCamera.add( light.cameraHelper );
  21347. }
  21348. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21349. updateShadowCamera( camera, light );
  21350. }
  21351. shadowMap = light.shadowMap;
  21352. shadowMatrix = light.shadowMatrix;
  21353. shadowCamera = light.shadowCamera;
  21354. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  21355. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  21356. shadowCamera.lookAt( _matrixPosition );
  21357. shadowCamera.updateMatrixWorld();
  21358. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21359. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21360. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21361. // compute shadow matrix
  21362. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21363. 0.0, 0.5, 0.0, 0.5,
  21364. 0.0, 0.0, 0.5, 0.5,
  21365. 0.0, 0.0, 0.0, 1.0 );
  21366. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21367. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21368. // update camera matrices and frustum
  21369. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21370. _frustum.setFromMatrix( _projScreenMatrix );
  21371. // render shadow map
  21372. _renderer.setRenderTarget( shadowMap );
  21373. _renderer.clear();
  21374. // set object matrices & frustum culling
  21375. renderList = scene.__webglObjects;
  21376. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21377. webglObject = renderList[ j ];
  21378. object = webglObject.object;
  21379. webglObject.render = false;
  21380. if ( object.visible && object.castShadow ) {
  21381. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21382. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21383. webglObject.render = true;
  21384. }
  21385. }
  21386. }
  21387. // render regular objects
  21388. var objectMaterial, useMorphing, useSkinning;
  21389. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21390. webglObject = renderList[ j ];
  21391. if ( webglObject.render ) {
  21392. object = webglObject.object;
  21393. buffer = webglObject.buffer;
  21394. // culling is overriden globally for all objects
  21395. // while rendering depth map
  21396. // need to deal with MeshFaceMaterial somehow
  21397. // in that case just use the first of material.materials for now
  21398. // (proper solution would require to break objects by materials
  21399. // similarly to regular rendering and then set corresponding
  21400. // depth materials per each chunk instead of just once per object)
  21401. objectMaterial = getObjectMaterial( object );
  21402. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21403. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21404. if ( object.customDepthMaterial ) {
  21405. material = object.customDepthMaterial;
  21406. } else if ( useSkinning ) {
  21407. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21408. } else if ( useMorphing ) {
  21409. material = _depthMaterialMorph;
  21410. } else {
  21411. material = _depthMaterial;
  21412. }
  21413. if ( buffer instanceof THREE.BufferGeometry ) {
  21414. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21415. } else {
  21416. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21417. }
  21418. }
  21419. }
  21420. // set matrices and render immediate objects
  21421. renderList = scene.__webglObjectsImmediate;
  21422. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21423. webglObject = renderList[ j ];
  21424. object = webglObject.object;
  21425. if ( object.visible && object.castShadow ) {
  21426. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21427. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21428. }
  21429. }
  21430. }
  21431. // restore GL state
  21432. var clearColor = _renderer.getClearColor(),
  21433. clearAlpha = _renderer.getClearAlpha();
  21434. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21435. _gl.enable( _gl.BLEND );
  21436. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21437. _gl.cullFace( _gl.BACK );
  21438. }
  21439. };
  21440. function createVirtualLight( light, cascade ) {
  21441. var virtualLight = new THREE.DirectionalLight();
  21442. virtualLight.isVirtual = true;
  21443. virtualLight.onlyShadow = true;
  21444. virtualLight.castShadow = true;
  21445. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21446. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21447. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21448. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21449. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21450. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21451. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21452. virtualLight.shadowDarkness = light.shadowDarkness;
  21453. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21454. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21455. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21456. virtualLight.pointsWorld = [];
  21457. virtualLight.pointsFrustum = [];
  21458. var pointsWorld = virtualLight.pointsWorld,
  21459. pointsFrustum = virtualLight.pointsFrustum;
  21460. for ( var i = 0; i < 8; i ++ ) {
  21461. pointsWorld[ i ] = new THREE.Vector3();
  21462. pointsFrustum[ i ] = new THREE.Vector3();
  21463. }
  21464. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21465. var farZ = light.shadowCascadeFarZ[ cascade ];
  21466. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21467. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21468. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21469. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21470. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21471. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21472. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21473. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21474. return virtualLight;
  21475. }
  21476. // Synchronize virtual light with the original light
  21477. function updateVirtualLight( light, cascade ) {
  21478. var virtualLight = light.shadowCascadeArray[ cascade ];
  21479. virtualLight.position.copy( light.position );
  21480. virtualLight.target.position.copy( light.target.position );
  21481. virtualLight.lookAt( virtualLight.target );
  21482. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21483. virtualLight.shadowDarkness = light.shadowDarkness;
  21484. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21485. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21486. var farZ = light.shadowCascadeFarZ[ cascade ];
  21487. var pointsFrustum = virtualLight.pointsFrustum;
  21488. pointsFrustum[ 0 ].z = nearZ;
  21489. pointsFrustum[ 1 ].z = nearZ;
  21490. pointsFrustum[ 2 ].z = nearZ;
  21491. pointsFrustum[ 3 ].z = nearZ;
  21492. pointsFrustum[ 4 ].z = farZ;
  21493. pointsFrustum[ 5 ].z = farZ;
  21494. pointsFrustum[ 6 ].z = farZ;
  21495. pointsFrustum[ 7 ].z = farZ;
  21496. }
  21497. // Fit shadow camera's ortho frustum to camera frustum
  21498. function updateShadowCamera( camera, light ) {
  21499. var shadowCamera = light.shadowCamera,
  21500. pointsFrustum = light.pointsFrustum,
  21501. pointsWorld = light.pointsWorld;
  21502. _min.set( Infinity, Infinity, Infinity );
  21503. _max.set( -Infinity, -Infinity, -Infinity );
  21504. for ( var i = 0; i < 8; i ++ ) {
  21505. var p = pointsWorld[ i ];
  21506. p.copy( pointsFrustum[ i ] );
  21507. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21508. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21509. if ( p.x < _min.x ) _min.x = p.x;
  21510. if ( p.x > _max.x ) _max.x = p.x;
  21511. if ( p.y < _min.y ) _min.y = p.y;
  21512. if ( p.y > _max.y ) _max.y = p.y;
  21513. if ( p.z < _min.z ) _min.z = p.z;
  21514. if ( p.z > _max.z ) _max.z = p.z;
  21515. }
  21516. shadowCamera.left = _min.x;
  21517. shadowCamera.right = _max.x;
  21518. shadowCamera.top = _max.y;
  21519. shadowCamera.bottom = _min.y;
  21520. // can't really fit near/far
  21521. //shadowCamera.near = _min.z;
  21522. //shadowCamera.far = _max.z;
  21523. shadowCamera.updateProjectionMatrix();
  21524. }
  21525. // For the moment just ignore objects that have multiple materials with different animation methods
  21526. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21527. function getObjectMaterial( object ) {
  21528. return object.material instanceof THREE.MeshFaceMaterial
  21529. ? object.material.materials[ 0 ]
  21530. : object.material;
  21531. };
  21532. };
  21533. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21534. /**
  21535. * @author mikael emtinger / http://gomo.se/
  21536. * @author alteredq / http://alteredqualia.com/
  21537. */
  21538. THREE.SpritePlugin = function () {
  21539. var _gl, _renderer, _precision, _sprite = {};
  21540. this.init = function ( renderer ) {
  21541. _gl = renderer.context;
  21542. _renderer = renderer;
  21543. _precision = renderer.getPrecision();
  21544. _sprite.vertices = new Float32Array( 8 + 8 );
  21545. _sprite.faces = new Uint16Array( 6 );
  21546. var i = 0;
  21547. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21548. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21549. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21550. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21551. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21552. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21553. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21554. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21555. i = 0;
  21556. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21557. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21558. _sprite.vertexBuffer = _gl.createBuffer();
  21559. _sprite.elementBuffer = _gl.createBuffer();
  21560. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21561. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21562. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21563. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21564. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21565. _sprite.attributes = {};
  21566. _sprite.uniforms = {};
  21567. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21568. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21569. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21570. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21571. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21572. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21573. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21574. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21575. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21576. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21577. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21578. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21579. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21580. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21581. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21582. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21583. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21584. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21585. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21586. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21587. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21588. };
  21589. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21590. var sprites = scene.__webglSprites,
  21591. nSprites = sprites.length;
  21592. if ( ! nSprites ) return;
  21593. var attributes = _sprite.attributes,
  21594. uniforms = _sprite.uniforms;
  21595. var invAspect = viewportHeight / viewportWidth;
  21596. var halfViewportWidth = viewportWidth * 0.5,
  21597. halfViewportHeight = viewportHeight * 0.5;
  21598. // setup gl
  21599. _gl.useProgram( _sprite.program );
  21600. _gl.enableVertexAttribArray( attributes.position );
  21601. _gl.enableVertexAttribArray( attributes.uv );
  21602. _gl.disable( _gl.CULL_FACE );
  21603. _gl.enable( _gl.BLEND );
  21604. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21605. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21606. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21607. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21608. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21609. _gl.activeTexture( _gl.TEXTURE0 );
  21610. _gl.uniform1i( uniforms.map, 0 );
  21611. var oldFogType = 0;
  21612. var sceneFogType = 0;
  21613. var fog = scene.fog;
  21614. if ( fog ) {
  21615. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21616. if ( fog instanceof THREE.Fog ) {
  21617. _gl.uniform1f( uniforms.fogNear, fog.near );
  21618. _gl.uniform1f( uniforms.fogFar, fog.far );
  21619. _gl.uniform1i( uniforms.fogType, 1 );
  21620. oldFogType = 1;
  21621. sceneFogType = 1;
  21622. } else if ( fog instanceof THREE.FogExp2 ) {
  21623. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21624. _gl.uniform1i( uniforms.fogType, 2 );
  21625. oldFogType = 2;
  21626. sceneFogType = 2;
  21627. }
  21628. } else {
  21629. _gl.uniform1i( uniforms.fogType, 0 );
  21630. oldFogType = 0;
  21631. sceneFogType = 0;
  21632. }
  21633. // update positions and sort
  21634. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21635. for( i = 0; i < nSprites; i ++ ) {
  21636. sprite = sprites[ i ];
  21637. material = sprite.material;
  21638. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21639. if ( ! material.useScreenCoordinates ) {
  21640. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21641. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21642. } else {
  21643. sprite.z = - sprite.position.z;
  21644. }
  21645. }
  21646. sprites.sort( painterSortStable );
  21647. // render all sprites
  21648. for( i = 0; i < nSprites; i ++ ) {
  21649. sprite = sprites[ i ];
  21650. material = sprite.material;
  21651. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21652. if ( material.map && material.map.image && material.map.image.width ) {
  21653. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21654. if ( material.useScreenCoordinates === true ) {
  21655. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21656. _gl.uniform3f(
  21657. uniforms.screenPosition,
  21658. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21659. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21660. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21661. );
  21662. scale[ 0 ] = _renderer.devicePixelRatio;
  21663. scale[ 1 ] = _renderer.devicePixelRatio;
  21664. } else {
  21665. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21666. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21667. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21668. scale[ 0 ] = 1;
  21669. scale[ 1 ] = 1;
  21670. }
  21671. if ( scene.fog && material.fog ) {
  21672. fogType = sceneFogType;
  21673. } else {
  21674. fogType = 0;
  21675. }
  21676. if ( oldFogType !== fogType ) {
  21677. _gl.uniform1i( uniforms.fogType, fogType );
  21678. oldFogType = fogType;
  21679. }
  21680. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21681. scale[ 0 ] *= size * invAspect * sprite.scale.x
  21682. scale[ 1 ] *= size * sprite.scale.y;
  21683. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21684. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21685. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21686. _gl.uniform1f( uniforms.opacity, material.opacity );
  21687. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21688. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21689. _gl.uniform2fv( uniforms.scale, scale );
  21690. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21691. _renderer.setDepthTest( material.depthTest );
  21692. _renderer.setDepthWrite( material.depthWrite );
  21693. _renderer.setTexture( material.map, 0 );
  21694. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21695. }
  21696. }
  21697. // restore gl
  21698. _gl.enable( _gl.CULL_FACE );
  21699. };
  21700. function createProgram ( shader, precision ) {
  21701. var program = _gl.createProgram();
  21702. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21703. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21704. var prefix = "precision " + precision + " float;\n";
  21705. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21706. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21707. _gl.compileShader( fragmentShader );
  21708. _gl.compileShader( vertexShader );
  21709. _gl.attachShader( program, fragmentShader );
  21710. _gl.attachShader( program, vertexShader );
  21711. _gl.linkProgram( program );
  21712. return program;
  21713. };
  21714. function painterSortStable ( a, b ) {
  21715. if ( a.z !== b.z ) {
  21716. return b.z - a.z;
  21717. } else {
  21718. return b.id - a.id;
  21719. }
  21720. };
  21721. };
  21722. /**
  21723. * @author alteredq / http://alteredqualia.com/
  21724. */
  21725. THREE.DepthPassPlugin = function () {
  21726. this.enabled = false;
  21727. this.renderTarget = null;
  21728. var _gl,
  21729. _renderer,
  21730. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21731. _frustum = new THREE.Frustum(),
  21732. _projScreenMatrix = new THREE.Matrix4();
  21733. this.init = function ( renderer ) {
  21734. _gl = renderer.context;
  21735. _renderer = renderer;
  21736. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21737. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21738. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21739. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21740. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21741. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21742. _depthMaterial._shadowPass = true;
  21743. _depthMaterialMorph._shadowPass = true;
  21744. _depthMaterialSkin._shadowPass = true;
  21745. _depthMaterialMorphSkin._shadowPass = true;
  21746. };
  21747. this.render = function ( scene, camera ) {
  21748. if ( ! this.enabled ) return;
  21749. this.update( scene, camera );
  21750. };
  21751. this.update = function ( scene, camera ) {
  21752. var i, il, j, jl, n,
  21753. program, buffer, material,
  21754. webglObject, object, light,
  21755. renderList,
  21756. fog = null;
  21757. // set GL state for depth map
  21758. _gl.clearColor( 1, 1, 1, 1 );
  21759. _gl.disable( _gl.BLEND );
  21760. _renderer.setDepthTest( true );
  21761. // update scene
  21762. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21763. // update camera matrices and frustum
  21764. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21765. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21766. _frustum.setFromMatrix( _projScreenMatrix );
  21767. // render depth map
  21768. _renderer.setRenderTarget( this.renderTarget );
  21769. _renderer.clear();
  21770. // set object matrices & frustum culling
  21771. renderList = scene.__webglObjects;
  21772. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21773. webglObject = renderList[ j ];
  21774. object = webglObject.object;
  21775. webglObject.render = false;
  21776. if ( object.visible ) {
  21777. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21778. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21779. webglObject.render = true;
  21780. }
  21781. }
  21782. }
  21783. // render regular objects
  21784. var objectMaterial, useMorphing, useSkinning;
  21785. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21786. webglObject = renderList[ j ];
  21787. if ( webglObject.render ) {
  21788. object = webglObject.object;
  21789. buffer = webglObject.buffer;
  21790. // todo: create proper depth material for particles
  21791. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21792. objectMaterial = getObjectMaterial( object );
  21793. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21794. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21795. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21796. if ( object.customDepthMaterial ) {
  21797. material = object.customDepthMaterial;
  21798. } else if ( useSkinning ) {
  21799. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21800. } else if ( useMorphing ) {
  21801. material = _depthMaterialMorph;
  21802. } else {
  21803. material = _depthMaterial;
  21804. }
  21805. if ( buffer instanceof THREE.BufferGeometry ) {
  21806. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21807. } else {
  21808. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21809. }
  21810. }
  21811. }
  21812. // set matrices and render immediate objects
  21813. renderList = scene.__webglObjectsImmediate;
  21814. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21815. webglObject = renderList[ j ];
  21816. object = webglObject.object;
  21817. if ( object.visible ) {
  21818. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21819. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21820. }
  21821. }
  21822. // restore GL state
  21823. var clearColor = _renderer.getClearColor(),
  21824. clearAlpha = _renderer.getClearAlpha();
  21825. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21826. _gl.enable( _gl.BLEND );
  21827. };
  21828. // For the moment just ignore objects that have multiple materials with different animation methods
  21829. // Only the first material will be taken into account for deciding which depth material to use
  21830. function getObjectMaterial( object ) {
  21831. return object.material instanceof THREE.MeshFaceMaterial
  21832. ? object.material.materials[ 0 ]
  21833. : object.material;
  21834. };
  21835. };
  21836. /**
  21837. * @author mikael emtinger / http://gomo.se/
  21838. *
  21839. */
  21840. THREE.ShaderFlares = {
  21841. 'lensFlareVertexTexture': {
  21842. vertexShader: [
  21843. "uniform lowp int renderType;",
  21844. "uniform vec3 screenPosition;",
  21845. "uniform vec2 scale;",
  21846. "uniform float rotation;",
  21847. "uniform sampler2D occlusionMap;",
  21848. "attribute vec2 position;",
  21849. "attribute vec2 uv;",
  21850. "varying vec2 vUV;",
  21851. "varying float vVisibility;",
  21852. "void main() {",
  21853. "vUV = uv;",
  21854. "vec2 pos = position;",
  21855. "if( renderType == 2 ) {",
  21856. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21857. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21858. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21859. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21860. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21861. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21862. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21863. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21864. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21865. "vVisibility = ( visibility.r / 9.0 ) *",
  21866. "( 1.0 - visibility.g / 9.0 ) *",
  21867. "( visibility.b / 9.0 ) *",
  21868. "( 1.0 - visibility.a / 9.0 );",
  21869. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21870. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21871. "}",
  21872. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21873. "}"
  21874. ].join( "\n" ),
  21875. fragmentShader: [
  21876. "uniform lowp int renderType;",
  21877. "uniform sampler2D map;",
  21878. "uniform float opacity;",
  21879. "uniform vec3 color;",
  21880. "varying vec2 vUV;",
  21881. "varying float vVisibility;",
  21882. "void main() {",
  21883. // pink square
  21884. "if( renderType == 0 ) {",
  21885. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21886. // restore
  21887. "} else if( renderType == 1 ) {",
  21888. "gl_FragColor = texture2D( map, vUV );",
  21889. // flare
  21890. "} else {",
  21891. "vec4 texture = texture2D( map, vUV );",
  21892. "texture.a *= opacity * vVisibility;",
  21893. "gl_FragColor = texture;",
  21894. "gl_FragColor.rgb *= color;",
  21895. "}",
  21896. "}"
  21897. ].join( "\n" )
  21898. },
  21899. 'lensFlare': {
  21900. vertexShader: [
  21901. "uniform lowp int renderType;",
  21902. "uniform vec3 screenPosition;",
  21903. "uniform vec2 scale;",
  21904. "uniform float rotation;",
  21905. "attribute vec2 position;",
  21906. "attribute vec2 uv;",
  21907. "varying vec2 vUV;",
  21908. "void main() {",
  21909. "vUV = uv;",
  21910. "vec2 pos = position;",
  21911. "if( renderType == 2 ) {",
  21912. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21913. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21914. "}",
  21915. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21916. "}"
  21917. ].join( "\n" ),
  21918. fragmentShader: [
  21919. "precision mediump float;",
  21920. "uniform lowp int renderType;",
  21921. "uniform sampler2D map;",
  21922. "uniform sampler2D occlusionMap;",
  21923. "uniform float opacity;",
  21924. "uniform vec3 color;",
  21925. "varying vec2 vUV;",
  21926. "void main() {",
  21927. // pink square
  21928. "if( renderType == 0 ) {",
  21929. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21930. // restore
  21931. "} else if( renderType == 1 ) {",
  21932. "gl_FragColor = texture2D( map, vUV );",
  21933. // flare
  21934. "} else {",
  21935. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21936. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21937. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21938. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21939. "visibility = ( 1.0 - visibility / 4.0 );",
  21940. "vec4 texture = texture2D( map, vUV );",
  21941. "texture.a *= opacity * visibility;",
  21942. "gl_FragColor = texture;",
  21943. "gl_FragColor.rgb *= color;",
  21944. "}",
  21945. "}"
  21946. ].join( "\n" )
  21947. }
  21948. };
  21949. /**
  21950. * @author mikael emtinger / http://gomo.se/
  21951. * @author alteredq / http://alteredqualia.com/
  21952. *
  21953. */
  21954. THREE.ShaderSprite = {
  21955. 'sprite': {
  21956. vertexShader: [
  21957. "uniform int useScreenCoordinates;",
  21958. "uniform int sizeAttenuation;",
  21959. "uniform vec3 screenPosition;",
  21960. "uniform mat4 modelViewMatrix;",
  21961. "uniform mat4 projectionMatrix;",
  21962. "uniform float rotation;",
  21963. "uniform vec2 scale;",
  21964. "uniform vec2 alignment;",
  21965. "uniform vec2 uvOffset;",
  21966. "uniform vec2 uvScale;",
  21967. "attribute vec2 position;",
  21968. "attribute vec2 uv;",
  21969. "varying vec2 vUV;",
  21970. "void main() {",
  21971. "vUV = uvOffset + uv * uvScale;",
  21972. "vec2 alignedPosition = position + alignment;",
  21973. "vec2 rotatedPosition;",
  21974. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21975. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21976. "vec4 finalPosition;",
  21977. "if( useScreenCoordinates != 0 ) {",
  21978. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21979. "} else {",
  21980. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21981. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21982. "}",
  21983. "gl_Position = finalPosition;",
  21984. "}"
  21985. ].join( "\n" ),
  21986. fragmentShader: [
  21987. "uniform vec3 color;",
  21988. "uniform sampler2D map;",
  21989. "uniform float opacity;",
  21990. "uniform int fogType;",
  21991. "uniform vec3 fogColor;",
  21992. "uniform float fogDensity;",
  21993. "uniform float fogNear;",
  21994. "uniform float fogFar;",
  21995. "uniform float alphaTest;",
  21996. "varying vec2 vUV;",
  21997. "void main() {",
  21998. "vec4 texture = texture2D( map, vUV );",
  21999. "if ( texture.a < alphaTest ) discard;",
  22000. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  22001. "if ( fogType > 0 ) {",
  22002. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  22003. "float fogFactor = 0.0;",
  22004. "if ( fogType == 1 ) {",
  22005. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  22006. "} else {",
  22007. "const float LOG2 = 1.442695;",
  22008. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  22009. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  22010. "}",
  22011. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  22012. "}",
  22013. "}"
  22014. ].join( "\n" )
  22015. }
  22016. };
粤ICP备19079148号