three.js 819 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760
  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 = { REVISION: '66' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  15. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  16. // requestAnimationFrame polyfill by Erik Möller
  17. // fixes from Paul Irish and Tino Zijdel
  18. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  19. ( function () {
  20. var lastTime = 0;
  21. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  22. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  23. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  24. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  25. }
  26. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  27. self.requestAnimationFrame = function ( callback ) {
  28. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  29. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  30. lastTime = currTime + timeToCall;
  31. return id;
  32. };
  33. }
  34. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  35. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  36. }
  37. }() );
  38. // GL STATE CONSTANTS
  39. THREE.CullFaceNone = 0;
  40. THREE.CullFaceBack = 1;
  41. THREE.CullFaceFront = 2;
  42. THREE.CullFaceFrontBack = 3;
  43. THREE.FrontFaceDirectionCW = 0;
  44. THREE.FrontFaceDirectionCCW = 1;
  45. // SHADOWING TYPES
  46. THREE.BasicShadowMap = 0;
  47. THREE.PCFShadowMap = 1;
  48. THREE.PCFSoftShadowMap = 2;
  49. // MATERIAL CONSTANTS
  50. // side
  51. THREE.FrontSide = 0;
  52. THREE.BackSide = 1;
  53. THREE.DoubleSide = 2;
  54. // shading
  55. THREE.NoShading = 0;
  56. THREE.FlatShading = 1;
  57. THREE.SmoothShading = 2;
  58. // colors
  59. THREE.NoColors = 0;
  60. THREE.FaceColors = 1;
  61. THREE.VertexColors = 2;
  62. // blending modes
  63. THREE.NoBlending = 0;
  64. THREE.NormalBlending = 1;
  65. THREE.AdditiveBlending = 2;
  66. THREE.SubtractiveBlending = 3;
  67. THREE.MultiplyBlending = 4;
  68. THREE.CustomBlending = 5;
  69. // custom blending equations
  70. // (numbers start from 100 not to clash with other
  71. // mappings to OpenGL constants defined in Texture.js)
  72. THREE.AddEquation = 100;
  73. THREE.SubtractEquation = 101;
  74. THREE.ReverseSubtractEquation = 102;
  75. // custom blending destination factors
  76. THREE.ZeroFactor = 200;
  77. THREE.OneFactor = 201;
  78. THREE.SrcColorFactor = 202;
  79. THREE.OneMinusSrcColorFactor = 203;
  80. THREE.SrcAlphaFactor = 204;
  81. THREE.OneMinusSrcAlphaFactor = 205;
  82. THREE.DstAlphaFactor = 206;
  83. THREE.OneMinusDstAlphaFactor = 207;
  84. // custom blending source factors
  85. //THREE.ZeroFactor = 200;
  86. //THREE.OneFactor = 201;
  87. //THREE.SrcAlphaFactor = 204;
  88. //THREE.OneMinusSrcAlphaFactor = 205;
  89. //THREE.DstAlphaFactor = 206;
  90. //THREE.OneMinusDstAlphaFactor = 207;
  91. THREE.DstColorFactor = 208;
  92. THREE.OneMinusDstColorFactor = 209;
  93. THREE.SrcAlphaSaturateFactor = 210;
  94. // TEXTURE CONSTANTS
  95. THREE.MultiplyOperation = 0;
  96. THREE.MixOperation = 1;
  97. THREE.AddOperation = 2;
  98. // Mapping modes
  99. THREE.UVMapping = function () {};
  100. THREE.CubeReflectionMapping = function () {};
  101. THREE.CubeRefractionMapping = function () {};
  102. THREE.SphericalReflectionMapping = function () {};
  103. THREE.SphericalRefractionMapping = function () {};
  104. // Wrapping modes
  105. THREE.RepeatWrapping = 1000;
  106. THREE.ClampToEdgeWrapping = 1001;
  107. THREE.MirroredRepeatWrapping = 1002;
  108. // Filters
  109. THREE.NearestFilter = 1003;
  110. THREE.NearestMipMapNearestFilter = 1004;
  111. THREE.NearestMipMapLinearFilter = 1005;
  112. THREE.LinearFilter = 1006;
  113. THREE.LinearMipMapNearestFilter = 1007;
  114. THREE.LinearMipMapLinearFilter = 1008;
  115. // Data types
  116. THREE.UnsignedByteType = 1009;
  117. THREE.ByteType = 1010;
  118. THREE.ShortType = 1011;
  119. THREE.UnsignedShortType = 1012;
  120. THREE.IntType = 1013;
  121. THREE.UnsignedIntType = 1014;
  122. THREE.FloatType = 1015;
  123. // Pixel types
  124. //THREE.UnsignedByteType = 1009;
  125. THREE.UnsignedShort4444Type = 1016;
  126. THREE.UnsignedShort5551Type = 1017;
  127. THREE.UnsignedShort565Type = 1018;
  128. // Pixel formats
  129. THREE.AlphaFormat = 1019;
  130. THREE.RGBFormat = 1020;
  131. THREE.RGBAFormat = 1021;
  132. THREE.LuminanceFormat = 1022;
  133. THREE.LuminanceAlphaFormat = 1023;
  134. // Compressed texture formats
  135. THREE.RGB_S3TC_DXT1_Format = 2001;
  136. THREE.RGBA_S3TC_DXT1_Format = 2002;
  137. THREE.RGBA_S3TC_DXT3_Format = 2003;
  138. THREE.RGBA_S3TC_DXT5_Format = 2004;
  139. /*
  140. // Potential future PVRTC compressed texture formats
  141. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  142. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  143. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  144. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  145. */
  146. /**
  147. * @author mrdoob / http://mrdoob.com/
  148. */
  149. THREE.Color = function ( color ) {
  150. if ( arguments.length === 3 ) {
  151. return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
  152. }
  153. return this.set( color )
  154. };
  155. THREE.Color.prototype = {
  156. constructor: THREE.Color,
  157. r: 1, g: 1, b: 1,
  158. set: function ( value ) {
  159. if ( value instanceof THREE.Color ) {
  160. this.copy( value );
  161. } else if ( typeof value === 'number' ) {
  162. this.setHex( value );
  163. } else if ( typeof value === 'string' ) {
  164. this.setStyle( value );
  165. }
  166. return this;
  167. },
  168. setHex: function ( hex ) {
  169. hex = Math.floor( hex );
  170. this.r = ( hex >> 16 & 255 ) / 255;
  171. this.g = ( hex >> 8 & 255 ) / 255;
  172. this.b = ( hex & 255 ) / 255;
  173. return this;
  174. },
  175. setRGB: function ( r, g, b ) {
  176. this.r = r;
  177. this.g = g;
  178. this.b = b;
  179. return this;
  180. },
  181. setHSL: function ( h, s, l ) {
  182. // h,s,l ranges are in 0.0 - 1.0
  183. if ( s === 0 ) {
  184. this.r = this.g = this.b = l;
  185. } else {
  186. var hue2rgb = function ( p, q, t ) {
  187. if ( t < 0 ) t += 1;
  188. if ( t > 1 ) t -= 1;
  189. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  190. if ( t < 1 / 2 ) return q;
  191. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  192. return p;
  193. };
  194. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  195. var q = ( 2 * l ) - p;
  196. this.r = hue2rgb( q, p, h + 1 / 3 );
  197. this.g = hue2rgb( q, p, h );
  198. this.b = hue2rgb( q, p, h - 1 / 3 );
  199. }
  200. return this;
  201. },
  202. setStyle: function ( style ) {
  203. // rgb(255,0,0)
  204. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  205. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  206. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  207. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  208. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  209. return this;
  210. }
  211. // rgb(100%,0%,0%)
  212. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  213. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  214. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  215. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  216. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  217. return this;
  218. }
  219. // #ff0000
  220. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  221. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  222. this.setHex( parseInt( color[ 1 ], 16 ) );
  223. return this;
  224. }
  225. // #f00
  226. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  227. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  228. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  229. return this;
  230. }
  231. // red
  232. if ( /^(\w+)$/i.test( style ) ) {
  233. this.setHex( THREE.ColorKeywords[ style ] );
  234. return this;
  235. }
  236. },
  237. copy: function ( color ) {
  238. this.r = color.r;
  239. this.g = color.g;
  240. this.b = color.b;
  241. return this;
  242. },
  243. copyGammaToLinear: function ( color ) {
  244. this.r = color.r * color.r;
  245. this.g = color.g * color.g;
  246. this.b = color.b * color.b;
  247. return this;
  248. },
  249. copyLinearToGamma: function ( color ) {
  250. this.r = Math.sqrt( color.r );
  251. this.g = Math.sqrt( color.g );
  252. this.b = Math.sqrt( color.b );
  253. return this;
  254. },
  255. convertGammaToLinear: function () {
  256. var r = this.r, g = this.g, b = this.b;
  257. this.r = r * r;
  258. this.g = g * g;
  259. this.b = b * b;
  260. return this;
  261. },
  262. convertLinearToGamma: function () {
  263. this.r = Math.sqrt( this.r );
  264. this.g = Math.sqrt( this.g );
  265. this.b = Math.sqrt( this.b );
  266. return this;
  267. },
  268. getHex: function () {
  269. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  270. },
  271. getHexString: function () {
  272. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  273. },
  274. getHSL: function ( optionalTarget ) {
  275. // h,s,l ranges are in 0.0 - 1.0
  276. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  277. var r = this.r, g = this.g, b = this.b;
  278. var max = Math.max( r, g, b );
  279. var min = Math.min( r, g, b );
  280. var hue, saturation;
  281. var lightness = ( min + max ) / 2.0;
  282. if ( min === max ) {
  283. hue = 0;
  284. saturation = 0;
  285. } else {
  286. var delta = max - min;
  287. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  288. switch ( max ) {
  289. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  290. case g: hue = ( b - r ) / delta + 2; break;
  291. case b: hue = ( r - g ) / delta + 4; break;
  292. }
  293. hue /= 6;
  294. }
  295. hsl.h = hue;
  296. hsl.s = saturation;
  297. hsl.l = lightness;
  298. return hsl;
  299. },
  300. getStyle: function () {
  301. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  302. },
  303. offsetHSL: function ( h, s, l ) {
  304. var hsl = this.getHSL();
  305. hsl.h += h; hsl.s += s; hsl.l += l;
  306. this.setHSL( hsl.h, hsl.s, hsl.l );
  307. return this;
  308. },
  309. add: function ( color ) {
  310. this.r += color.r;
  311. this.g += color.g;
  312. this.b += color.b;
  313. return this;
  314. },
  315. addColors: function ( color1, color2 ) {
  316. this.r = color1.r + color2.r;
  317. this.g = color1.g + color2.g;
  318. this.b = color1.b + color2.b;
  319. return this;
  320. },
  321. addScalar: function ( s ) {
  322. this.r += s;
  323. this.g += s;
  324. this.b += s;
  325. return this;
  326. },
  327. multiply: function ( color ) {
  328. this.r *= color.r;
  329. this.g *= color.g;
  330. this.b *= color.b;
  331. return this;
  332. },
  333. multiplyScalar: function ( s ) {
  334. this.r *= s;
  335. this.g *= s;
  336. this.b *= s;
  337. return this;
  338. },
  339. lerp: function ( color, alpha ) {
  340. this.r += ( color.r - this.r ) * alpha;
  341. this.g += ( color.g - this.g ) * alpha;
  342. this.b += ( color.b - this.b ) * alpha;
  343. return this;
  344. },
  345. equals: function ( c ) {
  346. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  347. },
  348. fromArray: function ( array ) {
  349. this.r = array[ 0 ];
  350. this.g = array[ 1 ];
  351. this.b = array[ 2 ];
  352. return this;
  353. },
  354. toArray: function () {
  355. return [ this.r, this.g, this.b ];
  356. },
  357. clone: function () {
  358. return new THREE.Color().setRGB( this.r, this.g, this.b );
  359. }
  360. };
  361. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  362. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  363. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  364. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  365. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  366. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  367. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  368. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  369. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  370. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  371. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  372. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  373. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  374. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  375. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  376. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  377. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  378. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  379. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  380. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  381. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  382. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  383. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  384. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  385. /**
  386. * @author mikael emtinger / http://gomo.se/
  387. * @author alteredq / http://alteredqualia.com/
  388. * @author WestLangley / http://github.com/WestLangley
  389. * @author bhouston / http://exocortex.com
  390. */
  391. THREE.Quaternion = function ( x, y, z, w ) {
  392. this._x = x || 0;
  393. this._y = y || 0;
  394. this._z = z || 0;
  395. this._w = ( w !== undefined ) ? w : 1;
  396. };
  397. THREE.Quaternion.prototype = {
  398. constructor: THREE.Quaternion,
  399. _x: 0,_y: 0, _z: 0, _w: 0,
  400. _euler: undefined,
  401. _updateEuler: function ( callback ) {
  402. if ( this._euler !== undefined ) {
  403. this._euler.setFromQuaternion( this, undefined, false );
  404. }
  405. },
  406. get x () {
  407. return this._x;
  408. },
  409. set x ( value ) {
  410. this._x = value;
  411. this._updateEuler();
  412. },
  413. get y () {
  414. return this._y;
  415. },
  416. set y ( value ) {
  417. this._y = value;
  418. this._updateEuler();
  419. },
  420. get z () {
  421. return this._z;
  422. },
  423. set z ( value ) {
  424. this._z = value;
  425. this._updateEuler();
  426. },
  427. get w () {
  428. return this._w;
  429. },
  430. set w ( value ) {
  431. this._w = value;
  432. this._updateEuler();
  433. },
  434. set: function ( x, y, z, w ) {
  435. this._x = x;
  436. this._y = y;
  437. this._z = z;
  438. this._w = w;
  439. this._updateEuler();
  440. return this;
  441. },
  442. copy: function ( quaternion ) {
  443. this._x = quaternion._x;
  444. this._y = quaternion._y;
  445. this._z = quaternion._z;
  446. this._w = quaternion._w;
  447. this._updateEuler();
  448. return this;
  449. },
  450. setFromEuler: function ( euler, update ) {
  451. if ( euler instanceof THREE.Euler === false ) {
  452. throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  453. }
  454. // http://www.mathworks.com/matlabcentral/fileexchange/
  455. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  456. // content/SpinCalc.m
  457. var c1 = Math.cos( euler._x / 2 );
  458. var c2 = Math.cos( euler._y / 2 );
  459. var c3 = Math.cos( euler._z / 2 );
  460. var s1 = Math.sin( euler._x / 2 );
  461. var s2 = Math.sin( euler._y / 2 );
  462. var s3 = Math.sin( euler._z / 2 );
  463. if ( euler.order === 'XYZ' ) {
  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. } else if ( euler.order === 'YXZ' ) {
  469. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  470. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  471. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  472. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  473. } else if ( euler.order === 'ZXY' ) {
  474. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  475. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  476. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  477. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  478. } else if ( euler.order === 'ZYX' ) {
  479. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  480. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  481. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  482. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  483. } else if ( euler.order === 'YZX' ) {
  484. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  485. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  486. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  487. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  488. } else if ( euler.order === 'XZY' ) {
  489. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  490. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  491. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  492. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  493. }
  494. if ( update !== false ) this._updateEuler();
  495. return this;
  496. },
  497. setFromAxisAngle: function ( axis, angle ) {
  498. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  499. // axis have to be normalized
  500. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  501. this._x = axis.x * s;
  502. this._y = axis.y * s;
  503. this._z = axis.z * s;
  504. this._w = Math.cos( halfAngle );
  505. this._updateEuler();
  506. return this;
  507. },
  508. setFromRotationMatrix: function ( m ) {
  509. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  510. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  511. var te = m.elements,
  512. m11 = te[0], m12 = te[4], m13 = te[8],
  513. m21 = te[1], m22 = te[5], m23 = te[9],
  514. m31 = te[2], m32 = te[6], m33 = te[10],
  515. trace = m11 + m22 + m33,
  516. s;
  517. if ( trace > 0 ) {
  518. s = 0.5 / Math.sqrt( trace + 1.0 );
  519. this._w = 0.25 / s;
  520. this._x = ( m32 - m23 ) * s;
  521. this._y = ( m13 - m31 ) * s;
  522. this._z = ( m21 - m12 ) * s;
  523. } else if ( m11 > m22 && m11 > m33 ) {
  524. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  525. this._w = (m32 - m23 ) / s;
  526. this._x = 0.25 * s;
  527. this._y = (m12 + m21 ) / s;
  528. this._z = (m13 + m31 ) / s;
  529. } else if ( m22 > m33 ) {
  530. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  531. this._w = (m13 - m31 ) / s;
  532. this._x = (m12 + m21 ) / s;
  533. this._y = 0.25 * s;
  534. this._z = (m23 + m32 ) / s;
  535. } else {
  536. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  537. this._w = ( m21 - m12 ) / s;
  538. this._x = ( m13 + m31 ) / s;
  539. this._y = ( m23 + m32 ) / s;
  540. this._z = 0.25 * s;
  541. }
  542. this._updateEuler();
  543. return this;
  544. },
  545. inverse: function () {
  546. this.conjugate().normalize();
  547. return this;
  548. },
  549. conjugate: function () {
  550. this._x *= -1;
  551. this._y *= -1;
  552. this._z *= -1;
  553. this._updateEuler();
  554. return this;
  555. },
  556. lengthSq: function () {
  557. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  558. },
  559. length: function () {
  560. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  561. },
  562. normalize: function () {
  563. var l = this.length();
  564. if ( l === 0 ) {
  565. this._x = 0;
  566. this._y = 0;
  567. this._z = 0;
  568. this._w = 1;
  569. } else {
  570. l = 1 / l;
  571. this._x = this._x * l;
  572. this._y = this._y * l;
  573. this._z = this._z * l;
  574. this._w = this._w * l;
  575. }
  576. return this;
  577. },
  578. multiply: function ( q, p ) {
  579. if ( p !== undefined ) {
  580. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  581. return this.multiplyQuaternions( q, p );
  582. }
  583. return this.multiplyQuaternions( this, q );
  584. },
  585. multiplyQuaternions: function ( a, b ) {
  586. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  587. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  588. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  589. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  590. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  591. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  592. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  593. this._updateEuler();
  594. return this;
  595. },
  596. multiplyVector3: function ( vector ) {
  597. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  598. return vector.applyQuaternion( this );
  599. },
  600. slerp: function ( qb, t ) {
  601. var x = this._x, y = this._y, z = this._z, w = this._w;
  602. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  603. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  604. if ( cosHalfTheta < 0 ) {
  605. this._w = -qb._w;
  606. this._x = -qb._x;
  607. this._y = -qb._y;
  608. this._z = -qb._z;
  609. cosHalfTheta = -cosHalfTheta;
  610. } else {
  611. this.copy( qb );
  612. }
  613. if ( cosHalfTheta >= 1.0 ) {
  614. this._w = w;
  615. this._x = x;
  616. this._y = y;
  617. this._z = z;
  618. return this;
  619. }
  620. var halfTheta = Math.acos( cosHalfTheta );
  621. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  622. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  623. this._w = 0.5 * ( w + this._w );
  624. this._x = 0.5 * ( x + this._x );
  625. this._y = 0.5 * ( y + this._y );
  626. this._z = 0.5 * ( z + this._z );
  627. return this;
  628. }
  629. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  630. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  631. this._w = ( w * ratioA + this._w * ratioB );
  632. this._x = ( x * ratioA + this._x * ratioB );
  633. this._y = ( y * ratioA + this._y * ratioB );
  634. this._z = ( z * ratioA + this._z * ratioB );
  635. this._updateEuler();
  636. return this;
  637. },
  638. equals: function ( quaternion ) {
  639. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  640. },
  641. fromArray: function ( array ) {
  642. this._x = array[ 0 ];
  643. this._y = array[ 1 ];
  644. this._z = array[ 2 ];
  645. this._w = array[ 3 ];
  646. this._updateEuler();
  647. return this;
  648. },
  649. toArray: function () {
  650. return [ this._x, this._y, this._z, this._w ];
  651. },
  652. clone: function () {
  653. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  654. }
  655. };
  656. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  657. return qm.copy( qa ).slerp( qb, t );
  658. }
  659. /**
  660. * @author mrdoob / http://mrdoob.com/
  661. * @author philogb / http://blog.thejit.org/
  662. * @author egraether / http://egraether.com/
  663. * @author zz85 / http://www.lab4games.net/zz85/blog
  664. */
  665. THREE.Vector2 = function ( x, y ) {
  666. this.x = x || 0;
  667. this.y = y || 0;
  668. };
  669. THREE.Vector2.prototype = {
  670. constructor: THREE.Vector2,
  671. set: function ( x, y ) {
  672. this.x = x;
  673. this.y = y;
  674. return this;
  675. },
  676. setX: function ( x ) {
  677. this.x = x;
  678. return this;
  679. },
  680. setY: function ( y ) {
  681. this.y = y;
  682. return this;
  683. },
  684. setComponent: function ( index, value ) {
  685. switch ( index ) {
  686. case 0: this.x = value; break;
  687. case 1: this.y = value; break;
  688. default: throw new Error( "index is out of range: " + index );
  689. }
  690. },
  691. getComponent: function ( index ) {
  692. switch ( index ) {
  693. case 0: return this.x;
  694. case 1: return this.y;
  695. default: throw new Error( "index is out of range: " + index );
  696. }
  697. },
  698. copy: function ( v ) {
  699. this.x = v.x;
  700. this.y = v.y;
  701. return this;
  702. },
  703. add: function ( v, w ) {
  704. if ( w !== undefined ) {
  705. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  706. return this.addVectors( v, w );
  707. }
  708. this.x += v.x;
  709. this.y += v.y;
  710. return this;
  711. },
  712. addVectors: function ( a, b ) {
  713. this.x = a.x + b.x;
  714. this.y = a.y + b.y;
  715. return this;
  716. },
  717. addScalar: function ( s ) {
  718. this.x += s;
  719. this.y += s;
  720. return this;
  721. },
  722. sub: function ( v, w ) {
  723. if ( w !== undefined ) {
  724. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  725. return this.subVectors( v, w );
  726. }
  727. this.x -= v.x;
  728. this.y -= v.y;
  729. return this;
  730. },
  731. subVectors: function ( a, b ) {
  732. this.x = a.x - b.x;
  733. this.y = a.y - b.y;
  734. return this;
  735. },
  736. multiplyScalar: function ( s ) {
  737. this.x *= s;
  738. this.y *= s;
  739. return this;
  740. },
  741. divideScalar: function ( scalar ) {
  742. if ( scalar !== 0 ) {
  743. var invScalar = 1 / scalar;
  744. this.x *= invScalar;
  745. this.y *= invScalar;
  746. } else {
  747. this.x = 0;
  748. this.y = 0;
  749. }
  750. return this;
  751. },
  752. min: function ( v ) {
  753. if ( this.x > v.x ) {
  754. this.x = v.x;
  755. }
  756. if ( this.y > v.y ) {
  757. this.y = v.y;
  758. }
  759. return this;
  760. },
  761. max: function ( v ) {
  762. if ( this.x < v.x ) {
  763. this.x = v.x;
  764. }
  765. if ( this.y < v.y ) {
  766. this.y = v.y;
  767. }
  768. return this;
  769. },
  770. clamp: function ( min, max ) {
  771. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  772. if ( this.x < min.x ) {
  773. this.x = min.x;
  774. } else if ( this.x > max.x ) {
  775. this.x = max.x;
  776. }
  777. if ( this.y < min.y ) {
  778. this.y = min.y;
  779. } else if ( this.y > max.y ) {
  780. this.y = max.y;
  781. }
  782. return this;
  783. },
  784. clampScalar: ( function () {
  785. var min, max;
  786. return function ( minVal, maxVal ) {
  787. if ( min === undefined ) {
  788. min = new THREE.Vector2();
  789. max = new THREE.Vector2();
  790. }
  791. min.set( minVal, minVal );
  792. max.set( maxVal, maxVal );
  793. return this.clamp( min, max );
  794. };
  795. } )(),
  796. floor: function () {
  797. this.x = Math.floor( this.x );
  798. this.y = Math.floor( this.y );
  799. return this;
  800. },
  801. ceil: function () {
  802. this.x = Math.ceil( this.x );
  803. this.y = Math.ceil( this.y );
  804. return this;
  805. },
  806. round: function () {
  807. this.x = Math.round( this.x );
  808. this.y = Math.round( this.y );
  809. return this;
  810. },
  811. roundToZero: function () {
  812. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  813. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  814. return this;
  815. },
  816. negate: function () {
  817. return this.multiplyScalar( - 1 );
  818. },
  819. dot: function ( v ) {
  820. return this.x * v.x + this.y * v.y;
  821. },
  822. lengthSq: function () {
  823. return this.x * this.x + this.y * this.y;
  824. },
  825. length: function () {
  826. return Math.sqrt( this.x * this.x + this.y * this.y );
  827. },
  828. normalize: function () {
  829. return this.divideScalar( this.length() );
  830. },
  831. distanceTo: function ( v ) {
  832. return Math.sqrt( this.distanceToSquared( v ) );
  833. },
  834. distanceToSquared: function ( v ) {
  835. var dx = this.x - v.x, dy = this.y - v.y;
  836. return dx * dx + dy * dy;
  837. },
  838. setLength: function ( l ) {
  839. var oldLength = this.length();
  840. if ( oldLength !== 0 && l !== oldLength ) {
  841. this.multiplyScalar( l / oldLength );
  842. }
  843. return this;
  844. },
  845. lerp: function ( v, alpha ) {
  846. this.x += ( v.x - this.x ) * alpha;
  847. this.y += ( v.y - this.y ) * alpha;
  848. return this;
  849. },
  850. equals: function( v ) {
  851. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  852. },
  853. fromArray: function ( array ) {
  854. this.x = array[ 0 ];
  855. this.y = array[ 1 ];
  856. return this;
  857. },
  858. toArray: function () {
  859. return [ this.x, this.y ];
  860. },
  861. clone: function () {
  862. return new THREE.Vector2( this.x, this.y );
  863. }
  864. };
  865. /**
  866. * @author mrdoob / http://mrdoob.com/
  867. * @author *kile / http://kile.stravaganza.org/
  868. * @author philogb / http://blog.thejit.org/
  869. * @author mikael emtinger / http://gomo.se/
  870. * @author egraether / http://egraether.com/
  871. * @author WestLangley / http://github.com/WestLangley
  872. */
  873. THREE.Vector3 = function ( x, y, z ) {
  874. this.x = x || 0;
  875. this.y = y || 0;
  876. this.z = z || 0;
  877. };
  878. THREE.Vector3.prototype = {
  879. constructor: THREE.Vector3,
  880. set: function ( x, y, z ) {
  881. this.x = x;
  882. this.y = y;
  883. this.z = z;
  884. return this;
  885. },
  886. setX: function ( x ) {
  887. this.x = x;
  888. return this;
  889. },
  890. setY: function ( y ) {
  891. this.y = y;
  892. return this;
  893. },
  894. setZ: function ( z ) {
  895. this.z = z;
  896. return this;
  897. },
  898. setComponent: function ( index, value ) {
  899. switch ( index ) {
  900. case 0: this.x = value; break;
  901. case 1: this.y = value; break;
  902. case 2: this.z = value; break;
  903. default: throw new Error( "index is out of range: " + index );
  904. }
  905. },
  906. getComponent: function ( index ) {
  907. switch ( index ) {
  908. case 0: return this.x;
  909. case 1: return this.y;
  910. case 2: return this.z;
  911. default: throw new Error( "index is out of range: " + index );
  912. }
  913. },
  914. copy: function ( v ) {
  915. this.x = v.x;
  916. this.y = v.y;
  917. this.z = v.z;
  918. return this;
  919. },
  920. add: function ( v, w ) {
  921. if ( w !== undefined ) {
  922. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  923. return this.addVectors( v, w );
  924. }
  925. this.x += v.x;
  926. this.y += v.y;
  927. this.z += v.z;
  928. return this;
  929. },
  930. addScalar: function ( s ) {
  931. this.x += s;
  932. this.y += s;
  933. this.z += s;
  934. return this;
  935. },
  936. addVectors: function ( a, b ) {
  937. this.x = a.x + b.x;
  938. this.y = a.y + b.y;
  939. this.z = a.z + b.z;
  940. return this;
  941. },
  942. sub: function ( v, w ) {
  943. if ( w !== undefined ) {
  944. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  945. return this.subVectors( v, w );
  946. }
  947. this.x -= v.x;
  948. this.y -= v.y;
  949. this.z -= v.z;
  950. return this;
  951. },
  952. subVectors: function ( a, b ) {
  953. this.x = a.x - b.x;
  954. this.y = a.y - b.y;
  955. this.z = a.z - b.z;
  956. return this;
  957. },
  958. multiply: function ( v, w ) {
  959. if ( w !== undefined ) {
  960. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  961. return this.multiplyVectors( v, w );
  962. }
  963. this.x *= v.x;
  964. this.y *= v.y;
  965. this.z *= v.z;
  966. return this;
  967. },
  968. multiplyScalar: function ( scalar ) {
  969. this.x *= scalar;
  970. this.y *= scalar;
  971. this.z *= scalar;
  972. return this;
  973. },
  974. multiplyVectors: function ( a, b ) {
  975. this.x = a.x * b.x;
  976. this.y = a.y * b.y;
  977. this.z = a.z * b.z;
  978. return this;
  979. },
  980. applyEuler: function () {
  981. var quaternion;
  982. return function ( euler ) {
  983. if ( euler instanceof THREE.Euler === false ) {
  984. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  985. }
  986. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  987. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  988. return this;
  989. };
  990. }(),
  991. applyAxisAngle: function () {
  992. var quaternion;
  993. return function ( axis, angle ) {
  994. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  995. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  996. return this;
  997. };
  998. }(),
  999. applyMatrix3: function ( m ) {
  1000. var x = this.x;
  1001. var y = this.y;
  1002. var z = this.z;
  1003. var e = m.elements;
  1004. this.x = e[0] * x + e[3] * y + e[6] * z;
  1005. this.y = e[1] * x + e[4] * y + e[7] * z;
  1006. this.z = e[2] * x + e[5] * y + e[8] * z;
  1007. return this;
  1008. },
  1009. applyMatrix4: function ( m ) {
  1010. // input: THREE.Matrix4 affine matrix
  1011. var x = this.x, y = this.y, z = this.z;
  1012. var e = m.elements;
  1013. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  1014. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  1015. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  1016. return this;
  1017. },
  1018. applyProjection: function ( m ) {
  1019. // input: THREE.Matrix4 projection matrix
  1020. var x = this.x, y = this.y, z = this.z;
  1021. var e = m.elements;
  1022. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  1023. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  1024. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  1025. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  1026. return this;
  1027. },
  1028. applyQuaternion: function ( q ) {
  1029. var x = this.x;
  1030. var y = this.y;
  1031. var z = this.z;
  1032. var qx = q.x;
  1033. var qy = q.y;
  1034. var qz = q.z;
  1035. var qw = q.w;
  1036. // calculate quat * vector
  1037. var ix = qw * x + qy * z - qz * y;
  1038. var iy = qw * y + qz * x - qx * z;
  1039. var iz = qw * z + qx * y - qy * x;
  1040. var iw = -qx * x - qy * y - qz * z;
  1041. // calculate result * inverse quat
  1042. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1043. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1044. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1045. return this;
  1046. },
  1047. transformDirection: function ( m ) {
  1048. // input: THREE.Matrix4 affine matrix
  1049. // vector interpreted as a direction
  1050. var x = this.x, y = this.y, z = this.z;
  1051. var e = m.elements;
  1052. this.x = e[0] * x + e[4] * y + e[8] * z;
  1053. this.y = e[1] * x + e[5] * y + e[9] * z;
  1054. this.z = e[2] * x + e[6] * y + e[10] * z;
  1055. this.normalize();
  1056. return this;
  1057. },
  1058. divide: function ( v ) {
  1059. this.x /= v.x;
  1060. this.y /= v.y;
  1061. this.z /= v.z;
  1062. return this;
  1063. },
  1064. divideScalar: function ( scalar ) {
  1065. if ( scalar !== 0 ) {
  1066. var invScalar = 1 / scalar;
  1067. this.x *= invScalar;
  1068. this.y *= invScalar;
  1069. this.z *= invScalar;
  1070. } else {
  1071. this.x = 0;
  1072. this.y = 0;
  1073. this.z = 0;
  1074. }
  1075. return this;
  1076. },
  1077. min: function ( v ) {
  1078. if ( this.x > v.x ) {
  1079. this.x = v.x;
  1080. }
  1081. if ( this.y > v.y ) {
  1082. this.y = v.y;
  1083. }
  1084. if ( this.z > v.z ) {
  1085. this.z = v.z;
  1086. }
  1087. return this;
  1088. },
  1089. max: function ( v ) {
  1090. if ( this.x < v.x ) {
  1091. this.x = v.x;
  1092. }
  1093. if ( this.y < v.y ) {
  1094. this.y = v.y;
  1095. }
  1096. if ( this.z < v.z ) {
  1097. this.z = v.z;
  1098. }
  1099. return this;
  1100. },
  1101. clamp: function ( min, max ) {
  1102. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1103. if ( this.x < min.x ) {
  1104. this.x = min.x;
  1105. } else if ( this.x > max.x ) {
  1106. this.x = max.x;
  1107. }
  1108. if ( this.y < min.y ) {
  1109. this.y = min.y;
  1110. } else if ( this.y > max.y ) {
  1111. this.y = max.y;
  1112. }
  1113. if ( this.z < min.z ) {
  1114. this.z = min.z;
  1115. } else if ( this.z > max.z ) {
  1116. this.z = max.z;
  1117. }
  1118. return this;
  1119. },
  1120. clampScalar: ( function () {
  1121. var min, max;
  1122. return function ( minVal, maxVal ) {
  1123. if ( min === undefined ) {
  1124. min = new THREE.Vector3();
  1125. max = new THREE.Vector3();
  1126. }
  1127. min.set( minVal, minVal, minVal );
  1128. max.set( maxVal, maxVal, maxVal );
  1129. return this.clamp( min, max );
  1130. };
  1131. } )(),
  1132. floor: function () {
  1133. this.x = Math.floor( this.x );
  1134. this.y = Math.floor( this.y );
  1135. this.z = Math.floor( this.z );
  1136. return this;
  1137. },
  1138. ceil: function () {
  1139. this.x = Math.ceil( this.x );
  1140. this.y = Math.ceil( this.y );
  1141. this.z = Math.ceil( this.z );
  1142. return this;
  1143. },
  1144. round: function () {
  1145. this.x = Math.round( this.x );
  1146. this.y = Math.round( this.y );
  1147. this.z = Math.round( this.z );
  1148. return this;
  1149. },
  1150. roundToZero: function () {
  1151. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1152. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1153. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1154. return this;
  1155. },
  1156. negate: function () {
  1157. return this.multiplyScalar( - 1 );
  1158. },
  1159. dot: function ( v ) {
  1160. return this.x * v.x + this.y * v.y + this.z * v.z;
  1161. },
  1162. lengthSq: function () {
  1163. return this.x * this.x + this.y * this.y + this.z * this.z;
  1164. },
  1165. length: function () {
  1166. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1167. },
  1168. lengthManhattan: function () {
  1169. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1170. },
  1171. normalize: function () {
  1172. return this.divideScalar( this.length() );
  1173. },
  1174. setLength: function ( l ) {
  1175. var oldLength = this.length();
  1176. if ( oldLength !== 0 && l !== oldLength ) {
  1177. this.multiplyScalar( l / oldLength );
  1178. }
  1179. return this;
  1180. },
  1181. lerp: function ( v, alpha ) {
  1182. this.x += ( v.x - this.x ) * alpha;
  1183. this.y += ( v.y - this.y ) * alpha;
  1184. this.z += ( v.z - this.z ) * alpha;
  1185. return this;
  1186. },
  1187. cross: function ( v, w ) {
  1188. if ( w !== undefined ) {
  1189. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1190. return this.crossVectors( v, w );
  1191. }
  1192. var x = this.x, y = this.y, z = this.z;
  1193. this.x = y * v.z - z * v.y;
  1194. this.y = z * v.x - x * v.z;
  1195. this.z = x * v.y - y * v.x;
  1196. return this;
  1197. },
  1198. crossVectors: function ( a, b ) {
  1199. var ax = a.x, ay = a.y, az = a.z;
  1200. var bx = b.x, by = b.y, bz = b.z;
  1201. this.x = ay * bz - az * by;
  1202. this.y = az * bx - ax * bz;
  1203. this.z = ax * by - ay * bx;
  1204. return this;
  1205. },
  1206. projectOnVector: function () {
  1207. var v1, dot;
  1208. return function ( vector ) {
  1209. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1210. v1.copy( vector ).normalize();
  1211. dot = this.dot( v1 );
  1212. return this.copy( v1 ).multiplyScalar( dot );
  1213. };
  1214. }(),
  1215. projectOnPlane: function () {
  1216. var v1;
  1217. return function ( planeNormal ) {
  1218. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1219. v1.copy( this ).projectOnVector( planeNormal );
  1220. return this.sub( v1 );
  1221. }
  1222. }(),
  1223. reflect: function () {
  1224. // reflect incident vector off plane orthogonal to normal
  1225. // normal is assumed to have unit length
  1226. var v1;
  1227. return function ( normal ) {
  1228. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1229. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1230. }
  1231. }(),
  1232. angleTo: function ( v ) {
  1233. var theta = this.dot( v ) / ( this.length() * v.length() );
  1234. // clamp, to handle numerical problems
  1235. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1236. },
  1237. distanceTo: function ( v ) {
  1238. return Math.sqrt( this.distanceToSquared( v ) );
  1239. },
  1240. distanceToSquared: function ( v ) {
  1241. var dx = this.x - v.x;
  1242. var dy = this.y - v.y;
  1243. var dz = this.z - v.z;
  1244. return dx * dx + dy * dy + dz * dz;
  1245. },
  1246. setEulerFromRotationMatrix: function ( m, order ) {
  1247. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1248. },
  1249. setEulerFromQuaternion: function ( q, order ) {
  1250. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1251. },
  1252. getPositionFromMatrix: function ( m ) {
  1253. console.warn( "DEPRECATED: Vector3\'s .getPositionFromMatrix() has been renamed to .setFromMatrixPosition(). Please update your code." );
  1254. return this.setFromMatrixPosition( m );
  1255. },
  1256. getScaleFromMatrix: function ( m ) {
  1257. console.warn( "DEPRECATED: Vector3\'s .getScaleFromMatrix() has been renamed to .setFromMatrixScale(). Please update your code." );
  1258. return this.setFromMatrixScale( m );
  1259. },
  1260. getColumnFromMatrix: function ( index, matrix ) {
  1261. console.warn( "DEPRECATED: Vector3\'s .getColumnFromMatrix() has been renamed to .setFromMatrixColumn(). Please update your code." );
  1262. return this.setFromMatrixColumn( index, matrix );
  1263. },
  1264. setFromMatrixPosition: function ( m ) {
  1265. this.x = m.elements[ 12 ];
  1266. this.y = m.elements[ 13 ];
  1267. this.z = m.elements[ 14 ];
  1268. return this;
  1269. },
  1270. setFromMatrixScale: function ( m ) {
  1271. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1272. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1273. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1274. this.x = sx;
  1275. this.y = sy;
  1276. this.z = sz;
  1277. return this;
  1278. },
  1279. setFromMatrixColumn: function ( index, matrix ) {
  1280. var offset = index * 4;
  1281. var me = matrix.elements;
  1282. this.x = me[ offset ];
  1283. this.y = me[ offset + 1 ];
  1284. this.z = me[ offset + 2 ];
  1285. return this;
  1286. },
  1287. equals: function ( v ) {
  1288. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1289. },
  1290. fromArray: function ( array ) {
  1291. this.x = array[ 0 ];
  1292. this.y = array[ 1 ];
  1293. this.z = array[ 2 ];
  1294. return this;
  1295. },
  1296. toArray: function () {
  1297. return [ this.x, this.y, this.z ];
  1298. },
  1299. clone: function () {
  1300. return new THREE.Vector3( this.x, this.y, this.z );
  1301. }
  1302. };
  1303. /**
  1304. * @author supereggbert / http://www.paulbrunt.co.uk/
  1305. * @author philogb / http://blog.thejit.org/
  1306. * @author mikael emtinger / http://gomo.se/
  1307. * @author egraether / http://egraether.com/
  1308. * @author WestLangley / http://github.com/WestLangley
  1309. */
  1310. THREE.Vector4 = function ( x, y, z, w ) {
  1311. this.x = x || 0;
  1312. this.y = y || 0;
  1313. this.z = z || 0;
  1314. this.w = ( w !== undefined ) ? w : 1;
  1315. };
  1316. THREE.Vector4.prototype = {
  1317. constructor: THREE.Vector4,
  1318. set: function ( x, y, z, w ) {
  1319. this.x = x;
  1320. this.y = y;
  1321. this.z = z;
  1322. this.w = w;
  1323. return this;
  1324. },
  1325. setX: function ( x ) {
  1326. this.x = x;
  1327. return this;
  1328. },
  1329. setY: function ( y ) {
  1330. this.y = y;
  1331. return this;
  1332. },
  1333. setZ: function ( z ) {
  1334. this.z = z;
  1335. return this;
  1336. },
  1337. setW: function ( w ) {
  1338. this.w = w;
  1339. return this;
  1340. },
  1341. setComponent: function ( index, value ) {
  1342. switch ( index ) {
  1343. case 0: this.x = value; break;
  1344. case 1: this.y = value; break;
  1345. case 2: this.z = value; break;
  1346. case 3: this.w = value; break;
  1347. default: throw new Error( "index is out of range: " + index );
  1348. }
  1349. },
  1350. getComponent: function ( index ) {
  1351. switch ( index ) {
  1352. case 0: return this.x;
  1353. case 1: return this.y;
  1354. case 2: return this.z;
  1355. case 3: return this.w;
  1356. default: throw new Error( "index is out of range: " + index );
  1357. }
  1358. },
  1359. copy: function ( v ) {
  1360. this.x = v.x;
  1361. this.y = v.y;
  1362. this.z = v.z;
  1363. this.w = ( v.w !== undefined ) ? v.w : 1;
  1364. return this;
  1365. },
  1366. add: function ( v, w ) {
  1367. if ( w !== undefined ) {
  1368. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1369. return this.addVectors( v, w );
  1370. }
  1371. this.x += v.x;
  1372. this.y += v.y;
  1373. this.z += v.z;
  1374. this.w += v.w;
  1375. return this;
  1376. },
  1377. addScalar: function ( s ) {
  1378. this.x += s;
  1379. this.y += s;
  1380. this.z += s;
  1381. this.w += s;
  1382. return this;
  1383. },
  1384. addVectors: function ( a, b ) {
  1385. this.x = a.x + b.x;
  1386. this.y = a.y + b.y;
  1387. this.z = a.z + b.z;
  1388. this.w = a.w + b.w;
  1389. return this;
  1390. },
  1391. sub: function ( v, w ) {
  1392. if ( w !== undefined ) {
  1393. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1394. return this.subVectors( v, w );
  1395. }
  1396. this.x -= v.x;
  1397. this.y -= v.y;
  1398. this.z -= v.z;
  1399. this.w -= v.w;
  1400. return this;
  1401. },
  1402. subVectors: function ( a, b ) {
  1403. this.x = a.x - b.x;
  1404. this.y = a.y - b.y;
  1405. this.z = a.z - b.z;
  1406. this.w = a.w - b.w;
  1407. return this;
  1408. },
  1409. multiplyScalar: function ( scalar ) {
  1410. this.x *= scalar;
  1411. this.y *= scalar;
  1412. this.z *= scalar;
  1413. this.w *= scalar;
  1414. return this;
  1415. },
  1416. applyMatrix4: function ( m ) {
  1417. var x = this.x;
  1418. var y = this.y;
  1419. var z = this.z;
  1420. var w = this.w;
  1421. var e = m.elements;
  1422. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1423. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1424. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1425. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1426. return this;
  1427. },
  1428. divideScalar: function ( scalar ) {
  1429. if ( scalar !== 0 ) {
  1430. var invScalar = 1 / scalar;
  1431. this.x *= invScalar;
  1432. this.y *= invScalar;
  1433. this.z *= invScalar;
  1434. this.w *= invScalar;
  1435. } else {
  1436. this.x = 0;
  1437. this.y = 0;
  1438. this.z = 0;
  1439. this.w = 1;
  1440. }
  1441. return this;
  1442. },
  1443. setAxisAngleFromQuaternion: function ( q ) {
  1444. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1445. // q is assumed to be normalized
  1446. this.w = 2 * Math.acos( q.w );
  1447. var s = Math.sqrt( 1 - q.w * q.w );
  1448. if ( s < 0.0001 ) {
  1449. this.x = 1;
  1450. this.y = 0;
  1451. this.z = 0;
  1452. } else {
  1453. this.x = q.x / s;
  1454. this.y = q.y / s;
  1455. this.z = q.z / s;
  1456. }
  1457. return this;
  1458. },
  1459. setAxisAngleFromRotationMatrix: function ( m ) {
  1460. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1461. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1462. var angle, x, y, z, // variables for result
  1463. epsilon = 0.01, // margin to allow for rounding errors
  1464. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1465. te = m.elements,
  1466. m11 = te[0], m12 = te[4], m13 = te[8],
  1467. m21 = te[1], m22 = te[5], m23 = te[9],
  1468. m31 = te[2], m32 = te[6], m33 = te[10];
  1469. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1470. && ( Math.abs( m13 - m31 ) < epsilon )
  1471. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1472. // singularity found
  1473. // first check for identity matrix which must have +1 for all terms
  1474. // in leading diagonal and zero in other terms
  1475. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1476. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1477. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1478. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1479. // this singularity is identity matrix so angle = 0
  1480. this.set( 1, 0, 0, 0 );
  1481. return this; // zero angle, arbitrary axis
  1482. }
  1483. // otherwise this singularity is angle = 180
  1484. angle = Math.PI;
  1485. var xx = ( m11 + 1 ) / 2;
  1486. var yy = ( m22 + 1 ) / 2;
  1487. var zz = ( m33 + 1 ) / 2;
  1488. var xy = ( m12 + m21 ) / 4;
  1489. var xz = ( m13 + m31 ) / 4;
  1490. var yz = ( m23 + m32 ) / 4;
  1491. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1492. if ( xx < epsilon ) {
  1493. x = 0;
  1494. y = 0.707106781;
  1495. z = 0.707106781;
  1496. } else {
  1497. x = Math.sqrt( xx );
  1498. y = xy / x;
  1499. z = xz / x;
  1500. }
  1501. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1502. if ( yy < epsilon ) {
  1503. x = 0.707106781;
  1504. y = 0;
  1505. z = 0.707106781;
  1506. } else {
  1507. y = Math.sqrt( yy );
  1508. x = xy / y;
  1509. z = yz / y;
  1510. }
  1511. } else { // m33 is the largest diagonal term so base result on this
  1512. if ( zz < epsilon ) {
  1513. x = 0.707106781;
  1514. y = 0.707106781;
  1515. z = 0;
  1516. } else {
  1517. z = Math.sqrt( zz );
  1518. x = xz / z;
  1519. y = yz / z;
  1520. }
  1521. }
  1522. this.set( x, y, z, angle );
  1523. return this; // return 180 deg rotation
  1524. }
  1525. // as we have reached here there are no singularities so we can handle normally
  1526. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1527. + ( m13 - m31 ) * ( m13 - m31 )
  1528. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1529. if ( Math.abs( s ) < 0.001 ) s = 1;
  1530. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1531. // caught by singularity test above, but I've left it in just in case
  1532. this.x = ( m32 - m23 ) / s;
  1533. this.y = ( m13 - m31 ) / s;
  1534. this.z = ( m21 - m12 ) / s;
  1535. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1536. return this;
  1537. },
  1538. min: function ( v ) {
  1539. if ( this.x > v.x ) {
  1540. this.x = v.x;
  1541. }
  1542. if ( this.y > v.y ) {
  1543. this.y = v.y;
  1544. }
  1545. if ( this.z > v.z ) {
  1546. this.z = v.z;
  1547. }
  1548. if ( this.w > v.w ) {
  1549. this.w = v.w;
  1550. }
  1551. return this;
  1552. },
  1553. max: function ( v ) {
  1554. if ( this.x < v.x ) {
  1555. this.x = v.x;
  1556. }
  1557. if ( this.y < v.y ) {
  1558. this.y = v.y;
  1559. }
  1560. if ( this.z < v.z ) {
  1561. this.z = v.z;
  1562. }
  1563. if ( this.w < v.w ) {
  1564. this.w = v.w;
  1565. }
  1566. return this;
  1567. },
  1568. clamp: function ( min, max ) {
  1569. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1570. if ( this.x < min.x ) {
  1571. this.x = min.x;
  1572. } else if ( this.x > max.x ) {
  1573. this.x = max.x;
  1574. }
  1575. if ( this.y < min.y ) {
  1576. this.y = min.y;
  1577. } else if ( this.y > max.y ) {
  1578. this.y = max.y;
  1579. }
  1580. if ( this.z < min.z ) {
  1581. this.z = min.z;
  1582. } else if ( this.z > max.z ) {
  1583. this.z = max.z;
  1584. }
  1585. if ( this.w < min.w ) {
  1586. this.w = min.w;
  1587. } else if ( this.w > max.w ) {
  1588. this.w = max.w;
  1589. }
  1590. return this;
  1591. },
  1592. clampScalar: ( function () {
  1593. var min, max;
  1594. return function ( minVal, maxVal ) {
  1595. if ( min === undefined ) {
  1596. min = new THREE.Vector4();
  1597. max = new THREE.Vector4();
  1598. }
  1599. min.set( minVal, minVal, minVal, minVal );
  1600. max.set( maxVal, maxVal, maxVal, maxVal );
  1601. return this.clamp( min, max );
  1602. };
  1603. } )(),
  1604. floor: function () {
  1605. this.x = Math.floor( this.x );
  1606. this.y = Math.floor( this.y );
  1607. this.z = Math.floor( this.z );
  1608. this.w = Math.floor( this.w );
  1609. return this;
  1610. },
  1611. ceil: function () {
  1612. this.x = Math.ceil( this.x );
  1613. this.y = Math.ceil( this.y );
  1614. this.z = Math.ceil( this.z );
  1615. this.w = Math.ceil( this.w );
  1616. return this;
  1617. },
  1618. round: function () {
  1619. this.x = Math.round( this.x );
  1620. this.y = Math.round( this.y );
  1621. this.z = Math.round( this.z );
  1622. this.w = Math.round( this.w );
  1623. return this;
  1624. },
  1625. roundToZero: function () {
  1626. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1627. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1628. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1629. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1630. return this;
  1631. },
  1632. negate: function () {
  1633. return this.multiplyScalar( -1 );
  1634. },
  1635. dot: function ( v ) {
  1636. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1637. },
  1638. lengthSq: function () {
  1639. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1640. },
  1641. length: function () {
  1642. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1643. },
  1644. lengthManhattan: function () {
  1645. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1646. },
  1647. normalize: function () {
  1648. return this.divideScalar( this.length() );
  1649. },
  1650. setLength: function ( l ) {
  1651. var oldLength = this.length();
  1652. if ( oldLength !== 0 && l !== oldLength ) {
  1653. this.multiplyScalar( l / oldLength );
  1654. }
  1655. return this;
  1656. },
  1657. lerp: function ( v, alpha ) {
  1658. this.x += ( v.x - this.x ) * alpha;
  1659. this.y += ( v.y - this.y ) * alpha;
  1660. this.z += ( v.z - this.z ) * alpha;
  1661. this.w += ( v.w - this.w ) * alpha;
  1662. return this;
  1663. },
  1664. equals: function ( v ) {
  1665. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1666. },
  1667. fromArray: function ( array ) {
  1668. this.x = array[ 0 ];
  1669. this.y = array[ 1 ];
  1670. this.z = array[ 2 ];
  1671. this.w = array[ 3 ];
  1672. return this;
  1673. },
  1674. toArray: function () {
  1675. return [ this.x, this.y, this.z, this.w ];
  1676. },
  1677. clone: function () {
  1678. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1679. }
  1680. };
  1681. /**
  1682. * @author mrdoob / http://mrdoob.com/
  1683. * @author WestLangley / http://github.com/WestLangley
  1684. * @author bhouston / http://exocortex.com
  1685. */
  1686. THREE.Euler = function ( x, y, z, order ) {
  1687. this._x = x || 0;
  1688. this._y = y || 0;
  1689. this._z = z || 0;
  1690. this._order = order || THREE.Euler.DefaultOrder;
  1691. };
  1692. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1693. THREE.Euler.DefaultOrder = 'XYZ';
  1694. THREE.Euler.prototype = {
  1695. constructor: THREE.Euler,
  1696. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1697. _quaternion: undefined,
  1698. _updateQuaternion: function () {
  1699. if ( this._quaternion !== undefined ) {
  1700. this._quaternion.setFromEuler( this, false );
  1701. }
  1702. },
  1703. get x () {
  1704. return this._x;
  1705. },
  1706. set x ( value ) {
  1707. this._x = value;
  1708. this._updateQuaternion();
  1709. },
  1710. get y () {
  1711. return this._y;
  1712. },
  1713. set y ( value ) {
  1714. this._y = value;
  1715. this._updateQuaternion();
  1716. },
  1717. get z () {
  1718. return this._z;
  1719. },
  1720. set z ( value ) {
  1721. this._z = value;
  1722. this._updateQuaternion();
  1723. },
  1724. get order () {
  1725. return this._order;
  1726. },
  1727. set order ( value ) {
  1728. this._order = value;
  1729. this._updateQuaternion();
  1730. },
  1731. set: function ( x, y, z, order ) {
  1732. this._x = x;
  1733. this._y = y;
  1734. this._z = z;
  1735. this._order = order || this._order;
  1736. this._updateQuaternion();
  1737. return this;
  1738. },
  1739. copy: function ( euler ) {
  1740. this._x = euler._x;
  1741. this._y = euler._y;
  1742. this._z = euler._z;
  1743. this._order = euler._order;
  1744. this._updateQuaternion();
  1745. return this;
  1746. },
  1747. setFromRotationMatrix: function ( m, order ) {
  1748. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1749. // clamp, to handle numerical problems
  1750. function clamp( x ) {
  1751. return Math.min( Math.max( x, -1 ), 1 );
  1752. }
  1753. var te = m.elements;
  1754. var m11 = te[0], m12 = te[4], m13 = te[8];
  1755. var m21 = te[1], m22 = te[5], m23 = te[9];
  1756. var m31 = te[2], m32 = te[6], m33 = te[10];
  1757. order = order || this._order;
  1758. if ( order === 'XYZ' ) {
  1759. this._y = Math.asin( clamp( m13 ) );
  1760. if ( Math.abs( m13 ) < 0.99999 ) {
  1761. this._x = Math.atan2( - m23, m33 );
  1762. this._z = Math.atan2( - m12, m11 );
  1763. } else {
  1764. this._x = Math.atan2( m32, m22 );
  1765. this._z = 0;
  1766. }
  1767. } else if ( order === 'YXZ' ) {
  1768. this._x = Math.asin( - clamp( m23 ) );
  1769. if ( Math.abs( m23 ) < 0.99999 ) {
  1770. this._y = Math.atan2( m13, m33 );
  1771. this._z = Math.atan2( m21, m22 );
  1772. } else {
  1773. this._y = Math.atan2( - m31, m11 );
  1774. this._z = 0;
  1775. }
  1776. } else if ( order === 'ZXY' ) {
  1777. this._x = Math.asin( clamp( m32 ) );
  1778. if ( Math.abs( m32 ) < 0.99999 ) {
  1779. this._y = Math.atan2( - m31, m33 );
  1780. this._z = Math.atan2( - m12, m22 );
  1781. } else {
  1782. this._y = 0;
  1783. this._z = Math.atan2( m21, m11 );
  1784. }
  1785. } else if ( order === 'ZYX' ) {
  1786. this._y = Math.asin( - clamp( m31 ) );
  1787. if ( Math.abs( m31 ) < 0.99999 ) {
  1788. this._x = Math.atan2( m32, m33 );
  1789. this._z = Math.atan2( m21, m11 );
  1790. } else {
  1791. this._x = 0;
  1792. this._z = Math.atan2( - m12, m22 );
  1793. }
  1794. } else if ( order === 'YZX' ) {
  1795. this._z = Math.asin( clamp( m21 ) );
  1796. if ( Math.abs( m21 ) < 0.99999 ) {
  1797. this._x = Math.atan2( - m23, m22 );
  1798. this._y = Math.atan2( - m31, m11 );
  1799. } else {
  1800. this._x = 0;
  1801. this._y = Math.atan2( m13, m33 );
  1802. }
  1803. } else if ( order === 'XZY' ) {
  1804. this._z = Math.asin( - clamp( m12 ) );
  1805. if ( Math.abs( m12 ) < 0.99999 ) {
  1806. this._x = Math.atan2( m32, m22 );
  1807. this._y = Math.atan2( m13, m11 );
  1808. } else {
  1809. this._x = Math.atan2( - m23, m33 );
  1810. this._y = 0;
  1811. }
  1812. } else {
  1813. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1814. }
  1815. this._order = order;
  1816. this._updateQuaternion();
  1817. return this;
  1818. },
  1819. setFromQuaternion: function ( q, order, update ) {
  1820. // q is assumed to be normalized
  1821. // clamp, to handle numerical problems
  1822. function clamp( x ) {
  1823. return Math.min( Math.max( x, -1 ), 1 );
  1824. }
  1825. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1826. var sqx = q.x * q.x;
  1827. var sqy = q.y * q.y;
  1828. var sqz = q.z * q.z;
  1829. var sqw = q.w * q.w;
  1830. order = order || this._order;
  1831. if ( order === 'XYZ' ) {
  1832. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1833. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1834. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1835. } else if ( order === 'YXZ' ) {
  1836. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1837. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1838. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1839. } else if ( order === 'ZXY' ) {
  1840. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1841. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1842. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1843. } else if ( order === 'ZYX' ) {
  1844. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1845. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1846. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1847. } else if ( order === 'YZX' ) {
  1848. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1849. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1850. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1851. } else if ( order === 'XZY' ) {
  1852. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1853. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1854. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1855. } else {
  1856. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1857. }
  1858. this._order = order;
  1859. if ( update !== false ) this._updateQuaternion();
  1860. return this;
  1861. },
  1862. reorder: function () {
  1863. // WARNING: this discards revolution information -bhouston
  1864. var q = new THREE.Quaternion();
  1865. return function ( newOrder ) {
  1866. q.setFromEuler( this );
  1867. this.setFromQuaternion( q, newOrder );
  1868. };
  1869. }(),
  1870. fromArray: function ( array ) {
  1871. this._x = array[ 0 ];
  1872. this._y = array[ 1 ];
  1873. this._z = array[ 2 ];
  1874. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1875. this._updateQuaternion();
  1876. return this;
  1877. },
  1878. toArray: function () {
  1879. return [ this._x, this._y, this._z, this._order ];
  1880. },
  1881. equals: function ( euler ) {
  1882. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1883. },
  1884. clone: function () {
  1885. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1886. }
  1887. };
  1888. /**
  1889. * @author bhouston / http://exocortex.com
  1890. */
  1891. THREE.Line3 = function ( start, end ) {
  1892. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1893. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1894. };
  1895. THREE.Line3.prototype = {
  1896. constructor: THREE.Line3,
  1897. set: function ( start, end ) {
  1898. this.start.copy( start );
  1899. this.end.copy( end );
  1900. return this;
  1901. },
  1902. copy: function ( line ) {
  1903. this.start.copy( line.start );
  1904. this.end.copy( line.end );
  1905. return this;
  1906. },
  1907. center: function ( optionalTarget ) {
  1908. var result = optionalTarget || new THREE.Vector3();
  1909. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1910. },
  1911. delta: function ( optionalTarget ) {
  1912. var result = optionalTarget || new THREE.Vector3();
  1913. return result.subVectors( this.end, this.start );
  1914. },
  1915. distanceSq: function () {
  1916. return this.start.distanceToSquared( this.end );
  1917. },
  1918. distance: function () {
  1919. return this.start.distanceTo( this.end );
  1920. },
  1921. at: function ( t, optionalTarget ) {
  1922. var result = optionalTarget || new THREE.Vector3();
  1923. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1924. },
  1925. closestPointToPointParameter: function() {
  1926. var startP = new THREE.Vector3();
  1927. var startEnd = new THREE.Vector3();
  1928. return function ( point, clampToLine ) {
  1929. startP.subVectors( point, this.start );
  1930. startEnd.subVectors( this.end, this.start );
  1931. var startEnd2 = startEnd.dot( startEnd );
  1932. var startEnd_startP = startEnd.dot( startP );
  1933. var t = startEnd_startP / startEnd2;
  1934. if ( clampToLine ) {
  1935. t = THREE.Math.clamp( t, 0, 1 );
  1936. }
  1937. return t;
  1938. };
  1939. }(),
  1940. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1941. var t = this.closestPointToPointParameter( point, clampToLine );
  1942. var result = optionalTarget || new THREE.Vector3();
  1943. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1944. },
  1945. applyMatrix4: function ( matrix ) {
  1946. this.start.applyMatrix4( matrix );
  1947. this.end.applyMatrix4( matrix );
  1948. return this;
  1949. },
  1950. equals: function ( line ) {
  1951. return line.start.equals( this.start ) && line.end.equals( this.end );
  1952. },
  1953. clone: function () {
  1954. return new THREE.Line3().copy( this );
  1955. }
  1956. };
  1957. /**
  1958. * @author bhouston / http://exocortex.com
  1959. */
  1960. THREE.Box2 = function ( min, max ) {
  1961. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1962. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1963. };
  1964. THREE.Box2.prototype = {
  1965. constructor: THREE.Box2,
  1966. set: function ( min, max ) {
  1967. this.min.copy( min );
  1968. this.max.copy( max );
  1969. return this;
  1970. },
  1971. setFromPoints: function ( points ) {
  1972. if ( points.length > 0 ) {
  1973. var point = points[ 0 ];
  1974. this.min.copy( point );
  1975. this.max.copy( point );
  1976. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1977. point = points[ i ];
  1978. if ( point.x < this.min.x ) {
  1979. this.min.x = point.x;
  1980. } else if ( point.x > this.max.x ) {
  1981. this.max.x = point.x;
  1982. }
  1983. if ( point.y < this.min.y ) {
  1984. this.min.y = point.y;
  1985. } else if ( point.y > this.max.y ) {
  1986. this.max.y = point.y;
  1987. }
  1988. }
  1989. } else {
  1990. this.makeEmpty();
  1991. }
  1992. return this;
  1993. },
  1994. setFromCenterAndSize: function () {
  1995. var v1 = new THREE.Vector2();
  1996. return function ( center, size ) {
  1997. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1998. this.min.copy( center ).sub( halfSize );
  1999. this.max.copy( center ).add( halfSize );
  2000. return this;
  2001. };
  2002. }(),
  2003. copy: function ( box ) {
  2004. this.min.copy( box.min );
  2005. this.max.copy( box.max );
  2006. return this;
  2007. },
  2008. makeEmpty: function () {
  2009. this.min.x = this.min.y = Infinity;
  2010. this.max.x = this.max.y = -Infinity;
  2011. return this;
  2012. },
  2013. empty: function () {
  2014. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2015. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2016. },
  2017. center: function ( optionalTarget ) {
  2018. var result = optionalTarget || new THREE.Vector2();
  2019. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2020. },
  2021. size: function ( optionalTarget ) {
  2022. var result = optionalTarget || new THREE.Vector2();
  2023. return result.subVectors( this.max, this.min );
  2024. },
  2025. expandByPoint: function ( point ) {
  2026. this.min.min( point );
  2027. this.max.max( point );
  2028. return this;
  2029. },
  2030. expandByVector: function ( vector ) {
  2031. this.min.sub( vector );
  2032. this.max.add( vector );
  2033. return this;
  2034. },
  2035. expandByScalar: function ( scalar ) {
  2036. this.min.addScalar( -scalar );
  2037. this.max.addScalar( scalar );
  2038. return this;
  2039. },
  2040. containsPoint: function ( point ) {
  2041. if ( point.x < this.min.x || point.x > this.max.x ||
  2042. point.y < this.min.y || point.y > this.max.y ) {
  2043. return false;
  2044. }
  2045. return true;
  2046. },
  2047. containsBox: function ( box ) {
  2048. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2049. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2050. return true;
  2051. }
  2052. return false;
  2053. },
  2054. getParameter: function ( point, optionalTarget ) {
  2055. // This can potentially have a divide by zero if the box
  2056. // has a size dimension of 0.
  2057. var result = optionalTarget || new THREE.Vector2();
  2058. return result.set(
  2059. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2060. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2061. );
  2062. },
  2063. isIntersectionBox: function ( box ) {
  2064. // using 6 splitting planes to rule out intersections.
  2065. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2066. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2067. return false;
  2068. }
  2069. return true;
  2070. },
  2071. clampPoint: function ( point, optionalTarget ) {
  2072. var result = optionalTarget || new THREE.Vector2();
  2073. return result.copy( point ).clamp( this.min, this.max );
  2074. },
  2075. distanceToPoint: function () {
  2076. var v1 = new THREE.Vector2();
  2077. return function ( point ) {
  2078. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2079. return clampedPoint.sub( point ).length();
  2080. };
  2081. }(),
  2082. intersect: function ( box ) {
  2083. this.min.max( box.min );
  2084. this.max.min( box.max );
  2085. return this;
  2086. },
  2087. union: function ( box ) {
  2088. this.min.min( box.min );
  2089. this.max.max( box.max );
  2090. return this;
  2091. },
  2092. translate: function ( offset ) {
  2093. this.min.add( offset );
  2094. this.max.add( offset );
  2095. return this;
  2096. },
  2097. equals: function ( box ) {
  2098. return box.min.equals( this.min ) && box.max.equals( this.max );
  2099. },
  2100. clone: function () {
  2101. return new THREE.Box2().copy( this );
  2102. }
  2103. };
  2104. /**
  2105. * @author bhouston / http://exocortex.com
  2106. * @author WestLangley / http://github.com/WestLangley
  2107. */
  2108. THREE.Box3 = function ( min, max ) {
  2109. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2110. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2111. };
  2112. THREE.Box3.prototype = {
  2113. constructor: THREE.Box3,
  2114. set: function ( min, max ) {
  2115. this.min.copy( min );
  2116. this.max.copy( max );
  2117. return this;
  2118. },
  2119. addPoint: function ( point ) {
  2120. if ( point.x < this.min.x ) {
  2121. this.min.x = point.x;
  2122. } else if ( point.x > this.max.x ) {
  2123. this.max.x = point.x;
  2124. }
  2125. if ( point.y < this.min.y ) {
  2126. this.min.y = point.y;
  2127. } else if ( point.y > this.max.y ) {
  2128. this.max.y = point.y;
  2129. }
  2130. if ( point.z < this.min.z ) {
  2131. this.min.z = point.z;
  2132. } else if ( point.z > this.max.z ) {
  2133. this.max.z = point.z;
  2134. }
  2135. },
  2136. setFromPoints: function ( points ) {
  2137. if ( points.length > 0 ) {
  2138. var point = points[ 0 ];
  2139. this.min.copy( point );
  2140. this.max.copy( point );
  2141. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2142. this.addPoint( points[ i ] )
  2143. }
  2144. } else {
  2145. this.makeEmpty();
  2146. }
  2147. return this;
  2148. },
  2149. setFromCenterAndSize: function() {
  2150. var v1 = new THREE.Vector3();
  2151. return function ( center, size ) {
  2152. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2153. this.min.copy( center ).sub( halfSize );
  2154. this.max.copy( center ).add( halfSize );
  2155. return this;
  2156. };
  2157. }(),
  2158. setFromObject: function() {
  2159. // Computes the world-axis-aligned bounding box of an object (including its children),
  2160. // accounting for both the object's, and childrens', world transforms
  2161. var v1 = new THREE.Vector3();
  2162. return function( object ) {
  2163. var scope = this;
  2164. object.updateMatrixWorld( true );
  2165. this.makeEmpty();
  2166. object.traverse( function ( node ) {
  2167. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2168. var vertices = node.geometry.vertices;
  2169. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2170. v1.copy( vertices[ i ] );
  2171. v1.applyMatrix4( node.matrixWorld );
  2172. scope.expandByPoint( v1 );
  2173. }
  2174. }
  2175. } );
  2176. return this;
  2177. };
  2178. }(),
  2179. copy: function ( box ) {
  2180. this.min.copy( box.min );
  2181. this.max.copy( box.max );
  2182. return this;
  2183. },
  2184. makeEmpty: function () {
  2185. this.min.x = this.min.y = this.min.z = Infinity;
  2186. this.max.x = this.max.y = this.max.z = -Infinity;
  2187. return this;
  2188. },
  2189. empty: function () {
  2190. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2191. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2192. },
  2193. center: function ( optionalTarget ) {
  2194. var result = optionalTarget || new THREE.Vector3();
  2195. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2196. },
  2197. size: function ( optionalTarget ) {
  2198. var result = optionalTarget || new THREE.Vector3();
  2199. return result.subVectors( this.max, this.min );
  2200. },
  2201. expandByPoint: function ( point ) {
  2202. this.min.min( point );
  2203. this.max.max( point );
  2204. return this;
  2205. },
  2206. expandByVector: function ( vector ) {
  2207. this.min.sub( vector );
  2208. this.max.add( vector );
  2209. return this;
  2210. },
  2211. expandByScalar: function ( scalar ) {
  2212. this.min.addScalar( -scalar );
  2213. this.max.addScalar( scalar );
  2214. return this;
  2215. },
  2216. containsPoint: function ( point ) {
  2217. if ( point.x < this.min.x || point.x > this.max.x ||
  2218. point.y < this.min.y || point.y > this.max.y ||
  2219. point.z < this.min.z || point.z > this.max.z ) {
  2220. return false;
  2221. }
  2222. return true;
  2223. },
  2224. containsBox: function ( box ) {
  2225. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2226. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2227. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2228. return true;
  2229. }
  2230. return false;
  2231. },
  2232. getParameter: function ( point, optionalTarget ) {
  2233. // This can potentially have a divide by zero if the box
  2234. // has a size dimension of 0.
  2235. var result = optionalTarget || new THREE.Vector3();
  2236. return result.set(
  2237. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2238. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2239. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2240. );
  2241. },
  2242. isIntersectionBox: function ( box ) {
  2243. // using 6 splitting planes to rule out intersections.
  2244. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2245. box.max.y < this.min.y || box.min.y > this.max.y ||
  2246. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2247. return false;
  2248. }
  2249. return true;
  2250. },
  2251. clampPoint: function ( point, optionalTarget ) {
  2252. var result = optionalTarget || new THREE.Vector3();
  2253. return result.copy( point ).clamp( this.min, this.max );
  2254. },
  2255. distanceToPoint: function() {
  2256. var v1 = new THREE.Vector3();
  2257. return function ( point ) {
  2258. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2259. return clampedPoint.sub( point ).length();
  2260. };
  2261. }(),
  2262. getBoundingSphere: function() {
  2263. var v1 = new THREE.Vector3();
  2264. return function ( optionalTarget ) {
  2265. var result = optionalTarget || new THREE.Sphere();
  2266. result.center = this.center();
  2267. result.radius = this.size( v1 ).length() * 0.5;
  2268. return result;
  2269. };
  2270. }(),
  2271. intersect: function ( box ) {
  2272. this.min.max( box.min );
  2273. this.max.min( box.max );
  2274. return this;
  2275. },
  2276. union: function ( box ) {
  2277. this.min.min( box.min );
  2278. this.max.max( box.max );
  2279. return this;
  2280. },
  2281. applyMatrix4: function() {
  2282. var points = [
  2283. new THREE.Vector3(),
  2284. new THREE.Vector3(),
  2285. new THREE.Vector3(),
  2286. new THREE.Vector3(),
  2287. new THREE.Vector3(),
  2288. new THREE.Vector3(),
  2289. new THREE.Vector3(),
  2290. new THREE.Vector3()
  2291. ];
  2292. return function ( matrix ) {
  2293. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2294. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2295. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2296. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2297. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2298. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2299. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2300. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2301. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2302. this.makeEmpty();
  2303. this.setFromPoints( points );
  2304. return this;
  2305. };
  2306. }(),
  2307. translate: function ( offset ) {
  2308. this.min.add( offset );
  2309. this.max.add( offset );
  2310. return this;
  2311. },
  2312. equals: function ( box ) {
  2313. return box.min.equals( this.min ) && box.max.equals( this.max );
  2314. },
  2315. clone: function () {
  2316. return new THREE.Box3().copy( this );
  2317. }
  2318. };
  2319. /**
  2320. * @author alteredq / http://alteredqualia.com/
  2321. * @author WestLangley / http://github.com/WestLangley
  2322. * @author bhouston / http://exocortex.com
  2323. */
  2324. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2325. this.elements = new Float32Array(9);
  2326. this.set(
  2327. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2328. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2329. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2330. );
  2331. };
  2332. THREE.Matrix3.prototype = {
  2333. constructor: THREE.Matrix3,
  2334. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2335. var te = this.elements;
  2336. te[0] = n11; te[3] = n12; te[6] = n13;
  2337. te[1] = n21; te[4] = n22; te[7] = n23;
  2338. te[2] = n31; te[5] = n32; te[8] = n33;
  2339. return this;
  2340. },
  2341. identity: function () {
  2342. this.set(
  2343. 1, 0, 0,
  2344. 0, 1, 0,
  2345. 0, 0, 1
  2346. );
  2347. return this;
  2348. },
  2349. copy: function ( m ) {
  2350. var me = m.elements;
  2351. this.set(
  2352. me[0], me[3], me[6],
  2353. me[1], me[4], me[7],
  2354. me[2], me[5], me[8]
  2355. );
  2356. return this;
  2357. },
  2358. multiplyVector3: function ( vector ) {
  2359. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2360. return vector.applyMatrix3( this );
  2361. },
  2362. multiplyVector3Array: function() {
  2363. var v1 = new THREE.Vector3();
  2364. return function ( a ) {
  2365. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2366. v1.x = a[ i ];
  2367. v1.y = a[ i + 1 ];
  2368. v1.z = a[ i + 2 ];
  2369. v1.applyMatrix3(this);
  2370. a[ i ] = v1.x;
  2371. a[ i + 1 ] = v1.y;
  2372. a[ i + 2 ] = v1.z;
  2373. }
  2374. return a;
  2375. };
  2376. }(),
  2377. multiplyScalar: function ( s ) {
  2378. var te = this.elements;
  2379. te[0] *= s; te[3] *= s; te[6] *= s;
  2380. te[1] *= s; te[4] *= s; te[7] *= s;
  2381. te[2] *= s; te[5] *= s; te[8] *= s;
  2382. return this;
  2383. },
  2384. determinant: function () {
  2385. var te = this.elements;
  2386. var a = te[0], b = te[1], c = te[2],
  2387. d = te[3], e = te[4], f = te[5],
  2388. g = te[6], h = te[7], i = te[8];
  2389. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2390. },
  2391. getInverse: function ( matrix, throwOnInvertible ) {
  2392. // input: THREE.Matrix4
  2393. // ( based on http://code.google.com/p/webgl-mjs/ )
  2394. var me = matrix.elements;
  2395. var te = this.elements;
  2396. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2397. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2398. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2399. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2400. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2401. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2402. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2403. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2404. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2405. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2406. // no inverse
  2407. if ( det === 0 ) {
  2408. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2409. if ( throwOnInvertible || false ) {
  2410. throw new Error( msg );
  2411. } else {
  2412. console.warn( msg );
  2413. }
  2414. this.identity();
  2415. return this;
  2416. }
  2417. this.multiplyScalar( 1.0 / det );
  2418. return this;
  2419. },
  2420. transpose: function () {
  2421. var tmp, m = this.elements;
  2422. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2423. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2424. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2425. return this;
  2426. },
  2427. getNormalMatrix: function ( m ) {
  2428. // input: THREE.Matrix4
  2429. this.getInverse( m ).transpose();
  2430. return this;
  2431. },
  2432. transposeIntoArray: function ( r ) {
  2433. var m = this.elements;
  2434. r[ 0 ] = m[ 0 ];
  2435. r[ 1 ] = m[ 3 ];
  2436. r[ 2 ] = m[ 6 ];
  2437. r[ 3 ] = m[ 1 ];
  2438. r[ 4 ] = m[ 4 ];
  2439. r[ 5 ] = m[ 7 ];
  2440. r[ 6 ] = m[ 2 ];
  2441. r[ 7 ] = m[ 5 ];
  2442. r[ 8 ] = m[ 8 ];
  2443. return this;
  2444. },
  2445. fromArray: function ( array ) {
  2446. this.elements.set( array );
  2447. return this;
  2448. },
  2449. toArray: function () {
  2450. var te = this.elements;
  2451. return [
  2452. te[ 0 ], te[ 1 ], te[ 2 ],
  2453. te[ 3 ], te[ 4 ], te[ 5 ],
  2454. te[ 6 ], te[ 7 ], te[ 8 ]
  2455. ];
  2456. },
  2457. clone: function () {
  2458. var te = this.elements;
  2459. return new THREE.Matrix3(
  2460. te[0], te[3], te[6],
  2461. te[1], te[4], te[7],
  2462. te[2], te[5], te[8]
  2463. );
  2464. }
  2465. };
  2466. /**
  2467. * @author mrdoob / http://mrdoob.com/
  2468. * @author supereggbert / http://www.paulbrunt.co.uk/
  2469. * @author philogb / http://blog.thejit.org/
  2470. * @author jordi_ros / http://plattsoft.com
  2471. * @author D1plo1d / http://github.com/D1plo1d
  2472. * @author alteredq / http://alteredqualia.com/
  2473. * @author mikael emtinger / http://gomo.se/
  2474. * @author timknip / http://www.floorplanner.com/
  2475. * @author bhouston / http://exocortex.com
  2476. * @author WestLangley / http://github.com/WestLangley
  2477. */
  2478. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2479. this.elements = new Float32Array( 16 );
  2480. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2481. // we should not support semi specification of Matrix4, it is just weird.
  2482. var te = this.elements;
  2483. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2484. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2485. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2486. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2487. };
  2488. THREE.Matrix4.prototype = {
  2489. constructor: THREE.Matrix4,
  2490. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2491. var te = this.elements;
  2492. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2493. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2494. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2495. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2496. return this;
  2497. },
  2498. identity: function () {
  2499. this.set(
  2500. 1, 0, 0, 0,
  2501. 0, 1, 0, 0,
  2502. 0, 0, 1, 0,
  2503. 0, 0, 0, 1
  2504. );
  2505. return this;
  2506. },
  2507. copy: function ( m ) {
  2508. this.elements.set( m.elements );
  2509. return this;
  2510. },
  2511. extractPosition: function ( m ) {
  2512. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2513. return this.copyPosition( m );
  2514. },
  2515. copyPosition: function ( m ) {
  2516. var te = this.elements;
  2517. var me = m.elements;
  2518. te[12] = me[12];
  2519. te[13] = me[13];
  2520. te[14] = me[14];
  2521. return this;
  2522. },
  2523. extractRotation: function () {
  2524. var v1 = new THREE.Vector3();
  2525. return function ( m ) {
  2526. var te = this.elements;
  2527. var me = m.elements;
  2528. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2529. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2530. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2531. te[0] = me[0] * scaleX;
  2532. te[1] = me[1] * scaleX;
  2533. te[2] = me[2] * scaleX;
  2534. te[4] = me[4] * scaleY;
  2535. te[5] = me[5] * scaleY;
  2536. te[6] = me[6] * scaleY;
  2537. te[8] = me[8] * scaleZ;
  2538. te[9] = me[9] * scaleZ;
  2539. te[10] = me[10] * scaleZ;
  2540. return this;
  2541. };
  2542. }(),
  2543. makeRotationFromEuler: function ( euler ) {
  2544. if ( euler instanceof THREE.Euler === false ) {
  2545. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2546. }
  2547. var te = this.elements;
  2548. var x = euler.x, y = euler.y, z = euler.z;
  2549. var a = Math.cos( x ), b = Math.sin( x );
  2550. var c = Math.cos( y ), d = Math.sin( y );
  2551. var e = Math.cos( z ), f = Math.sin( z );
  2552. if ( euler.order === 'XYZ' ) {
  2553. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2554. te[0] = c * e;
  2555. te[4] = - c * f;
  2556. te[8] = d;
  2557. te[1] = af + be * d;
  2558. te[5] = ae - bf * d;
  2559. te[9] = - b * c;
  2560. te[2] = bf - ae * d;
  2561. te[6] = be + af * d;
  2562. te[10] = a * c;
  2563. } else if ( euler.order === 'YXZ' ) {
  2564. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2565. te[0] = ce + df * b;
  2566. te[4] = de * b - cf;
  2567. te[8] = a * d;
  2568. te[1] = a * f;
  2569. te[5] = a * e;
  2570. te[9] = - b;
  2571. te[2] = cf * b - de;
  2572. te[6] = df + ce * b;
  2573. te[10] = a * c;
  2574. } else if ( euler.order === 'ZXY' ) {
  2575. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2576. te[0] = ce - df * b;
  2577. te[4] = - a * f;
  2578. te[8] = de + cf * b;
  2579. te[1] = cf + de * b;
  2580. te[5] = a * e;
  2581. te[9] = df - ce * b;
  2582. te[2] = - a * d;
  2583. te[6] = b;
  2584. te[10] = a * c;
  2585. } else if ( euler.order === 'ZYX' ) {
  2586. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2587. te[0] = c * e;
  2588. te[4] = be * d - af;
  2589. te[8] = ae * d + bf;
  2590. te[1] = c * f;
  2591. te[5] = bf * d + ae;
  2592. te[9] = af * d - be;
  2593. te[2] = - d;
  2594. te[6] = b * c;
  2595. te[10] = a * c;
  2596. } else if ( euler.order === 'YZX' ) {
  2597. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2598. te[0] = c * e;
  2599. te[4] = bd - ac * f;
  2600. te[8] = bc * f + ad;
  2601. te[1] = f;
  2602. te[5] = a * e;
  2603. te[9] = - b * e;
  2604. te[2] = - d * e;
  2605. te[6] = ad * f + bc;
  2606. te[10] = ac - bd * f;
  2607. } else if ( euler.order === 'XZY' ) {
  2608. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2609. te[0] = c * e;
  2610. te[4] = - f;
  2611. te[8] = d * e;
  2612. te[1] = ac * f + bd;
  2613. te[5] = a * e;
  2614. te[9] = ad * f - bc;
  2615. te[2] = bc * f - ad;
  2616. te[6] = b * e;
  2617. te[10] = bd * f + ac;
  2618. }
  2619. // last column
  2620. te[3] = 0;
  2621. te[7] = 0;
  2622. te[11] = 0;
  2623. // bottom row
  2624. te[12] = 0;
  2625. te[13] = 0;
  2626. te[14] = 0;
  2627. te[15] = 1;
  2628. return this;
  2629. },
  2630. setRotationFromQuaternion: function ( q ) {
  2631. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2632. return this.makeRotationFromQuaternion( q );
  2633. },
  2634. makeRotationFromQuaternion: function ( q ) {
  2635. var te = this.elements;
  2636. var x = q.x, y = q.y, z = q.z, w = q.w;
  2637. var x2 = x + x, y2 = y + y, z2 = z + z;
  2638. var xx = x * x2, xy = x * y2, xz = x * z2;
  2639. var yy = y * y2, yz = y * z2, zz = z * z2;
  2640. var wx = w * x2, wy = w * y2, wz = w * z2;
  2641. te[0] = 1 - ( yy + zz );
  2642. te[4] = xy - wz;
  2643. te[8] = xz + wy;
  2644. te[1] = xy + wz;
  2645. te[5] = 1 - ( xx + zz );
  2646. te[9] = yz - wx;
  2647. te[2] = xz - wy;
  2648. te[6] = yz + wx;
  2649. te[10] = 1 - ( xx + yy );
  2650. // last column
  2651. te[3] = 0;
  2652. te[7] = 0;
  2653. te[11] = 0;
  2654. // bottom row
  2655. te[12] = 0;
  2656. te[13] = 0;
  2657. te[14] = 0;
  2658. te[15] = 1;
  2659. return this;
  2660. },
  2661. lookAt: function() {
  2662. var x = new THREE.Vector3();
  2663. var y = new THREE.Vector3();
  2664. var z = new THREE.Vector3();
  2665. return function ( eye, target, up ) {
  2666. var te = this.elements;
  2667. z.subVectors( eye, target ).normalize();
  2668. if ( z.length() === 0 ) {
  2669. z.z = 1;
  2670. }
  2671. x.crossVectors( up, z ).normalize();
  2672. if ( x.length() === 0 ) {
  2673. z.x += 0.0001;
  2674. x.crossVectors( up, z ).normalize();
  2675. }
  2676. y.crossVectors( z, x );
  2677. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2678. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2679. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2680. return this;
  2681. };
  2682. }(),
  2683. multiply: function ( m, n ) {
  2684. if ( n !== undefined ) {
  2685. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2686. return this.multiplyMatrices( m, n );
  2687. }
  2688. return this.multiplyMatrices( this, m );
  2689. },
  2690. multiplyMatrices: function ( a, b ) {
  2691. var ae = a.elements;
  2692. var be = b.elements;
  2693. var te = this.elements;
  2694. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2695. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2696. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2697. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2698. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2699. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2700. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2701. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2702. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2703. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2704. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2705. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2706. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2707. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2708. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2709. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2710. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2711. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2712. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2713. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2714. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2715. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2716. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2717. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2718. return this;
  2719. },
  2720. multiplyToArray: function ( a, b, r ) {
  2721. var te = this.elements;
  2722. this.multiplyMatrices( a, b );
  2723. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2724. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2725. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2726. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2727. return this;
  2728. },
  2729. multiplyScalar: function ( s ) {
  2730. var te = this.elements;
  2731. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2732. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2733. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2734. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2735. return this;
  2736. },
  2737. multiplyVector3: function ( vector ) {
  2738. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2739. return vector.applyProjection( this );
  2740. },
  2741. multiplyVector4: function ( vector ) {
  2742. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2743. return vector.applyMatrix4( this );
  2744. },
  2745. multiplyVector3Array: function() {
  2746. var v1 = new THREE.Vector3();
  2747. return function ( a ) {
  2748. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2749. v1.x = a[ i ];
  2750. v1.y = a[ i + 1 ];
  2751. v1.z = a[ i + 2 ];
  2752. v1.applyProjection( this );
  2753. a[ i ] = v1.x;
  2754. a[ i + 1 ] = v1.y;
  2755. a[ i + 2 ] = v1.z;
  2756. }
  2757. return a;
  2758. };
  2759. }(),
  2760. rotateAxis: function ( v ) {
  2761. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2762. v.transformDirection( this );
  2763. },
  2764. crossVector: function ( vector ) {
  2765. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2766. return vector.applyMatrix4( this );
  2767. },
  2768. determinant: function () {
  2769. var te = this.elements;
  2770. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2771. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2772. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2773. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2774. //TODO: make this more efficient
  2775. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2776. return (
  2777. n41 * (
  2778. +n14 * n23 * n32
  2779. -n13 * n24 * n32
  2780. -n14 * n22 * n33
  2781. +n12 * n24 * n33
  2782. +n13 * n22 * n34
  2783. -n12 * n23 * n34
  2784. ) +
  2785. n42 * (
  2786. +n11 * n23 * n34
  2787. -n11 * n24 * n33
  2788. +n14 * n21 * n33
  2789. -n13 * n21 * n34
  2790. +n13 * n24 * n31
  2791. -n14 * n23 * n31
  2792. ) +
  2793. n43 * (
  2794. +n11 * n24 * n32
  2795. -n11 * n22 * n34
  2796. -n14 * n21 * n32
  2797. +n12 * n21 * n34
  2798. +n14 * n22 * n31
  2799. -n12 * n24 * n31
  2800. ) +
  2801. n44 * (
  2802. -n13 * n22 * n31
  2803. -n11 * n23 * n32
  2804. +n11 * n22 * n33
  2805. +n13 * n21 * n32
  2806. -n12 * n21 * n33
  2807. +n12 * n23 * n31
  2808. )
  2809. );
  2810. },
  2811. transpose: function () {
  2812. var te = this.elements;
  2813. var tmp;
  2814. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2815. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2816. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2817. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2818. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2819. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2820. return this;
  2821. },
  2822. flattenToArray: function ( flat ) {
  2823. var te = this.elements;
  2824. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2825. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2826. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2827. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2828. return flat;
  2829. },
  2830. flattenToArrayOffset: function( flat, offset ) {
  2831. var te = this.elements;
  2832. flat[ offset ] = te[0];
  2833. flat[ offset + 1 ] = te[1];
  2834. flat[ offset + 2 ] = te[2];
  2835. flat[ offset + 3 ] = te[3];
  2836. flat[ offset + 4 ] = te[4];
  2837. flat[ offset + 5 ] = te[5];
  2838. flat[ offset + 6 ] = te[6];
  2839. flat[ offset + 7 ] = te[7];
  2840. flat[ offset + 8 ] = te[8];
  2841. flat[ offset + 9 ] = te[9];
  2842. flat[ offset + 10 ] = te[10];
  2843. flat[ offset + 11 ] = te[11];
  2844. flat[ offset + 12 ] = te[12];
  2845. flat[ offset + 13 ] = te[13];
  2846. flat[ offset + 14 ] = te[14];
  2847. flat[ offset + 15 ] = te[15];
  2848. return flat;
  2849. },
  2850. getPosition: function() {
  2851. var v1 = new THREE.Vector3();
  2852. return function () {
  2853. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2854. var te = this.elements;
  2855. return v1.set( te[12], te[13], te[14] );
  2856. };
  2857. }(),
  2858. setPosition: function ( v ) {
  2859. var te = this.elements;
  2860. te[12] = v.x;
  2861. te[13] = v.y;
  2862. te[14] = v.z;
  2863. return this;
  2864. },
  2865. getInverse: function ( m, throwOnInvertible ) {
  2866. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2867. var te = this.elements;
  2868. var me = m.elements;
  2869. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2870. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2871. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2872. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2873. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2874. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2875. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2876. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2877. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2878. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2879. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2880. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2881. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2882. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2883. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2884. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2885. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2886. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2887. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2888. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2889. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2890. if ( det == 0 ) {
  2891. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2892. if ( throwOnInvertible || false ) {
  2893. throw new Error( msg );
  2894. } else {
  2895. console.warn( msg );
  2896. }
  2897. this.identity();
  2898. return this;
  2899. }
  2900. this.multiplyScalar( 1 / det );
  2901. return this;
  2902. },
  2903. translate: function ( v ) {
  2904. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2905. },
  2906. rotateX: function ( angle ) {
  2907. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2908. },
  2909. rotateY: function ( angle ) {
  2910. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2911. },
  2912. rotateZ: function ( angle ) {
  2913. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2914. },
  2915. rotateByAxis: function ( axis, angle ) {
  2916. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2917. },
  2918. scale: function ( v ) {
  2919. var te = this.elements;
  2920. var x = v.x, y = v.y, z = v.z;
  2921. te[0] *= x; te[4] *= y; te[8] *= z;
  2922. te[1] *= x; te[5] *= y; te[9] *= z;
  2923. te[2] *= x; te[6] *= y; te[10] *= z;
  2924. te[3] *= x; te[7] *= y; te[11] *= z;
  2925. return this;
  2926. },
  2927. getMaxScaleOnAxis: function () {
  2928. var te = this.elements;
  2929. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2930. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2931. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2932. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2933. },
  2934. makeTranslation: function ( x, y, z ) {
  2935. this.set(
  2936. 1, 0, 0, x,
  2937. 0, 1, 0, y,
  2938. 0, 0, 1, z,
  2939. 0, 0, 0, 1
  2940. );
  2941. return this;
  2942. },
  2943. makeRotationX: function ( theta ) {
  2944. var c = Math.cos( theta ), s = Math.sin( theta );
  2945. this.set(
  2946. 1, 0, 0, 0,
  2947. 0, c, -s, 0,
  2948. 0, s, c, 0,
  2949. 0, 0, 0, 1
  2950. );
  2951. return this;
  2952. },
  2953. makeRotationY: function ( theta ) {
  2954. var c = Math.cos( theta ), s = Math.sin( theta );
  2955. this.set(
  2956. c, 0, s, 0,
  2957. 0, 1, 0, 0,
  2958. -s, 0, c, 0,
  2959. 0, 0, 0, 1
  2960. );
  2961. return this;
  2962. },
  2963. makeRotationZ: function ( theta ) {
  2964. var c = Math.cos( theta ), s = Math.sin( theta );
  2965. this.set(
  2966. c, -s, 0, 0,
  2967. s, c, 0, 0,
  2968. 0, 0, 1, 0,
  2969. 0, 0, 0, 1
  2970. );
  2971. return this;
  2972. },
  2973. makeRotationAxis: function ( axis, angle ) {
  2974. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2975. var c = Math.cos( angle );
  2976. var s = Math.sin( angle );
  2977. var t = 1 - c;
  2978. var x = axis.x, y = axis.y, z = axis.z;
  2979. var tx = t * x, ty = t * y;
  2980. this.set(
  2981. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2982. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2983. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2984. 0, 0, 0, 1
  2985. );
  2986. return this;
  2987. },
  2988. makeScale: function ( x, y, z ) {
  2989. this.set(
  2990. x, 0, 0, 0,
  2991. 0, y, 0, 0,
  2992. 0, 0, z, 0,
  2993. 0, 0, 0, 1
  2994. );
  2995. return this;
  2996. },
  2997. compose: function ( position, quaternion, scale ) {
  2998. this.makeRotationFromQuaternion( quaternion );
  2999. this.scale( scale );
  3000. this.setPosition( position );
  3001. return this;
  3002. },
  3003. decompose: function () {
  3004. var vector = new THREE.Vector3();
  3005. var matrix = new THREE.Matrix4();
  3006. return function ( position, quaternion, scale ) {
  3007. var te = this.elements;
  3008. var sx = vector.set( te[0], te[1], te[2] ).length();
  3009. var sy = vector.set( te[4], te[5], te[6] ).length();
  3010. var sz = vector.set( te[8], te[9], te[10] ).length();
  3011. // if determine is negative, we need to invert one scale
  3012. var det = this.determinant();
  3013. if( det < 0 ) {
  3014. sx = -sx;
  3015. }
  3016. position.x = te[12];
  3017. position.y = te[13];
  3018. position.z = te[14];
  3019. // scale the rotation part
  3020. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3021. var invSX = 1 / sx;
  3022. var invSY = 1 / sy;
  3023. var invSZ = 1 / sz;
  3024. matrix.elements[0] *= invSX;
  3025. matrix.elements[1] *= invSX;
  3026. matrix.elements[2] *= invSX;
  3027. matrix.elements[4] *= invSY;
  3028. matrix.elements[5] *= invSY;
  3029. matrix.elements[6] *= invSY;
  3030. matrix.elements[8] *= invSZ;
  3031. matrix.elements[9] *= invSZ;
  3032. matrix.elements[10] *= invSZ;
  3033. quaternion.setFromRotationMatrix( matrix );
  3034. scale.x = sx;
  3035. scale.y = sy;
  3036. scale.z = sz;
  3037. return this;
  3038. };
  3039. }(),
  3040. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3041. var te = this.elements;
  3042. var x = 2 * near / ( right - left );
  3043. var y = 2 * near / ( top - bottom );
  3044. var a = ( right + left ) / ( right - left );
  3045. var b = ( top + bottom ) / ( top - bottom );
  3046. var c = - ( far + near ) / ( far - near );
  3047. var d = - 2 * far * near / ( far - near );
  3048. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  3049. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  3050. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  3051. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  3052. return this;
  3053. },
  3054. makePerspective: function ( fov, aspect, near, far ) {
  3055. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3056. var ymin = - ymax;
  3057. var xmin = ymin * aspect;
  3058. var xmax = ymax * aspect;
  3059. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3060. },
  3061. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3062. var te = this.elements;
  3063. var w = right - left;
  3064. var h = top - bottom;
  3065. var p = far - near;
  3066. var x = ( right + left ) / w;
  3067. var y = ( top + bottom ) / h;
  3068. var z = ( far + near ) / p;
  3069. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  3070. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  3071. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  3072. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  3073. return this;
  3074. },
  3075. fromArray: function ( array ) {
  3076. this.elements.set( array );
  3077. return this;
  3078. },
  3079. toArray: function () {
  3080. var te = this.elements;
  3081. return [
  3082. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3083. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3084. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3085. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3086. ];
  3087. },
  3088. clone: function () {
  3089. var te = this.elements;
  3090. return new THREE.Matrix4(
  3091. te[0], te[4], te[8], te[12],
  3092. te[1], te[5], te[9], te[13],
  3093. te[2], te[6], te[10], te[14],
  3094. te[3], te[7], te[11], te[15]
  3095. );
  3096. }
  3097. };
  3098. /**
  3099. * @author bhouston / http://exocortex.com
  3100. */
  3101. THREE.Ray = function ( origin, direction ) {
  3102. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3103. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3104. };
  3105. THREE.Ray.prototype = {
  3106. constructor: THREE.Ray,
  3107. set: function ( origin, direction ) {
  3108. this.origin.copy( origin );
  3109. this.direction.copy( direction );
  3110. return this;
  3111. },
  3112. copy: function ( ray ) {
  3113. this.origin.copy( ray.origin );
  3114. this.direction.copy( ray.direction );
  3115. return this;
  3116. },
  3117. at: function ( t, optionalTarget ) {
  3118. var result = optionalTarget || new THREE.Vector3();
  3119. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3120. },
  3121. recast: function () {
  3122. var v1 = new THREE.Vector3();
  3123. return function ( t ) {
  3124. this.origin.copy( this.at( t, v1 ) );
  3125. return this;
  3126. };
  3127. }(),
  3128. closestPointToPoint: function ( point, optionalTarget ) {
  3129. var result = optionalTarget || new THREE.Vector3();
  3130. result.subVectors( point, this.origin );
  3131. var directionDistance = result.dot( this.direction );
  3132. if ( directionDistance < 0 ) {
  3133. return result.copy( this.origin );
  3134. }
  3135. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3136. },
  3137. distanceToPoint: function () {
  3138. var v1 = new THREE.Vector3();
  3139. return function ( point ) {
  3140. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3141. // point behind the ray
  3142. if ( directionDistance < 0 ) {
  3143. return this.origin.distanceTo( point );
  3144. }
  3145. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3146. return v1.distanceTo( point );
  3147. };
  3148. }(),
  3149. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3150. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3151. // It returns the min distance between the ray and the segment
  3152. // defined by v0 and v1
  3153. // It can also set two optional targets :
  3154. // - The closest point on the ray
  3155. // - The closest point on the segment
  3156. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3157. var segDir = v1.clone().sub( v0 ).normalize();
  3158. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3159. var diff = this.origin.clone().sub( segCenter );
  3160. var a01 = - this.direction.dot( segDir );
  3161. var b0 = diff.dot( this.direction );
  3162. var b1 = - diff.dot( segDir );
  3163. var c = diff.lengthSq();
  3164. var det = Math.abs( 1 - a01 * a01 );
  3165. var s0, s1, sqrDist, extDet;
  3166. if ( det >= 0 ) {
  3167. // The ray and segment are not parallel.
  3168. s0 = a01 * b1 - b0;
  3169. s1 = a01 * b0 - b1;
  3170. extDet = segExtent * det;
  3171. if ( s0 >= 0 ) {
  3172. if ( s1 >= - extDet ) {
  3173. if ( s1 <= extDet ) {
  3174. // region 0
  3175. // Minimum at interior points of ray and segment.
  3176. var invDet = 1 / det;
  3177. s0 *= invDet;
  3178. s1 *= invDet;
  3179. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3180. } else {
  3181. // region 1
  3182. s1 = segExtent;
  3183. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3184. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3185. }
  3186. } else {
  3187. // region 5
  3188. s1 = - segExtent;
  3189. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3190. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3191. }
  3192. } else {
  3193. if ( s1 <= - extDet) {
  3194. // region 4
  3195. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3196. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3197. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3198. } else if ( s1 <= extDet ) {
  3199. // region 3
  3200. s0 = 0;
  3201. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3202. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3203. } else {
  3204. // region 2
  3205. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3206. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3207. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3208. }
  3209. }
  3210. } else {
  3211. // Ray and segment are parallel.
  3212. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3213. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3214. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3215. }
  3216. if ( optionalPointOnRay ) {
  3217. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3218. }
  3219. if ( optionalPointOnSegment ) {
  3220. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3221. }
  3222. return sqrDist;
  3223. },
  3224. isIntersectionSphere: function ( sphere ) {
  3225. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3226. },
  3227. isIntersectionPlane: function ( plane ) {
  3228. // check if the ray lies on the plane first
  3229. var distToPoint = plane.distanceToPoint( this.origin );
  3230. if ( distToPoint === 0 ) {
  3231. return true;
  3232. }
  3233. var denominator = plane.normal.dot( this.direction );
  3234. if ( denominator * distToPoint < 0 ) {
  3235. return true
  3236. }
  3237. // ray origin is behind the plane (and is pointing behind it)
  3238. return false;
  3239. },
  3240. distanceToPlane: function ( plane ) {
  3241. var denominator = plane.normal.dot( this.direction );
  3242. if ( denominator == 0 ) {
  3243. // line is coplanar, return origin
  3244. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3245. return 0;
  3246. }
  3247. // Null is preferable to undefined since undefined means.... it is undefined
  3248. return null;
  3249. }
  3250. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3251. // Return if the ray never intersects the plane
  3252. return t >= 0 ? t : null;
  3253. },
  3254. intersectPlane: function ( plane, optionalTarget ) {
  3255. var t = this.distanceToPlane( plane );
  3256. if ( t === null ) {
  3257. return null;
  3258. }
  3259. return this.at( t, optionalTarget );
  3260. },
  3261. isIntersectionBox: function () {
  3262. var v = new THREE.Vector3();
  3263. return function ( box ) {
  3264. return this.intersectBox( box, v ) !== null;
  3265. }
  3266. }(),
  3267. intersectBox: function ( box , optionalTarget ) {
  3268. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3269. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3270. var invdirx = 1/this.direction.x,
  3271. invdiry = 1/this.direction.y,
  3272. invdirz = 1/this.direction.z;
  3273. var origin = this.origin;
  3274. if (invdirx >= 0) {
  3275. tmin = (box.min.x - origin.x) * invdirx;
  3276. tmax = (box.max.x - origin.x) * invdirx;
  3277. } else {
  3278. tmin = (box.max.x - origin.x) * invdirx;
  3279. tmax = (box.min.x - origin.x) * invdirx;
  3280. }
  3281. if (invdiry >= 0) {
  3282. tymin = (box.min.y - origin.y) * invdiry;
  3283. tymax = (box.max.y - origin.y) * invdiry;
  3284. } else {
  3285. tymin = (box.max.y - origin.y) * invdiry;
  3286. tymax = (box.min.y - origin.y) * invdiry;
  3287. }
  3288. if ((tmin > tymax) || (tymin > tmax)) return null;
  3289. // These lines also handle the case where tmin or tmax is NaN
  3290. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3291. if (tymin > tmin || tmin !== tmin ) tmin = tymin;
  3292. if (tymax < tmax || tmax !== tmax ) tmax = tymax;
  3293. if (invdirz >= 0) {
  3294. tzmin = (box.min.z - origin.z) * invdirz;
  3295. tzmax = (box.max.z - origin.z) * invdirz;
  3296. } else {
  3297. tzmin = (box.max.z - origin.z) * invdirz;
  3298. tzmax = (box.min.z - origin.z) * invdirz;
  3299. }
  3300. if ((tmin > tzmax) || (tzmin > tmax)) return null;
  3301. if (tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3302. if (tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3303. //return point closest to the ray (positive side)
  3304. if ( tmax < 0 ) return null;
  3305. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3306. },
  3307. intersectTriangle: function() {
  3308. // Compute the offset origin, edges, and normal.
  3309. var diff = new THREE.Vector3();
  3310. var edge1 = new THREE.Vector3();
  3311. var edge2 = new THREE.Vector3();
  3312. var normal = new THREE.Vector3();
  3313. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3314. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3315. edge1.subVectors( b, a );
  3316. edge2.subVectors( c, a );
  3317. normal.crossVectors( edge1, edge2 );
  3318. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3319. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3320. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3321. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3322. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3323. var DdN = this.direction.dot( normal );
  3324. var sign;
  3325. if ( DdN > 0 ) {
  3326. if ( backfaceCulling ) return null;
  3327. sign = 1;
  3328. } else if ( DdN < 0 ) {
  3329. sign = - 1;
  3330. DdN = - DdN;
  3331. } else {
  3332. return null;
  3333. }
  3334. diff.subVectors( this.origin, a );
  3335. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3336. // b1 < 0, no intersection
  3337. if ( DdQxE2 < 0 ) {
  3338. return null;
  3339. }
  3340. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3341. // b2 < 0, no intersection
  3342. if ( DdE1xQ < 0 ) {
  3343. return null;
  3344. }
  3345. // b1+b2 > 1, no intersection
  3346. if ( DdQxE2 + DdE1xQ > DdN ) {
  3347. return null;
  3348. }
  3349. // Line intersects triangle, check if ray does.
  3350. var QdN = - sign * diff.dot( normal );
  3351. // t < 0, no intersection
  3352. if ( QdN < 0 ) {
  3353. return null;
  3354. }
  3355. // Ray intersects triangle.
  3356. return this.at( QdN / DdN, optionalTarget );
  3357. }
  3358. }(),
  3359. applyMatrix4: function ( matrix4 ) {
  3360. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3361. this.origin.applyMatrix4( matrix4 );
  3362. this.direction.sub( this.origin );
  3363. this.direction.normalize();
  3364. return this;
  3365. },
  3366. equals: function ( ray ) {
  3367. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3368. },
  3369. clone: function () {
  3370. return new THREE.Ray().copy( this );
  3371. }
  3372. };
  3373. /**
  3374. * @author bhouston / http://exocortex.com
  3375. * @author mrdoob / http://mrdoob.com/
  3376. */
  3377. THREE.Sphere = function ( center, radius ) {
  3378. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3379. this.radius = ( radius !== undefined ) ? radius : 0;
  3380. };
  3381. THREE.Sphere.prototype = {
  3382. constructor: THREE.Sphere,
  3383. set: function ( center, radius ) {
  3384. this.center.copy( center );
  3385. this.radius = radius;
  3386. return this;
  3387. },
  3388. setFromPoints: function () {
  3389. var box = new THREE.Box3();
  3390. return function ( points, optionalCenter ) {
  3391. var center = this.center;
  3392. if ( optionalCenter !== undefined ) {
  3393. center.copy( optionalCenter );
  3394. } else {
  3395. box.setFromPoints( points ).center( center );
  3396. }
  3397. var maxRadiusSq = 0;
  3398. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3399. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3400. }
  3401. this.radius = Math.sqrt( maxRadiusSq );
  3402. return this;
  3403. };
  3404. }(),
  3405. copy: function ( sphere ) {
  3406. this.center.copy( sphere.center );
  3407. this.radius = sphere.radius;
  3408. return this;
  3409. },
  3410. empty: function () {
  3411. return ( this.radius <= 0 );
  3412. },
  3413. containsPoint: function ( point ) {
  3414. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3415. },
  3416. distanceToPoint: function ( point ) {
  3417. return ( point.distanceTo( this.center ) - this.radius );
  3418. },
  3419. intersectsSphere: function ( sphere ) {
  3420. var radiusSum = this.radius + sphere.radius;
  3421. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3422. },
  3423. clampPoint: function ( point, optionalTarget ) {
  3424. var deltaLengthSq = this.center.distanceToSquared( point );
  3425. var result = optionalTarget || new THREE.Vector3();
  3426. result.copy( point );
  3427. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3428. result.sub( this.center ).normalize();
  3429. result.multiplyScalar( this.radius ).add( this.center );
  3430. }
  3431. return result;
  3432. },
  3433. getBoundingBox: function ( optionalTarget ) {
  3434. var box = optionalTarget || new THREE.Box3();
  3435. box.set( this.center, this.center );
  3436. box.expandByScalar( this.radius );
  3437. return box;
  3438. },
  3439. applyMatrix4: function ( matrix ) {
  3440. this.center.applyMatrix4( matrix );
  3441. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3442. return this;
  3443. },
  3444. translate: function ( offset ) {
  3445. this.center.add( offset );
  3446. return this;
  3447. },
  3448. equals: function ( sphere ) {
  3449. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3450. },
  3451. clone: function () {
  3452. return new THREE.Sphere().copy( this );
  3453. }
  3454. };
  3455. /**
  3456. * @author mrdoob / http://mrdoob.com/
  3457. * @author alteredq / http://alteredqualia.com/
  3458. * @author bhouston / http://exocortex.com
  3459. */
  3460. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3461. this.planes = [
  3462. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3463. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3464. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3465. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3466. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3467. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3468. ];
  3469. };
  3470. THREE.Frustum.prototype = {
  3471. constructor: THREE.Frustum,
  3472. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3473. var planes = this.planes;
  3474. planes[0].copy( p0 );
  3475. planes[1].copy( p1 );
  3476. planes[2].copy( p2 );
  3477. planes[3].copy( p3 );
  3478. planes[4].copy( p4 );
  3479. planes[5].copy( p5 );
  3480. return this;
  3481. },
  3482. copy: function ( frustum ) {
  3483. var planes = this.planes;
  3484. for( var i = 0; i < 6; i ++ ) {
  3485. planes[i].copy( frustum.planes[i] );
  3486. }
  3487. return this;
  3488. },
  3489. setFromMatrix: function ( m ) {
  3490. var planes = this.planes;
  3491. var me = m.elements;
  3492. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3493. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3494. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3495. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3496. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3497. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3498. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3499. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3500. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3501. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3502. return this;
  3503. },
  3504. intersectsObject: function () {
  3505. var sphere = new THREE.Sphere();
  3506. return function ( object ) {
  3507. var geometry = object.geometry;
  3508. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3509. sphere.copy( geometry.boundingSphere );
  3510. sphere.applyMatrix4( object.matrixWorld );
  3511. return this.intersectsSphere( sphere );
  3512. };
  3513. }(),
  3514. intersectsSphere: function ( sphere ) {
  3515. var planes = this.planes;
  3516. var center = sphere.center;
  3517. var negRadius = -sphere.radius;
  3518. for ( var i = 0; i < 6; i ++ ) {
  3519. var distance = planes[ i ].distanceToPoint( center );
  3520. if ( distance < negRadius ) {
  3521. return false;
  3522. }
  3523. }
  3524. return true;
  3525. },
  3526. intersectsBox : function() {
  3527. var p1 = new THREE.Vector3(),
  3528. p2 = new THREE.Vector3();
  3529. return function( box ) {
  3530. var planes = this.planes;
  3531. for ( var i = 0; i < 6 ; i ++ ) {
  3532. var plane = planes[i];
  3533. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3534. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3535. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3536. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3537. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3538. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3539. var d1 = plane.distanceToPoint( p1 );
  3540. var d2 = plane.distanceToPoint( p2 );
  3541. // if both outside plane, no intersection
  3542. if ( d1 < 0 && d2 < 0 ) {
  3543. return false;
  3544. }
  3545. }
  3546. return true;
  3547. };
  3548. }(),
  3549. containsPoint: function ( point ) {
  3550. var planes = this.planes;
  3551. for ( var i = 0; i < 6; i ++ ) {
  3552. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3553. return false;
  3554. }
  3555. }
  3556. return true;
  3557. },
  3558. clone: function () {
  3559. return new THREE.Frustum().copy( this );
  3560. }
  3561. };
  3562. /**
  3563. * @author bhouston / http://exocortex.com
  3564. */
  3565. THREE.Plane = function ( normal, constant ) {
  3566. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3567. this.constant = ( constant !== undefined ) ? constant : 0;
  3568. };
  3569. THREE.Plane.prototype = {
  3570. constructor: THREE.Plane,
  3571. set: function ( normal, constant ) {
  3572. this.normal.copy( normal );
  3573. this.constant = constant;
  3574. return this;
  3575. },
  3576. setComponents: function ( x, y, z, w ) {
  3577. this.normal.set( x, y, z );
  3578. this.constant = w;
  3579. return this;
  3580. },
  3581. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3582. this.normal.copy( normal );
  3583. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3584. return this;
  3585. },
  3586. setFromCoplanarPoints: function() {
  3587. var v1 = new THREE.Vector3();
  3588. var v2 = new THREE.Vector3();
  3589. return function ( a, b, c ) {
  3590. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3591. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3592. this.setFromNormalAndCoplanarPoint( normal, a );
  3593. return this;
  3594. };
  3595. }(),
  3596. copy: function ( plane ) {
  3597. this.normal.copy( plane.normal );
  3598. this.constant = plane.constant;
  3599. return this;
  3600. },
  3601. normalize: function () {
  3602. // Note: will lead to a divide by zero if the plane is invalid.
  3603. var inverseNormalLength = 1.0 / this.normal.length();
  3604. this.normal.multiplyScalar( inverseNormalLength );
  3605. this.constant *= inverseNormalLength;
  3606. return this;
  3607. },
  3608. negate: function () {
  3609. this.constant *= -1;
  3610. this.normal.negate();
  3611. return this;
  3612. },
  3613. distanceToPoint: function ( point ) {
  3614. return this.normal.dot( point ) + this.constant;
  3615. },
  3616. distanceToSphere: function ( sphere ) {
  3617. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3618. },
  3619. projectPoint: function ( point, optionalTarget ) {
  3620. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3621. },
  3622. orthoPoint: function ( point, optionalTarget ) {
  3623. var perpendicularMagnitude = this.distanceToPoint( point );
  3624. var result = optionalTarget || new THREE.Vector3();
  3625. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3626. },
  3627. isIntersectionLine: function ( line ) {
  3628. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3629. var startSign = this.distanceToPoint( line.start );
  3630. var endSign = this.distanceToPoint( line.end );
  3631. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3632. },
  3633. intersectLine: function() {
  3634. var v1 = new THREE.Vector3();
  3635. return function ( line, optionalTarget ) {
  3636. var result = optionalTarget || new THREE.Vector3();
  3637. var direction = line.delta( v1 );
  3638. var denominator = this.normal.dot( direction );
  3639. if ( denominator == 0 ) {
  3640. // line is coplanar, return origin
  3641. if( this.distanceToPoint( line.start ) == 0 ) {
  3642. return result.copy( line.start );
  3643. }
  3644. // Unsure if this is the correct method to handle this case.
  3645. return undefined;
  3646. }
  3647. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3648. if( t < 0 || t > 1 ) {
  3649. return undefined;
  3650. }
  3651. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3652. };
  3653. }(),
  3654. coplanarPoint: function ( optionalTarget ) {
  3655. var result = optionalTarget || new THREE.Vector3();
  3656. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3657. },
  3658. applyMatrix4: function() {
  3659. var v1 = new THREE.Vector3();
  3660. var v2 = new THREE.Vector3();
  3661. var m1 = new THREE.Matrix3();
  3662. return function ( matrix, optionalNormalMatrix ) {
  3663. // compute new normal based on theory here:
  3664. // http://www.songho.ca/opengl/gl_normaltransform.html
  3665. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3666. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3667. var newCoplanarPoint = this.coplanarPoint( v2 );
  3668. newCoplanarPoint.applyMatrix4( matrix );
  3669. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3670. return this;
  3671. };
  3672. }(),
  3673. translate: function ( offset ) {
  3674. this.constant = this.constant - offset.dot( this.normal );
  3675. return this;
  3676. },
  3677. equals: function ( plane ) {
  3678. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3679. },
  3680. clone: function () {
  3681. return new THREE.Plane().copy( this );
  3682. }
  3683. };
  3684. /**
  3685. * @author alteredq / http://alteredqualia.com/
  3686. * @author mrdoob / http://mrdoob.com/
  3687. */
  3688. THREE.Math = {
  3689. PI2: Math.PI * 2,
  3690. generateUUID: function () {
  3691. // http://www.broofa.com/Tools/Math.uuid.htm
  3692. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3693. var uuid = new Array(36);
  3694. var rnd = 0, r;
  3695. return function () {
  3696. for ( var i = 0; i < 36; i ++ ) {
  3697. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3698. uuid[ i ] = '-';
  3699. } else if ( i == 14 ) {
  3700. uuid[ i ] = '4';
  3701. } else {
  3702. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3703. r = rnd & 0xf;
  3704. rnd = rnd >> 4;
  3705. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3706. }
  3707. }
  3708. return uuid.join('');
  3709. };
  3710. }(),
  3711. // Clamp value to range <a, b>
  3712. clamp: function ( x, a, b ) {
  3713. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3714. },
  3715. // Clamp value to range <a, inf)
  3716. clampBottom: function ( x, a ) {
  3717. return x < a ? a : x;
  3718. },
  3719. // Linear mapping from range <a1, a2> to range <b1, b2>
  3720. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3721. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3722. },
  3723. // http://en.wikipedia.org/wiki/Smoothstep
  3724. smoothstep: function ( x, min, max ) {
  3725. if ( x <= min ) return 0;
  3726. if ( x >= max ) return 1;
  3727. x = ( x - min )/( max - min );
  3728. return x*x*(3 - 2*x);
  3729. },
  3730. smootherstep: function ( x, min, max ) {
  3731. if ( x <= min ) return 0;
  3732. if ( x >= max ) return 1;
  3733. x = ( x - min )/( max - min );
  3734. return x*x*x*(x*(x*6 - 15) + 10);
  3735. },
  3736. // Random float from <0, 1> with 16 bits of randomness
  3737. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3738. random16: function () {
  3739. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3740. },
  3741. // Random integer from <low, high> interval
  3742. randInt: function ( low, high ) {
  3743. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3744. },
  3745. // Random float from <low, high> interval
  3746. randFloat: function ( low, high ) {
  3747. return low + Math.random() * ( high - low );
  3748. },
  3749. // Random float from <-range/2, range/2> interval
  3750. randFloatSpread: function ( range ) {
  3751. return range * ( 0.5 - Math.random() );
  3752. },
  3753. sign: function ( x ) {
  3754. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0;
  3755. },
  3756. degToRad: function() {
  3757. var degreeToRadiansFactor = Math.PI / 180;
  3758. return function ( degrees ) {
  3759. return degrees * degreeToRadiansFactor;
  3760. };
  3761. }(),
  3762. radToDeg: function() {
  3763. var radianToDegreesFactor = 180 / Math.PI;
  3764. return function ( radians ) {
  3765. return radians * radianToDegreesFactor;
  3766. };
  3767. }(),
  3768. isPowerOfTwo: function ( value ) {
  3769. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3770. }
  3771. };
  3772. /**
  3773. * Spline from Tween.js, slightly optimized (and trashed)
  3774. * http://sole.github.com/tween.js/examples/05_spline.html
  3775. *
  3776. * @author mrdoob / http://mrdoob.com/
  3777. * @author alteredq / http://alteredqualia.com/
  3778. */
  3779. THREE.Spline = function ( points ) {
  3780. this.points = points;
  3781. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3782. point, intPoint, weight, w2, w3,
  3783. pa, pb, pc, pd;
  3784. this.initFromArray = function( a ) {
  3785. this.points = [];
  3786. for ( var i = 0; i < a.length; i++ ) {
  3787. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3788. }
  3789. };
  3790. this.getPoint = function ( k ) {
  3791. point = ( this.points.length - 1 ) * k;
  3792. intPoint = Math.floor( point );
  3793. weight = point - intPoint;
  3794. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3795. c[ 1 ] = intPoint;
  3796. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3797. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3798. pa = this.points[ c[ 0 ] ];
  3799. pb = this.points[ c[ 1 ] ];
  3800. pc = this.points[ c[ 2 ] ];
  3801. pd = this.points[ c[ 3 ] ];
  3802. w2 = weight * weight;
  3803. w3 = weight * w2;
  3804. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3805. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3806. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3807. return v3;
  3808. };
  3809. this.getControlPointsArray = function () {
  3810. var i, p, l = this.points.length,
  3811. coords = [];
  3812. for ( i = 0; i < l; i ++ ) {
  3813. p = this.points[ i ];
  3814. coords[ i ] = [ p.x, p.y, p.z ];
  3815. }
  3816. return coords;
  3817. };
  3818. // approximate length by summing linear segments
  3819. this.getLength = function ( nSubDivisions ) {
  3820. var i, index, nSamples, position,
  3821. point = 0, intPoint = 0, oldIntPoint = 0,
  3822. oldPosition = new THREE.Vector3(),
  3823. tmpVec = new THREE.Vector3(),
  3824. chunkLengths = [],
  3825. totalLength = 0;
  3826. // first point has 0 length
  3827. chunkLengths[ 0 ] = 0;
  3828. if ( !nSubDivisions ) nSubDivisions = 100;
  3829. nSamples = this.points.length * nSubDivisions;
  3830. oldPosition.copy( this.points[ 0 ] );
  3831. for ( i = 1; i < nSamples; i ++ ) {
  3832. index = i / nSamples;
  3833. position = this.getPoint( index );
  3834. tmpVec.copy( position );
  3835. totalLength += tmpVec.distanceTo( oldPosition );
  3836. oldPosition.copy( position );
  3837. point = ( this.points.length - 1 ) * index;
  3838. intPoint = Math.floor( point );
  3839. if ( intPoint != oldIntPoint ) {
  3840. chunkLengths[ intPoint ] = totalLength;
  3841. oldIntPoint = intPoint;
  3842. }
  3843. }
  3844. // last point ends with total length
  3845. chunkLengths[ chunkLengths.length ] = totalLength;
  3846. return { chunks: chunkLengths, total: totalLength };
  3847. };
  3848. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3849. var i, j,
  3850. index, indexCurrent, indexNext,
  3851. linearDistance, realDistance,
  3852. sampling, position,
  3853. newpoints = [],
  3854. tmpVec = new THREE.Vector3(),
  3855. sl = this.getLength();
  3856. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3857. for ( i = 1; i < this.points.length; i++ ) {
  3858. //tmpVec.copy( this.points[ i - 1 ] );
  3859. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3860. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3861. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3862. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3863. indexNext = i / ( this.points.length - 1 );
  3864. for ( j = 1; j < sampling - 1; j++ ) {
  3865. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3866. position = this.getPoint( index );
  3867. newpoints.push( tmpVec.copy( position ).clone() );
  3868. }
  3869. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3870. }
  3871. this.points = newpoints;
  3872. };
  3873. // Catmull-Rom
  3874. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3875. var v0 = ( p2 - p0 ) * 0.5,
  3876. v1 = ( p3 - p1 ) * 0.5;
  3877. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3878. };
  3879. };
  3880. /**
  3881. * @author bhouston / http://exocortex.com
  3882. * @author mrdoob / http://mrdoob.com/
  3883. */
  3884. THREE.Triangle = function ( a, b, c ) {
  3885. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3886. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3887. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3888. };
  3889. THREE.Triangle.normal = function() {
  3890. var v0 = new THREE.Vector3();
  3891. return function ( a, b, c, optionalTarget ) {
  3892. var result = optionalTarget || new THREE.Vector3();
  3893. result.subVectors( c, b );
  3894. v0.subVectors( a, b );
  3895. result.cross( v0 );
  3896. var resultLengthSq = result.lengthSq();
  3897. if( resultLengthSq > 0 ) {
  3898. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3899. }
  3900. return result.set( 0, 0, 0 );
  3901. };
  3902. }();
  3903. // static/instance method to calculate barycoordinates
  3904. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3905. THREE.Triangle.barycoordFromPoint = function() {
  3906. var v0 = new THREE.Vector3();
  3907. var v1 = new THREE.Vector3();
  3908. var v2 = new THREE.Vector3();
  3909. return function ( point, a, b, c, optionalTarget ) {
  3910. v0.subVectors( c, a );
  3911. v1.subVectors( b, a );
  3912. v2.subVectors( point, a );
  3913. var dot00 = v0.dot( v0 );
  3914. var dot01 = v0.dot( v1 );
  3915. var dot02 = v0.dot( v2 );
  3916. var dot11 = v1.dot( v1 );
  3917. var dot12 = v1.dot( v2 );
  3918. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3919. var result = optionalTarget || new THREE.Vector3();
  3920. // colinear or singular triangle
  3921. if( denom == 0 ) {
  3922. // arbitrary location outside of triangle?
  3923. // not sure if this is the best idea, maybe should be returning undefined
  3924. return result.set( -2, -1, -1 );
  3925. }
  3926. var invDenom = 1 / denom;
  3927. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3928. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3929. // barycoordinates must always sum to 1
  3930. return result.set( 1 - u - v, v, u );
  3931. };
  3932. }();
  3933. THREE.Triangle.containsPoint = function() {
  3934. var v1 = new THREE.Vector3();
  3935. return function ( point, a, b, c ) {
  3936. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3937. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3938. };
  3939. }();
  3940. THREE.Triangle.prototype = {
  3941. constructor: THREE.Triangle,
  3942. set: function ( a, b, c ) {
  3943. this.a.copy( a );
  3944. this.b.copy( b );
  3945. this.c.copy( c );
  3946. return this;
  3947. },
  3948. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3949. this.a.copy( points[i0] );
  3950. this.b.copy( points[i1] );
  3951. this.c.copy( points[i2] );
  3952. return this;
  3953. },
  3954. copy: function ( triangle ) {
  3955. this.a.copy( triangle.a );
  3956. this.b.copy( triangle.b );
  3957. this.c.copy( triangle.c );
  3958. return this;
  3959. },
  3960. area: function() {
  3961. var v0 = new THREE.Vector3();
  3962. var v1 = new THREE.Vector3();
  3963. return function () {
  3964. v0.subVectors( this.c, this.b );
  3965. v1.subVectors( this.a, this.b );
  3966. return v0.cross( v1 ).length() * 0.5;
  3967. };
  3968. }(),
  3969. midpoint: function ( optionalTarget ) {
  3970. var result = optionalTarget || new THREE.Vector3();
  3971. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3972. },
  3973. normal: function ( optionalTarget ) {
  3974. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3975. },
  3976. plane: function ( optionalTarget ) {
  3977. var result = optionalTarget || new THREE.Plane();
  3978. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3979. },
  3980. barycoordFromPoint: function ( point, optionalTarget ) {
  3981. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3982. },
  3983. containsPoint: function ( point ) {
  3984. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3985. },
  3986. equals: function ( triangle ) {
  3987. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3988. },
  3989. clone: function () {
  3990. return new THREE.Triangle().copy( this );
  3991. }
  3992. };
  3993. /**
  3994. * @author mrdoob / http://mrdoob.com/
  3995. */
  3996. THREE.Vertex = function ( v ) {
  3997. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3998. return v;
  3999. };
  4000. /**
  4001. * @author mrdoob / http://mrdoob.com/
  4002. */
  4003. THREE.UV = function ( u, v ) {
  4004. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  4005. return new THREE.Vector2( u, v );
  4006. };
  4007. /**
  4008. * @author alteredq / http://alteredqualia.com/
  4009. */
  4010. THREE.Clock = function ( autoStart ) {
  4011. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4012. this.startTime = 0;
  4013. this.oldTime = 0;
  4014. this.elapsedTime = 0;
  4015. this.running = false;
  4016. };
  4017. THREE.Clock.prototype = {
  4018. constructor: THREE.Clock,
  4019. start: function () {
  4020. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  4021. ? self.performance.now()
  4022. : Date.now();
  4023. this.oldTime = this.startTime;
  4024. this.running = true;
  4025. },
  4026. stop: function () {
  4027. this.getElapsedTime();
  4028. this.running = false;
  4029. },
  4030. getElapsedTime: function () {
  4031. this.getDelta();
  4032. return this.elapsedTime;
  4033. },
  4034. getDelta: function () {
  4035. var diff = 0;
  4036. if ( this.autoStart && ! this.running ) {
  4037. this.start();
  4038. }
  4039. if ( this.running ) {
  4040. var newTime = self.performance !== undefined && self.performance.now !== undefined
  4041. ? self.performance.now()
  4042. : Date.now();
  4043. diff = 0.001 * ( newTime - this.oldTime );
  4044. this.oldTime = newTime;
  4045. this.elapsedTime += diff;
  4046. }
  4047. return diff;
  4048. }
  4049. };
  4050. /**
  4051. * https://github.com/mrdoob/eventdispatcher.js/
  4052. */
  4053. THREE.EventDispatcher = function () {}
  4054. THREE.EventDispatcher.prototype = {
  4055. constructor: THREE.EventDispatcher,
  4056. apply: function ( object ) {
  4057. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4058. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4059. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4060. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4061. },
  4062. addEventListener: function ( type, listener ) {
  4063. if ( this._listeners === undefined ) this._listeners = {};
  4064. var listeners = this._listeners;
  4065. if ( listeners[ type ] === undefined ) {
  4066. listeners[ type ] = [];
  4067. }
  4068. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4069. listeners[ type ].push( listener );
  4070. }
  4071. },
  4072. hasEventListener: function ( type, listener ) {
  4073. if ( this._listeners === undefined ) return false;
  4074. var listeners = this._listeners;
  4075. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4076. return true;
  4077. }
  4078. return false;
  4079. },
  4080. removeEventListener: function ( type, listener ) {
  4081. if ( this._listeners === undefined ) return;
  4082. var listeners = this._listeners;
  4083. var listenerArray = listeners[ type ];
  4084. if ( listenerArray !== undefined ) {
  4085. var index = listenerArray.indexOf( listener );
  4086. if ( index !== - 1 ) {
  4087. listenerArray.splice( index, 1 );
  4088. }
  4089. }
  4090. },
  4091. dispatchEvent: function () {
  4092. var array = [];
  4093. return function ( event ) {
  4094. if ( this._listeners === undefined ) return;
  4095. var listeners = this._listeners;
  4096. var listenerArray = listeners[ event.type ];
  4097. if ( listenerArray !== undefined ) {
  4098. event.target = this;
  4099. var length = listenerArray.length;
  4100. for ( var i = 0; i < length; i ++ ) {
  4101. array[ i ] = listenerArray[ i ];
  4102. }
  4103. for ( var i = 0; i < length; i ++ ) {
  4104. array[ i ].call( this, event );
  4105. }
  4106. }
  4107. };
  4108. }()
  4109. };
  4110. /**
  4111. * @author mrdoob / http://mrdoob.com/
  4112. * @author bhouston / http://exocortex.com/
  4113. * @author stephomi / http://stephaneginier.com/
  4114. */
  4115. ( function ( THREE ) {
  4116. THREE.Raycaster = function ( origin, direction, near, far ) {
  4117. this.ray = new THREE.Ray( origin, direction );
  4118. // direction is assumed to be normalized (for accurate distance calculations)
  4119. this.near = near || 0;
  4120. this.far = far || Infinity;
  4121. };
  4122. var sphere = new THREE.Sphere();
  4123. var localRay = new THREE.Ray();
  4124. var facePlane = new THREE.Plane();
  4125. var intersectPoint = new THREE.Vector3();
  4126. var matrixPosition = new THREE.Vector3();
  4127. var inverseMatrix = new THREE.Matrix4();
  4128. var descSort = function ( a, b ) {
  4129. return a.distance - b.distance;
  4130. };
  4131. var vA = new THREE.Vector3();
  4132. var vB = new THREE.Vector3();
  4133. var vC = new THREE.Vector3();
  4134. var intersectObject = function ( object, raycaster, intersects ) {
  4135. if ( object instanceof THREE.Sprite ) {
  4136. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4137. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  4138. if ( distance > object.scale.x ) {
  4139. return intersects;
  4140. }
  4141. intersects.push( {
  4142. distance: distance,
  4143. point: object.position,
  4144. face: null,
  4145. object: object
  4146. } );
  4147. } else if ( object instanceof THREE.LOD ) {
  4148. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4149. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  4150. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  4151. } else if ( object instanceof THREE.Mesh ) {
  4152. var geometry = object.geometry;
  4153. // Checking boundingSphere distance to ray
  4154. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4155. sphere.copy( geometry.boundingSphere );
  4156. sphere.applyMatrix4( object.matrixWorld );
  4157. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4158. return intersects;
  4159. }
  4160. // Check boundingBox before continuing
  4161. inverseMatrix.getInverse( object.matrixWorld );
  4162. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4163. if ( geometry.boundingBox !== null ) {
  4164. if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) {
  4165. return intersects;
  4166. }
  4167. }
  4168. if ( geometry instanceof THREE.BufferGeometry ) {
  4169. var material = object.material;
  4170. if ( material === undefined ) return intersects;
  4171. var attributes = geometry.attributes;
  4172. var a, b, c;
  4173. var precision = raycaster.precision;
  4174. if ( attributes.index !== undefined ) {
  4175. var offsets = geometry.offsets;
  4176. var indices = attributes.index.array;
  4177. var positions = attributes.position.array;
  4178. for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {
  4179. var start = offsets[ oi ].start;
  4180. var count = offsets[ oi ].count;
  4181. var index = offsets[ oi ].index;
  4182. for ( var i = start, il = start + count; i < il; i += 3 ) {
  4183. a = index + indices[ i ];
  4184. b = index + indices[ i + 1 ];
  4185. c = index + indices[ i + 2 ];
  4186. vA.set(
  4187. positions[ a * 3 ],
  4188. positions[ a * 3 + 1 ],
  4189. positions[ a * 3 + 2 ]
  4190. );
  4191. vB.set(
  4192. positions[ b * 3 ],
  4193. positions[ b * 3 + 1 ],
  4194. positions[ b * 3 + 2 ]
  4195. );
  4196. vC.set(
  4197. positions[ c * 3 ],
  4198. positions[ c * 3 + 1 ],
  4199. positions[ c * 3 + 2 ]
  4200. );
  4201. if ( material.side === THREE.BackSide ) {
  4202. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4203. } else {
  4204. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4205. }
  4206. if ( intersectionPoint === null ) continue;
  4207. intersectionPoint.applyMatrix4( object.matrixWorld );
  4208. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4209. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4210. intersects.push( {
  4211. distance: distance,
  4212. point: intersectionPoint,
  4213. indices: [a, b, c],
  4214. face: null,
  4215. faceIndex: null,
  4216. object: object
  4217. } );
  4218. }
  4219. }
  4220. } else {
  4221. var offsets = geometry.offsets;
  4222. var positions = attributes.position.array;
  4223. for ( var i = 0, il = attributes.position.array.length; i < il; i += 3 ) {
  4224. a = i;
  4225. b = i + 1;
  4226. c = i + 2;
  4227. vA.set(
  4228. positions[ a * 3 ],
  4229. positions[ a * 3 + 1 ],
  4230. positions[ a * 3 + 2 ]
  4231. );
  4232. vB.set(
  4233. positions[ b * 3 ],
  4234. positions[ b * 3 + 1 ],
  4235. positions[ b * 3 + 2 ]
  4236. );
  4237. vC.set(
  4238. positions[ c * 3 ],
  4239. positions[ c * 3 + 1 ],
  4240. positions[ c * 3 + 2 ]
  4241. );
  4242. if ( material.side === THREE.BackSide ) {
  4243. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4244. } else {
  4245. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4246. }
  4247. if ( intersectionPoint === null ) continue;
  4248. intersectionPoint.applyMatrix4( object.matrixWorld );
  4249. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4250. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4251. intersects.push( {
  4252. distance: distance,
  4253. point: intersectionPoint,
  4254. indices: [a, b, c],
  4255. face: null,
  4256. faceIndex: null,
  4257. object: object
  4258. } );
  4259. }
  4260. }
  4261. } else if ( geometry instanceof THREE.Geometry ) {
  4262. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4263. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4264. var a, b, c, d;
  4265. var precision = raycaster.precision;
  4266. var vertices = geometry.vertices;
  4267. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4268. var face = geometry.faces[ f ];
  4269. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4270. if ( material === undefined ) continue;
  4271. a = vertices[ face.a ];
  4272. b = vertices[ face.b ];
  4273. c = vertices[ face.c ];
  4274. if ( material.morphTargets === true ) {
  4275. var morphTargets = geometry.morphTargets;
  4276. var morphInfluences = object.morphTargetInfluences;
  4277. vA.set( 0, 0, 0 );
  4278. vB.set( 0, 0, 0 );
  4279. vC.set( 0, 0, 0 );
  4280. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4281. var influence = morphInfluences[ t ];
  4282. if ( influence === 0 ) continue;
  4283. var targets = morphTargets[ t ].vertices;
  4284. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  4285. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  4286. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  4287. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  4288. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  4289. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  4290. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  4291. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  4292. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  4293. }
  4294. vA.add( a );
  4295. vB.add( b );
  4296. vC.add( c );
  4297. a = vA;
  4298. b = vB;
  4299. c = vC;
  4300. }
  4301. if ( material.side === THREE.BackSide ) {
  4302. var intersectionPoint = localRay.intersectTriangle( c, b, a, true );
  4303. } else {
  4304. var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  4305. }
  4306. if ( intersectionPoint === null ) continue;
  4307. intersectionPoint.applyMatrix4( object.matrixWorld );
  4308. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4309. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4310. intersects.push( {
  4311. distance: distance,
  4312. point: intersectionPoint,
  4313. face: face,
  4314. faceIndex: f,
  4315. object: object
  4316. } );
  4317. }
  4318. }
  4319. } else if ( object instanceof THREE.Line ) {
  4320. var precision = raycaster.linePrecision;
  4321. var precisionSq = precision * precision;
  4322. var geometry = object.geometry;
  4323. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4324. // Checking boundingSphere distance to ray
  4325. sphere.copy( geometry.boundingSphere );
  4326. sphere.applyMatrix4( object.matrixWorld );
  4327. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4328. return intersects;
  4329. }
  4330. inverseMatrix.getInverse( object.matrixWorld );
  4331. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4332. /* if ( geometry instanceof THREE.BufferGeometry ) {
  4333. } else */ if ( geometry instanceof THREE.Geometry ) {
  4334. var vertices = geometry.vertices;
  4335. var nbVertices = vertices.length;
  4336. var interSegment = new THREE.Vector3();
  4337. var interRay = new THREE.Vector3();
  4338. var step = object.type === THREE.LineStrip ? 1 : 2;
  4339. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4340. var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4341. if ( distSq > precisionSq ) continue;
  4342. var distance = localRay.origin.distanceTo( interRay );
  4343. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4344. intersects.push( {
  4345. distance: distance,
  4346. // What do we want? intersection point on the ray or on the segment??
  4347. // point: raycaster.ray.at( distance ),
  4348. point: interSegment.clone().applyMatrix4( object.matrixWorld ),
  4349. face: null,
  4350. faceIndex: null,
  4351. object: object
  4352. } );
  4353. }
  4354. }
  4355. }
  4356. };
  4357. var intersectDescendants = function ( object, raycaster, intersects ) {
  4358. var descendants = object.getDescendants();
  4359. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4360. intersectObject( descendants[ i ], raycaster, intersects );
  4361. }
  4362. };
  4363. //
  4364. THREE.Raycaster.prototype.precision = 0.0001;
  4365. THREE.Raycaster.prototype.linePrecision = 1;
  4366. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4367. this.ray.set( origin, direction );
  4368. // direction is assumed to be normalized (for accurate distance calculations)
  4369. };
  4370. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4371. var intersects = [];
  4372. if ( recursive === true ) {
  4373. intersectDescendants( object, this, intersects );
  4374. }
  4375. intersectObject( object, this, intersects );
  4376. intersects.sort( descSort );
  4377. return intersects;
  4378. };
  4379. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4380. var intersects = [];
  4381. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4382. intersectObject( objects[ i ], this, intersects );
  4383. if ( recursive === true ) {
  4384. intersectDescendants( objects[ i ], this, intersects );
  4385. }
  4386. }
  4387. intersects.sort( descSort );
  4388. return intersects;
  4389. };
  4390. }( THREE ) );
  4391. /**
  4392. * @author mrdoob / http://mrdoob.com/
  4393. * @author mikael emtinger / http://gomo.se/
  4394. * @author alteredq / http://alteredqualia.com/
  4395. * @author WestLangley / http://github.com/WestLangley
  4396. */
  4397. THREE.Object3D = function () {
  4398. this.id = THREE.Object3DIdCount ++;
  4399. this.uuid = THREE.Math.generateUUID();
  4400. this.name = '';
  4401. this.parent = undefined;
  4402. this.children = [];
  4403. this.up = new THREE.Vector3( 0, 1, 0 );
  4404. this.position = new THREE.Vector3();
  4405. this._rotation = new THREE.Euler();
  4406. this._quaternion = new THREE.Quaternion();
  4407. this.scale = new THREE.Vector3( 1, 1, 1 );
  4408. // keep rotation and quaternion in sync
  4409. this._rotation._quaternion = this.quaternion;
  4410. this._quaternion._euler = this.rotation;
  4411. this.renderDepth = null;
  4412. this.rotationAutoUpdate = true;
  4413. this.matrix = new THREE.Matrix4();
  4414. this.matrixWorld = new THREE.Matrix4();
  4415. this.matrixAutoUpdate = true;
  4416. this.matrixWorldNeedsUpdate = true;
  4417. this.visible = true;
  4418. this.castShadow = false;
  4419. this.receiveShadow = false;
  4420. this.frustumCulled = true;
  4421. this.userData = {};
  4422. };
  4423. THREE.Object3D.prototype = {
  4424. constructor: THREE.Object3D,
  4425. get rotation () {
  4426. return this._rotation;
  4427. },
  4428. set rotation ( value ) {
  4429. this._rotation = value;
  4430. this._rotation._quaternion = this._quaternion;
  4431. this._quaternion._euler = this._rotation;
  4432. this._rotation._updateQuaternion();
  4433. },
  4434. get quaternion () {
  4435. return this._quaternion;
  4436. },
  4437. set quaternion ( value ) {
  4438. this._quaternion = value;
  4439. this._quaternion._euler = this._rotation;
  4440. this._rotation._quaternion = this._quaternion;
  4441. this._quaternion._updateEuler();
  4442. },
  4443. get eulerOrder () {
  4444. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4445. return this.rotation.order;
  4446. },
  4447. set eulerOrder ( value ) {
  4448. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4449. this.rotation.order = value;
  4450. },
  4451. get useQuaternion () {
  4452. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4453. },
  4454. set useQuaternion ( value ) {
  4455. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4456. },
  4457. applyMatrix: function ( matrix ) {
  4458. this.matrix.multiplyMatrices( matrix, this.matrix );
  4459. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4460. },
  4461. setRotationFromAxisAngle: function ( axis, angle ) {
  4462. // assumes axis is normalized
  4463. this.quaternion.setFromAxisAngle( axis, angle );
  4464. },
  4465. setRotationFromEuler: function ( euler ) {
  4466. this.quaternion.setFromEuler( euler, true );
  4467. },
  4468. setRotationFromMatrix: function ( m ) {
  4469. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4470. this.quaternion.setFromRotationMatrix( m );
  4471. },
  4472. setRotationFromQuaternion: function ( q ) {
  4473. // assumes q is normalized
  4474. this.quaternion.copy( q );
  4475. },
  4476. rotateOnAxis: function() {
  4477. // rotate object on axis in object space
  4478. // axis is assumed to be normalized
  4479. var q1 = new THREE.Quaternion();
  4480. return function ( axis, angle ) {
  4481. q1.setFromAxisAngle( axis, angle );
  4482. this.quaternion.multiply( q1 );
  4483. return this;
  4484. }
  4485. }(),
  4486. rotateX: function () {
  4487. var v1 = new THREE.Vector3( 1, 0, 0 );
  4488. return function ( angle ) {
  4489. return this.rotateOnAxis( v1, angle );
  4490. };
  4491. }(),
  4492. rotateY: function () {
  4493. var v1 = new THREE.Vector3( 0, 1, 0 );
  4494. return function ( angle ) {
  4495. return this.rotateOnAxis( v1, angle );
  4496. };
  4497. }(),
  4498. rotateZ: function () {
  4499. var v1 = new THREE.Vector3( 0, 0, 1 );
  4500. return function ( angle ) {
  4501. return this.rotateOnAxis( v1, angle );
  4502. };
  4503. }(),
  4504. translateOnAxis: function () {
  4505. // translate object by distance along axis in object space
  4506. // axis is assumed to be normalized
  4507. var v1 = new THREE.Vector3();
  4508. return function ( axis, distance ) {
  4509. v1.copy( axis );
  4510. v1.applyQuaternion( this.quaternion );
  4511. this.position.add( v1.multiplyScalar( distance ) );
  4512. return this;
  4513. }
  4514. }(),
  4515. translate: function ( distance, axis ) {
  4516. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4517. return this.translateOnAxis( axis, distance );
  4518. },
  4519. translateX: function () {
  4520. var v1 = new THREE.Vector3( 1, 0, 0 );
  4521. return function ( distance ) {
  4522. return this.translateOnAxis( v1, distance );
  4523. };
  4524. }(),
  4525. translateY: function () {
  4526. var v1 = new THREE.Vector3( 0, 1, 0 );
  4527. return function ( distance ) {
  4528. return this.translateOnAxis( v1, distance );
  4529. };
  4530. }(),
  4531. translateZ: function () {
  4532. var v1 = new THREE.Vector3( 0, 0, 1 );
  4533. return function ( distance ) {
  4534. return this.translateOnAxis( v1, distance );
  4535. };
  4536. }(),
  4537. localToWorld: function ( vector ) {
  4538. return vector.applyMatrix4( this.matrixWorld );
  4539. },
  4540. worldToLocal: function () {
  4541. var m1 = new THREE.Matrix4();
  4542. return function ( vector ) {
  4543. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4544. };
  4545. }(),
  4546. lookAt: function () {
  4547. // This routine does not support objects with rotated and/or translated parent(s)
  4548. var m1 = new THREE.Matrix4();
  4549. return function ( vector ) {
  4550. m1.lookAt( vector, this.position, this.up );
  4551. this.quaternion.setFromRotationMatrix( m1 );
  4552. };
  4553. }(),
  4554. add: function ( object ) {
  4555. if ( object === this ) {
  4556. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4557. return;
  4558. }
  4559. if ( object instanceof THREE.Object3D ) {
  4560. if ( object.parent !== undefined ) {
  4561. object.parent.remove( object );
  4562. }
  4563. object.parent = this;
  4564. object.dispatchEvent( { type: 'added' } );
  4565. this.children.push( object );
  4566. // add to scene
  4567. var scene = this;
  4568. while ( scene.parent !== undefined ) {
  4569. scene = scene.parent;
  4570. }
  4571. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4572. scene.__addObject( object );
  4573. }
  4574. }
  4575. },
  4576. remove: function ( object ) {
  4577. var index = this.children.indexOf( object );
  4578. if ( index !== - 1 ) {
  4579. object.parent = undefined;
  4580. object.dispatchEvent( { type: 'removed' } );
  4581. this.children.splice( index, 1 );
  4582. // remove from scene
  4583. var scene = this;
  4584. while ( scene.parent !== undefined ) {
  4585. scene = scene.parent;
  4586. }
  4587. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4588. scene.__removeObject( object );
  4589. }
  4590. }
  4591. },
  4592. traverse: function ( callback ) {
  4593. callback( this );
  4594. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4595. this.children[ i ].traverse( callback );
  4596. }
  4597. },
  4598. getObjectById: function ( id, recursive ) {
  4599. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4600. var child = this.children[ i ];
  4601. if ( child.id === id ) {
  4602. return child;
  4603. }
  4604. if ( recursive === true ) {
  4605. child = child.getObjectById( id, recursive );
  4606. if ( child !== undefined ) {
  4607. return child;
  4608. }
  4609. }
  4610. }
  4611. return undefined;
  4612. },
  4613. getObjectByName: function ( name, recursive ) {
  4614. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4615. var child = this.children[ i ];
  4616. if ( child.name === name ) {
  4617. return child;
  4618. }
  4619. if ( recursive === true ) {
  4620. child = child.getObjectByName( name, recursive );
  4621. if ( child !== undefined ) {
  4622. return child;
  4623. }
  4624. }
  4625. }
  4626. return undefined;
  4627. },
  4628. getChildByName: function ( name, recursive ) {
  4629. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4630. return this.getObjectByName( name, recursive );
  4631. },
  4632. getDescendants: function ( array ) {
  4633. if ( array === undefined ) array = [];
  4634. Array.prototype.push.apply( array, this.children );
  4635. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4636. this.children[ i ].getDescendants( array );
  4637. }
  4638. return array;
  4639. },
  4640. updateMatrix: function () {
  4641. this.matrix.compose( this.position, this.quaternion, this.scale );
  4642. this.matrixWorldNeedsUpdate = true;
  4643. },
  4644. updateMatrixWorld: function ( force ) {
  4645. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4646. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4647. if ( this.parent === undefined ) {
  4648. this.matrixWorld.copy( this.matrix );
  4649. } else {
  4650. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4651. }
  4652. this.matrixWorldNeedsUpdate = false;
  4653. force = true;
  4654. }
  4655. // update children
  4656. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4657. this.children[ i ].updateMatrixWorld( force );
  4658. }
  4659. },
  4660. clone: function ( object, recursive ) {
  4661. if ( object === undefined ) object = new THREE.Object3D();
  4662. if ( recursive === undefined ) recursive = true;
  4663. object.name = this.name;
  4664. object.up.copy( this.up );
  4665. object.position.copy( this.position );
  4666. object.quaternion.copy( this.quaternion );
  4667. object.scale.copy( this.scale );
  4668. object.renderDepth = this.renderDepth;
  4669. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4670. object.matrix.copy( this.matrix );
  4671. object.matrixWorld.copy( this.matrixWorld );
  4672. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4673. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4674. object.visible = this.visible;
  4675. object.castShadow = this.castShadow;
  4676. object.receiveShadow = this.receiveShadow;
  4677. object.frustumCulled = this.frustumCulled;
  4678. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4679. if ( recursive === true ) {
  4680. for ( var i = 0; i < this.children.length; i ++ ) {
  4681. var child = this.children[ i ];
  4682. object.add( child.clone() );
  4683. }
  4684. }
  4685. return object;
  4686. }
  4687. };
  4688. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4689. THREE.Object3DIdCount = 0;
  4690. /**
  4691. * @author mrdoob / http://mrdoob.com/
  4692. * @author supereggbert / http://www.paulbrunt.co.uk/
  4693. * @author julianwa / https://github.com/julianwa
  4694. */
  4695. THREE.Projector = function () {
  4696. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4697. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4698. _face, _faceCount, _facePool = [], _facePoolLength = 0,
  4699. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4700. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4701. _renderData = { objects: [], lights: [], elements: [] },
  4702. _vA = new THREE.Vector3(),
  4703. _vB = new THREE.Vector3(),
  4704. _vC = new THREE.Vector3(),
  4705. _vector3 = new THREE.Vector3(),
  4706. _vector4 = new THREE.Vector4(),
  4707. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4708. _boundingBox = new THREE.Box3(),
  4709. _points3 = new Array( 3 ),
  4710. _points4 = new Array( 4 ),
  4711. _viewMatrix = new THREE.Matrix4(),
  4712. _viewProjectionMatrix = new THREE.Matrix4(),
  4713. _modelMatrix,
  4714. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4715. _normalMatrix = new THREE.Matrix3(),
  4716. _frustum = new THREE.Frustum(),
  4717. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4718. _clippedVertex2PositionScreen = new THREE.Vector4();
  4719. this.projectVector = function ( vector, camera ) {
  4720. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4721. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4722. return vector.applyProjection( _viewProjectionMatrix );
  4723. };
  4724. this.unprojectVector = function () {
  4725. var projectionMatrixInverse = new THREE.Matrix4();
  4726. return function ( vector, camera ) {
  4727. projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4728. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse );
  4729. return vector.applyProjection( _viewProjectionMatrix );
  4730. };
  4731. }();
  4732. this.pickingRay = function ( vector, camera ) {
  4733. // set two vectors with opposing z values
  4734. vector.z = -1.0;
  4735. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4736. this.unprojectVector( vector, camera );
  4737. this.unprojectVector( end, camera );
  4738. // find direction from vector to end
  4739. end.sub( vector ).normalize();
  4740. return new THREE.Raycaster( vector, end );
  4741. };
  4742. var projectObject = function ( object ) {
  4743. if ( object.visible === false ) return;
  4744. if ( object instanceof THREE.Light ) {
  4745. _renderData.lights.push( object );
  4746. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Sprite ) {
  4747. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4748. _object = getNextObjectInPool();
  4749. _object.id = object.id;
  4750. _object.object = object;
  4751. if ( object.renderDepth !== null ) {
  4752. _object.z = object.renderDepth;
  4753. } else {
  4754. _vector3.setFromMatrixPosition( object.matrixWorld );
  4755. _vector3.applyProjection( _viewProjectionMatrix );
  4756. _object.z = _vector3.z;
  4757. }
  4758. _renderData.objects.push( _object );
  4759. }
  4760. }
  4761. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4762. projectObject( object.children[ i ] );
  4763. }
  4764. };
  4765. var projectGraph = function ( root, sortObjects ) {
  4766. _objectCount = 0;
  4767. _renderData.objects.length = 0;
  4768. _renderData.lights.length = 0;
  4769. projectObject( root );
  4770. if ( sortObjects === true ) {
  4771. _renderData.objects.sort( painterSort );
  4772. }
  4773. };
  4774. var RenderList = function () {
  4775. var normals = [];
  4776. var object = null;
  4777. var normalMatrix = new THREE.Matrix3();
  4778. var setObject = function ( value ) {
  4779. object = value;
  4780. normalMatrix.getNormalMatrix( object.matrixWorld );
  4781. normals.length = 0;
  4782. };
  4783. var projectVertex = function ( vertex ) {
  4784. var position = vertex.position;
  4785. var positionWorld = vertex.positionWorld;
  4786. var positionScreen = vertex.positionScreen;
  4787. positionWorld.copy( position ).applyMatrix4( _modelMatrix );
  4788. positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4789. var invW = 1 / positionScreen.w;
  4790. positionScreen.x *= invW;
  4791. positionScreen.y *= invW;
  4792. positionScreen.z *= invW;
  4793. vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 &&
  4794. positionScreen.y >= -1 && positionScreen.y <= 1 &&
  4795. positionScreen.z >= -1 && positionScreen.z <= 1;
  4796. };
  4797. var pushVertex = function ( x, y, z ) {
  4798. _vertex = getNextVertexInPool();
  4799. _vertex.position.set( x, y, z );
  4800. projectVertex( _vertex );
  4801. };
  4802. var pushNormal = function ( x, y, z ) {
  4803. normals.push( x, y, z );
  4804. };
  4805. var checkTriangleVisibility = function ( v1, v2, v3 ) {
  4806. _points3[ 0 ] = v1.positionScreen;
  4807. _points3[ 1 ] = v2.positionScreen;
  4808. _points3[ 2 ] = v3.positionScreen;
  4809. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4810. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4811. return ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4812. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4813. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4814. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4815. }
  4816. return false;
  4817. };
  4818. var pushLine = function ( a, b ) {
  4819. var v1 = _vertexPool[ a ];
  4820. var v2 = _vertexPool[ b ];
  4821. _line = getNextLineInPool();
  4822. _line.id = object.id;
  4823. _line.v1.copy( v1 );
  4824. _line.v2.copy( v2 );
  4825. _line.z = ( v1.positionScreen.z + v2.positionScreen.z ) / 2;
  4826. _line.material = object.material;
  4827. _renderData.elements.push( _line );
  4828. };
  4829. var pushTriangle = function ( a, b, c ) {
  4830. var v1 = _vertexPool[ a ];
  4831. var v2 = _vertexPool[ b ];
  4832. var v3 = _vertexPool[ c ];
  4833. if ( checkTriangleVisibility( v1, v2, v3 ) === true ) {
  4834. _face = getNextFaceInPool();
  4835. _face.id = object.id;
  4836. _face.v1.copy( v1 );
  4837. _face.v2.copy( v2 );
  4838. _face.v3.copy( v3 );
  4839. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4840. for ( var i = 0; i < 3; i ++ ) {
  4841. var offset = arguments[ i ] * 3;
  4842. var normal = _face.vertexNormalsModel[ i ];
  4843. normal.set( normals[ offset + 0 ], normals[ offset + 1 ], normals[ offset + 2 ] );
  4844. normal.applyMatrix3( normalMatrix ).normalize();
  4845. }
  4846. _face.vertexNormalsLength = 3;
  4847. _face.material = object.material;
  4848. _renderData.elements.push( _face );
  4849. }
  4850. };
  4851. return {
  4852. setObject: setObject,
  4853. projectVertex: projectVertex,
  4854. checkTriangleVisibility: checkTriangleVisibility,
  4855. pushVertex: pushVertex,
  4856. pushNormal: pushNormal,
  4857. pushLine: pushLine,
  4858. pushTriangle: pushTriangle
  4859. }
  4860. };
  4861. var renderList = new RenderList();
  4862. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4863. var object, geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4864. isFaceMaterial, objectMaterials;
  4865. _faceCount = 0;
  4866. _lineCount = 0;
  4867. _spriteCount = 0;
  4868. _renderData.elements.length = 0;
  4869. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4870. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4871. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4872. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4873. _frustum.setFromMatrix( _viewProjectionMatrix );
  4874. projectGraph( scene, sortObjects );
  4875. for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4876. object = _renderData.objects[ o ].object;
  4877. geometry = object.geometry;
  4878. renderList.setObject( object );
  4879. _modelMatrix = object.matrixWorld;
  4880. _vertexCount = 0;
  4881. if ( object instanceof THREE.Mesh ) {
  4882. if ( geometry instanceof THREE.BufferGeometry ) {
  4883. var attributes = geometry.attributes;
  4884. var offsets = geometry.offsets;
  4885. if ( attributes.position === undefined ) continue;
  4886. var positions = attributes.position.array;
  4887. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4888. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4889. }
  4890. var normals = attributes.normal.array;
  4891. for ( var i = 0, l = normals.length; i < l; i += 3 ) {
  4892. renderList.pushNormal( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] );
  4893. }
  4894. if ( attributes.index !== undefined ) {
  4895. var indices = attributes.index.array;
  4896. if ( offsets.length > 0 ) {
  4897. for ( var o = 0; o < offsets.length; o ++ ) {
  4898. var offset = offsets[ o ];
  4899. var index = offset.index;
  4900. for ( var i = offset.start, l = offset.start + offset.count; i < l; i += 3 ) {
  4901. renderList.pushTriangle( indices[ i ] + index, indices[ i + 1 ] + index, indices[ i + 2 ] + index );
  4902. }
  4903. }
  4904. } else {
  4905. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  4906. renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  4907. }
  4908. }
  4909. } else {
  4910. for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) {
  4911. renderList.pushTriangle( i, i + 1, i + 2 );
  4912. }
  4913. }
  4914. } else if ( geometry instanceof THREE.Geometry ) {
  4915. vertices = geometry.vertices;
  4916. faces = geometry.faces;
  4917. faceVertexUvs = geometry.faceVertexUvs;
  4918. _normalMatrix.getNormalMatrix( _modelMatrix );
  4919. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4920. objectMaterials = isFaceMaterial === true ? object.material : null;
  4921. for ( var v = 0, vl = vertices.length; v < vl; v ++ ) {
  4922. var vertex = vertices[ v ];
  4923. renderList.pushVertex( vertex.x, vertex.y, vertex.z );
  4924. }
  4925. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  4926. face = faces[ f ];
  4927. var material = isFaceMaterial === true
  4928. ? objectMaterials.materials[ face.materialIndex ]
  4929. : object.material;
  4930. if ( material === undefined ) continue;
  4931. var side = material.side;
  4932. var v1 = _vertexPool[ face.a ];
  4933. var v2 = _vertexPool[ face.b ];
  4934. var v3 = _vertexPool[ face.c ];
  4935. if ( material.morphTargets === true ) {
  4936. var morphTargets = geometry.morphTargets;
  4937. var morphInfluences = object.morphTargetInfluences;
  4938. var v1p = v1.position;
  4939. var v2p = v2.position;
  4940. var v3p = v3.position;
  4941. _vA.set( 0, 0, 0 );
  4942. _vB.set( 0, 0, 0 );
  4943. _vC.set( 0, 0, 0 );
  4944. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4945. var influence = morphInfluences[ t ];
  4946. if ( influence === 0 ) continue;
  4947. var targets = morphTargets[ t ].vertices;
  4948. _vA.x += ( targets[ face.a ].x - v1p.x ) * influence;
  4949. _vA.y += ( targets[ face.a ].y - v1p.y ) * influence;
  4950. _vA.z += ( targets[ face.a ].z - v1p.z ) * influence;
  4951. _vB.x += ( targets[ face.b ].x - v2p.x ) * influence;
  4952. _vB.y += ( targets[ face.b ].y - v2p.y ) * influence;
  4953. _vB.z += ( targets[ face.b ].z - v2p.z ) * influence;
  4954. _vC.x += ( targets[ face.c ].x - v3p.x ) * influence;
  4955. _vC.y += ( targets[ face.c ].y - v3p.y ) * influence;
  4956. _vC.z += ( targets[ face.c ].z - v3p.z ) * influence;
  4957. }
  4958. v1.position.add( _vA );
  4959. v2.position.add( _vB );
  4960. v3.position.add( _vC );
  4961. renderList.projectVertex( v1 );
  4962. renderList.projectVertex( v2 );
  4963. renderList.projectVertex( v3 );
  4964. }
  4965. var visible = renderList.checkTriangleVisibility( v1, v2, v3 );
  4966. if ( ( visible === false && side === THREE.FrontSide ) ||
  4967. ( visible === true && side === THREE.BackSide ) ) continue;
  4968. _face = getNextFaceInPool();
  4969. _face.id = object.id;
  4970. _face.v1.copy( v1 );
  4971. _face.v2.copy( v2 );
  4972. _face.v3.copy( v3 );
  4973. _face.normalModel.copy( face.normal );
  4974. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4975. _face.normalModel.negate();
  4976. }
  4977. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4978. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4979. faceVertexNormals = face.vertexNormals;
  4980. for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  4981. var normalModel = _face.vertexNormalsModel[ n ];
  4982. normalModel.copy( faceVertexNormals[ n ] );
  4983. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4984. normalModel.negate();
  4985. }
  4986. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4987. }
  4988. _face.vertexNormalsLength = faceVertexNormals.length;
  4989. for ( var c = 0, cl = Math.min( faceVertexUvs.length, 3 ); c < cl; c ++ ) {
  4990. uvs = faceVertexUvs[ c ][ f ];
  4991. if ( uvs === undefined ) continue;
  4992. for ( var u = 0, ul = uvs.length; u < ul; u ++ ) {
  4993. _face.uvs[ c ][ u ] = uvs[ u ];
  4994. }
  4995. }
  4996. _face.color = face.color;
  4997. _face.material = material;
  4998. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4999. _renderData.elements.push( _face );
  5000. }
  5001. }
  5002. } else if ( object instanceof THREE.Line ) {
  5003. if ( geometry instanceof THREE.BufferGeometry ) {
  5004. var attributes = geometry.attributes;
  5005. if ( attributes.position !== undefined ) {
  5006. var positions = attributes.position.array;
  5007. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  5008. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5009. }
  5010. if ( attributes.index !== undefined ) {
  5011. var indices = attributes.index.array;
  5012. for ( var i = 0, l = indices.length; i < l; i += 2 ) {
  5013. renderList.pushLine( indices[ i ], indices[ i + 1 ] );
  5014. }
  5015. } else {
  5016. for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i ++ ) {
  5017. renderList.pushLine( i, i + 1 );
  5018. }
  5019. }
  5020. }
  5021. } else if ( geometry instanceof THREE.Geometry ) {
  5022. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  5023. vertices = object.geometry.vertices;
  5024. if ( vertices.length === 0 ) continue;
  5025. v1 = getNextVertexInPool();
  5026. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  5027. // Handle LineStrip and LinePieces
  5028. var step = object.type === THREE.LinePieces ? 2 : 1;
  5029. for ( var v = 1, vl = vertices.length; v < vl; v ++ ) {
  5030. v1 = getNextVertexInPool();
  5031. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  5032. if ( ( v + 1 ) % step > 0 ) continue;
  5033. v2 = _vertexPool[ _vertexCount - 2 ];
  5034. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  5035. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  5036. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  5037. // Perform the perspective divide
  5038. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  5039. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  5040. _line = getNextLineInPool();
  5041. _line.id = object.id;
  5042. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  5043. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  5044. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  5045. _line.material = object.material;
  5046. if ( object.material.vertexColors === THREE.VertexColors ) {
  5047. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  5048. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  5049. }
  5050. _renderData.elements.push( _line );
  5051. }
  5052. }
  5053. }
  5054. } else if ( object instanceof THREE.Sprite ) {
  5055. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  5056. _vector4.applyMatrix4( _viewProjectionMatrix );
  5057. var invW = 1 / _vector4.w;
  5058. _vector4.z *= invW;
  5059. if ( _vector4.z >= -1 && _vector4.z <= 1 ) {
  5060. _sprite = getNextSpriteInPool();
  5061. _sprite.id = object.id;
  5062. _sprite.x = _vector4.x * invW;
  5063. _sprite.y = _vector4.y * invW;
  5064. _sprite.z = _vector4.z;
  5065. _sprite.object = object;
  5066. _sprite.rotation = object.rotation;
  5067. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  5068. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  5069. _sprite.material = object.material;
  5070. _renderData.elements.push( _sprite );
  5071. }
  5072. }
  5073. }
  5074. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  5075. return _renderData;
  5076. };
  5077. // Pools
  5078. function getNextObjectInPool() {
  5079. if ( _objectCount === _objectPoolLength ) {
  5080. var object = new THREE.RenderableObject();
  5081. _objectPool.push( object );
  5082. _objectPoolLength ++;
  5083. _objectCount ++;
  5084. return object;
  5085. }
  5086. return _objectPool[ _objectCount ++ ];
  5087. }
  5088. function getNextVertexInPool() {
  5089. if ( _vertexCount === _vertexPoolLength ) {
  5090. var vertex = new THREE.RenderableVertex();
  5091. _vertexPool.push( vertex );
  5092. _vertexPoolLength ++;
  5093. _vertexCount ++;
  5094. return vertex;
  5095. }
  5096. return _vertexPool[ _vertexCount ++ ];
  5097. }
  5098. function getNextFaceInPool() {
  5099. if ( _faceCount === _facePoolLength ) {
  5100. var face = new THREE.RenderableFace();
  5101. _facePool.push( face );
  5102. _facePoolLength ++;
  5103. _faceCount ++;
  5104. return face;
  5105. }
  5106. return _facePool[ _faceCount ++ ];
  5107. }
  5108. function getNextLineInPool() {
  5109. if ( _lineCount === _linePoolLength ) {
  5110. var line = new THREE.RenderableLine();
  5111. _linePool.push( line );
  5112. _linePoolLength ++;
  5113. _lineCount ++
  5114. return line;
  5115. }
  5116. return _linePool[ _lineCount ++ ];
  5117. }
  5118. function getNextSpriteInPool() {
  5119. if ( _spriteCount === _spritePoolLength ) {
  5120. var sprite = new THREE.RenderableSprite();
  5121. _spritePool.push( sprite );
  5122. _spritePoolLength ++;
  5123. _spriteCount ++
  5124. return sprite;
  5125. }
  5126. return _spritePool[ _spriteCount ++ ];
  5127. }
  5128. //
  5129. function painterSort( a, b ) {
  5130. if ( a.z !== b.z ) {
  5131. return b.z - a.z;
  5132. } else if ( a.id !== b.id ) {
  5133. return a.id - b.id;
  5134. } else {
  5135. return 0;
  5136. }
  5137. }
  5138. function clipLine( s1, s2 ) {
  5139. var alpha1 = 0, alpha2 = 1,
  5140. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  5141. // Z = -1 and Z = +1, respectively.
  5142. bc1near = s1.z + s1.w,
  5143. bc2near = s2.z + s2.w,
  5144. bc1far = - s1.z + s1.w,
  5145. bc2far = - s2.z + s2.w;
  5146. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  5147. // Both vertices lie entirely within all clip planes.
  5148. return true;
  5149. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  5150. // Both vertices lie entirely outside one of the clip planes.
  5151. return false;
  5152. } else {
  5153. // The line segment spans at least one clip plane.
  5154. if ( bc1near < 0 ) {
  5155. // v1 lies outside the near plane, v2 inside
  5156. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  5157. } else if ( bc2near < 0 ) {
  5158. // v2 lies outside the near plane, v1 inside
  5159. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  5160. }
  5161. if ( bc1far < 0 ) {
  5162. // v1 lies outside the far plane, v2 inside
  5163. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  5164. } else if ( bc2far < 0 ) {
  5165. // v2 lies outside the far plane, v2 inside
  5166. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  5167. }
  5168. if ( alpha2 < alpha1 ) {
  5169. // The line segment spans two boundaries, but is outside both of them.
  5170. // (This can't happen when we're only clipping against just near/far but good
  5171. // to leave the check here for future usage if other clip planes are added.)
  5172. return false;
  5173. } else {
  5174. // Update the s1 and s2 vertices to match the clipped line segment.
  5175. s1.lerp( s2, alpha1 );
  5176. s2.lerp( s1, 1 - alpha2 );
  5177. return true;
  5178. }
  5179. }
  5180. }
  5181. };
  5182. /**
  5183. * @author mrdoob / http://mrdoob.com/
  5184. * @author alteredq / http://alteredqualia.com/
  5185. */
  5186. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5187. this.a = a;
  5188. this.b = b;
  5189. this.c = c;
  5190. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5191. this.vertexNormals = normal instanceof Array ? normal : [ ];
  5192. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5193. this.vertexColors = color instanceof Array ? color : [];
  5194. this.vertexTangents = [];
  5195. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5196. this.centroid = new THREE.Vector3();
  5197. };
  5198. THREE.Face3.prototype = {
  5199. constructor: THREE.Face3,
  5200. clone: function () {
  5201. var face = new THREE.Face3( this.a, this.b, this.c );
  5202. face.normal.copy( this.normal );
  5203. face.color.copy( this.color );
  5204. face.centroid.copy( this.centroid );
  5205. face.materialIndex = this.materialIndex;
  5206. var i, il;
  5207. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  5208. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  5209. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  5210. return face;
  5211. }
  5212. };
  5213. /**
  5214. * @author mrdoob / http://mrdoob.com/
  5215. */
  5216. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5217. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  5218. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5219. };
  5220. /**
  5221. * @author alteredq / http://alteredqualia.com/
  5222. */
  5223. THREE.BufferGeometry = function () {
  5224. this.id = THREE.GeometryIdCount ++;
  5225. this.uuid = THREE.Math.generateUUID();
  5226. this.name = '';
  5227. // attributes
  5228. this.attributes = {};
  5229. // offsets for chunks when using indexed elements
  5230. this.offsets = [];
  5231. // boundings
  5232. this.boundingBox = null;
  5233. this.boundingSphere = null;
  5234. };
  5235. THREE.BufferGeometry.prototype = {
  5236. constructor: THREE.BufferGeometry,
  5237. addAttribute: function ( name, type, numItems, itemSize ) {
  5238. this.attributes[ name ] = {
  5239. array: new type( numItems * itemSize ),
  5240. itemSize: itemSize
  5241. };
  5242. return this.attributes[ name ];
  5243. },
  5244. applyMatrix: function ( matrix ) {
  5245. var position = this.attributes.position;
  5246. if ( position !== undefined ) {
  5247. matrix.multiplyVector3Array( position.array );
  5248. position.needsUpdate = true;
  5249. }
  5250. var normal = this.attributes.normal;
  5251. if ( normal !== undefined ) {
  5252. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5253. normalMatrix.multiplyVector3Array( normal.array );
  5254. normal.needsUpdate = true;
  5255. }
  5256. },
  5257. computeBoundingBox: function () {
  5258. if ( this.boundingBox === null ) {
  5259. this.boundingBox = new THREE.Box3();
  5260. }
  5261. var positions = this.attributes[ "position" ].array;
  5262. if ( positions ) {
  5263. var bb = this.boundingBox;
  5264. if( positions.length >= 3 ) {
  5265. bb.min.x = bb.max.x = positions[ 0 ];
  5266. bb.min.y = bb.max.y = positions[ 1 ];
  5267. bb.min.z = bb.max.z = positions[ 2 ];
  5268. }
  5269. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5270. var x = positions[ i ];
  5271. var y = positions[ i + 1 ];
  5272. var z = positions[ i + 2 ];
  5273. // bounding box
  5274. if ( x < bb.min.x ) {
  5275. bb.min.x = x;
  5276. } else if ( x > bb.max.x ) {
  5277. bb.max.x = x;
  5278. }
  5279. if ( y < bb.min.y ) {
  5280. bb.min.y = y;
  5281. } else if ( y > bb.max.y ) {
  5282. bb.max.y = y;
  5283. }
  5284. if ( z < bb.min.z ) {
  5285. bb.min.z = z;
  5286. } else if ( z > bb.max.z ) {
  5287. bb.max.z = z;
  5288. }
  5289. }
  5290. }
  5291. if ( positions === undefined || positions.length === 0 ) {
  5292. this.boundingBox.min.set( 0, 0, 0 );
  5293. this.boundingBox.max.set( 0, 0, 0 );
  5294. }
  5295. },
  5296. computeBoundingSphere: function () {
  5297. var box = new THREE.Box3();
  5298. var vector = new THREE.Vector3();
  5299. return function () {
  5300. if ( this.boundingSphere === null ) {
  5301. this.boundingSphere = new THREE.Sphere();
  5302. }
  5303. var positions = this.attributes[ "position" ].array;
  5304. if ( positions ) {
  5305. box.makeEmpty();
  5306. var center = this.boundingSphere.center;
  5307. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5308. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5309. box.addPoint( vector );
  5310. }
  5311. box.center( center );
  5312. var maxRadiusSq = 0;
  5313. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5314. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5315. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5316. }
  5317. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5318. }
  5319. }
  5320. }(),
  5321. computeVertexNormals: function () {
  5322. if ( this.attributes[ "position" ] ) {
  5323. var i, il;
  5324. var j, jl;
  5325. var nVertexElements = this.attributes[ "position" ].array.length;
  5326. if ( this.attributes[ "normal" ] === undefined ) {
  5327. this.attributes[ "normal" ] = {
  5328. itemSize: 3,
  5329. array: new Float32Array( nVertexElements )
  5330. };
  5331. } else {
  5332. // reset existing normals to zero
  5333. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5334. this.attributes[ "normal" ].array[ i ] = 0;
  5335. }
  5336. }
  5337. var positions = this.attributes[ "position" ].array;
  5338. var normals = this.attributes[ "normal" ].array;
  5339. var vA, vB, vC, x, y, z,
  5340. pA = new THREE.Vector3(),
  5341. pB = new THREE.Vector3(),
  5342. pC = new THREE.Vector3(),
  5343. cb = new THREE.Vector3(),
  5344. ab = new THREE.Vector3();
  5345. // indexed elements
  5346. if ( this.attributes[ "index" ] ) {
  5347. var indices = this.attributes[ "index" ].array;
  5348. var offsets = this.offsets;
  5349. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5350. var start = offsets[ j ].start;
  5351. var count = offsets[ j ].count;
  5352. var index = offsets[ j ].index;
  5353. for ( i = start, il = start + count; i < il; i += 3 ) {
  5354. vA = index + indices[ i ];
  5355. vB = index + indices[ i + 1 ];
  5356. vC = index + indices[ i + 2 ];
  5357. x = positions[ vA * 3 ];
  5358. y = positions[ vA * 3 + 1 ];
  5359. z = positions[ vA * 3 + 2 ];
  5360. pA.set( x, y, z );
  5361. x = positions[ vB * 3 ];
  5362. y = positions[ vB * 3 + 1 ];
  5363. z = positions[ vB * 3 + 2 ];
  5364. pB.set( x, y, z );
  5365. x = positions[ vC * 3 ];
  5366. y = positions[ vC * 3 + 1 ];
  5367. z = positions[ vC * 3 + 2 ];
  5368. pC.set( x, y, z );
  5369. cb.subVectors( pC, pB );
  5370. ab.subVectors( pA, pB );
  5371. cb.cross( ab );
  5372. normals[ vA * 3 ] += cb.x;
  5373. normals[ vA * 3 + 1 ] += cb.y;
  5374. normals[ vA * 3 + 2 ] += cb.z;
  5375. normals[ vB * 3 ] += cb.x;
  5376. normals[ vB * 3 + 1 ] += cb.y;
  5377. normals[ vB * 3 + 2 ] += cb.z;
  5378. normals[ vC * 3 ] += cb.x;
  5379. normals[ vC * 3 + 1 ] += cb.y;
  5380. normals[ vC * 3 + 2 ] += cb.z;
  5381. }
  5382. }
  5383. // non-indexed elements (unconnected triangle soup)
  5384. } else {
  5385. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5386. x = positions[ i ];
  5387. y = positions[ i + 1 ];
  5388. z = positions[ i + 2 ];
  5389. pA.set( x, y, z );
  5390. x = positions[ i + 3 ];
  5391. y = positions[ i + 4 ];
  5392. z = positions[ i + 5 ];
  5393. pB.set( x, y, z );
  5394. x = positions[ i + 6 ];
  5395. y = positions[ i + 7 ];
  5396. z = positions[ i + 8 ];
  5397. pC.set( x, y, z );
  5398. cb.subVectors( pC, pB );
  5399. ab.subVectors( pA, pB );
  5400. cb.cross( ab );
  5401. normals[ i ] = cb.x;
  5402. normals[ i + 1 ] = cb.y;
  5403. normals[ i + 2 ] = cb.z;
  5404. normals[ i + 3 ] = cb.x;
  5405. normals[ i + 4 ] = cb.y;
  5406. normals[ i + 5 ] = cb.z;
  5407. normals[ i + 6 ] = cb.x;
  5408. normals[ i + 7 ] = cb.y;
  5409. normals[ i + 8 ] = cb.z;
  5410. }
  5411. }
  5412. this.normalizeNormals();
  5413. this.normalsNeedUpdate = true;
  5414. }
  5415. },
  5416. normalizeNormals: function () {
  5417. var normals = this.attributes[ "normal" ].array;
  5418. var x, y, z, n;
  5419. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5420. x = normals[ i ];
  5421. y = normals[ i + 1 ];
  5422. z = normals[ i + 2 ];
  5423. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5424. normals[ i ] *= n;
  5425. normals[ i + 1 ] *= n;
  5426. normals[ i + 2 ] *= n;
  5427. }
  5428. },
  5429. computeTangents: function () {
  5430. // based on http://www.terathon.com/code/tangent.html
  5431. // (per vertex tangents)
  5432. if ( this.attributes[ "index" ] === undefined ||
  5433. this.attributes[ "position" ] === undefined ||
  5434. this.attributes[ "normal" ] === undefined ||
  5435. this.attributes[ "uv" ] === undefined ) {
  5436. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5437. return;
  5438. }
  5439. var indices = this.attributes[ "index" ].array;
  5440. var positions = this.attributes[ "position" ].array;
  5441. var normals = this.attributes[ "normal" ].array;
  5442. var uvs = this.attributes[ "uv" ].array;
  5443. var nVertices = positions.length / 3;
  5444. if ( this.attributes[ "tangent" ] === undefined ) {
  5445. var nTangentElements = 4 * nVertices;
  5446. this.attributes[ "tangent" ] = {
  5447. itemSize: 4,
  5448. array: new Float32Array( nTangentElements )
  5449. };
  5450. }
  5451. var tangents = this.attributes[ "tangent" ].array;
  5452. var tan1 = [], tan2 = [];
  5453. for ( var k = 0; k < nVertices; k ++ ) {
  5454. tan1[ k ] = new THREE.Vector3();
  5455. tan2[ k ] = new THREE.Vector3();
  5456. }
  5457. var xA, yA, zA,
  5458. xB, yB, zB,
  5459. xC, yC, zC,
  5460. uA, vA,
  5461. uB, vB,
  5462. uC, vC,
  5463. x1, x2, y1, y2, z1, z2,
  5464. s1, s2, t1, t2, r;
  5465. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5466. function handleTriangle( a, b, c ) {
  5467. xA = positions[ a * 3 ];
  5468. yA = positions[ a * 3 + 1 ];
  5469. zA = positions[ a * 3 + 2 ];
  5470. xB = positions[ b * 3 ];
  5471. yB = positions[ b * 3 + 1 ];
  5472. zB = positions[ b * 3 + 2 ];
  5473. xC = positions[ c * 3 ];
  5474. yC = positions[ c * 3 + 1 ];
  5475. zC = positions[ c * 3 + 2 ];
  5476. uA = uvs[ a * 2 ];
  5477. vA = uvs[ a * 2 + 1 ];
  5478. uB = uvs[ b * 2 ];
  5479. vB = uvs[ b * 2 + 1 ];
  5480. uC = uvs[ c * 2 ];
  5481. vC = uvs[ c * 2 + 1 ];
  5482. x1 = xB - xA;
  5483. x2 = xC - xA;
  5484. y1 = yB - yA;
  5485. y2 = yC - yA;
  5486. z1 = zB - zA;
  5487. z2 = zC - zA;
  5488. s1 = uB - uA;
  5489. s2 = uC - uA;
  5490. t1 = vB - vA;
  5491. t2 = vC - vA;
  5492. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5493. sdir.set(
  5494. ( t2 * x1 - t1 * x2 ) * r,
  5495. ( t2 * y1 - t1 * y2 ) * r,
  5496. ( t2 * z1 - t1 * z2 ) * r
  5497. );
  5498. tdir.set(
  5499. ( s1 * x2 - s2 * x1 ) * r,
  5500. ( s1 * y2 - s2 * y1 ) * r,
  5501. ( s1 * z2 - s2 * z1 ) * r
  5502. );
  5503. tan1[ a ].add( sdir );
  5504. tan1[ b ].add( sdir );
  5505. tan1[ c ].add( sdir );
  5506. tan2[ a ].add( tdir );
  5507. tan2[ b ].add( tdir );
  5508. tan2[ c ].add( tdir );
  5509. }
  5510. var i, il;
  5511. var j, jl;
  5512. var iA, iB, iC;
  5513. var offsets = this.offsets;
  5514. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5515. var start = offsets[ j ].start;
  5516. var count = offsets[ j ].count;
  5517. var index = offsets[ j ].index;
  5518. for ( i = start, il = start + count; i < il; i += 3 ) {
  5519. iA = index + indices[ i ];
  5520. iB = index + indices[ i + 1 ];
  5521. iC = index + indices[ i + 2 ];
  5522. handleTriangle( iA, iB, iC );
  5523. }
  5524. }
  5525. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5526. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5527. var w, t, test;
  5528. function handleVertex( v ) {
  5529. n.x = normals[ v * 3 ];
  5530. n.y = normals[ v * 3 + 1 ];
  5531. n.z = normals[ v * 3 + 2 ];
  5532. n2.copy( n );
  5533. t = tan1[ v ];
  5534. // Gram-Schmidt orthogonalize
  5535. tmp.copy( t );
  5536. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5537. // Calculate handedness
  5538. tmp2.crossVectors( n2, t );
  5539. test = tmp2.dot( tan2[ v ] );
  5540. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5541. tangents[ v * 4 ] = tmp.x;
  5542. tangents[ v * 4 + 1 ] = tmp.y;
  5543. tangents[ v * 4 + 2 ] = tmp.z;
  5544. tangents[ v * 4 + 3 ] = w;
  5545. }
  5546. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5547. var start = offsets[ j ].start;
  5548. var count = offsets[ j ].count;
  5549. var index = offsets[ j ].index;
  5550. for ( i = start, il = start + count; i < il; i += 3 ) {
  5551. iA = index + indices[ i ];
  5552. iB = index + indices[ i + 1 ];
  5553. iC = index + indices[ i + 2 ];
  5554. handleVertex( iA );
  5555. handleVertex( iB );
  5556. handleVertex( iC );
  5557. }
  5558. }
  5559. },
  5560. /*
  5561. computeOffsets
  5562. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  5563. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  5564. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  5565. indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks.
  5566. */
  5567. computeOffsets: function(indexBufferSize) {
  5568. var size = indexBufferSize;
  5569. if(indexBufferSize === undefined)
  5570. size = 65535; //WebGL limits type of index buffer values to 16-bit.
  5571. var s = Date.now();
  5572. var indices = this.attributes['index'].array;
  5573. var vertices = this.attributes['position'].array;
  5574. var verticesCount = (vertices.length/3);
  5575. var facesCount = (indices.length/3);
  5576. /*
  5577. console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  5578. console.log("Faces to process: "+(indices.length/3));
  5579. console.log("Reordering "+verticesCount+" vertices.");
  5580. */
  5581. var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers
  5582. var indexPtr = 0;
  5583. var vertexPtr = 0;
  5584. var offsets = [ { start:0, count:0, index:0 } ];
  5585. var offset = offsets[0];
  5586. var duplicatedVertices = 0;
  5587. var newVerticeMaps = 0;
  5588. var faceVertices = new Int32Array(6);
  5589. var vertexMap = new Int32Array( vertices.length );
  5590. var revVertexMap = new Int32Array( vertices.length );
  5591. for(var j = 0; j < vertices.length; j++) { vertexMap[j] = -1; revVertexMap[j] = -1; }
  5592. /*
  5593. Traverse every face and reorder vertices in the proper offsets of 65k.
  5594. We can have more than 65k entries in the index buffer per offset, but only reference 65k values.
  5595. */
  5596. for(var findex = 0; findex < facesCount; findex++) {
  5597. newVerticeMaps = 0;
  5598. for(var vo = 0; vo < 3; vo++) {
  5599. var vid = indices[ findex*3 + vo ];
  5600. if(vertexMap[vid] == -1) {
  5601. //Unmapped vertice
  5602. faceVertices[vo*2] = vid;
  5603. faceVertices[vo*2+1] = -1;
  5604. newVerticeMaps++;
  5605. } else if(vertexMap[vid] < offset.index) {
  5606. //Reused vertices from previous block (duplicate)
  5607. faceVertices[vo*2] = vid;
  5608. faceVertices[vo*2+1] = -1;
  5609. duplicatedVertices++;
  5610. } else {
  5611. //Reused vertice in the current block
  5612. faceVertices[vo*2] = vid;
  5613. faceVertices[vo*2+1] = vertexMap[vid];
  5614. }
  5615. }
  5616. var faceMax = vertexPtr + newVerticeMaps;
  5617. if(faceMax > (offset.index + size)) {
  5618. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  5619. offsets.push(new_offset);
  5620. offset = new_offset;
  5621. //Re-evaluate reused vertices in light of new offset.
  5622. for(var v = 0; v < 6; v+=2) {
  5623. var new_vid = faceVertices[v+1];
  5624. if(new_vid > -1 && new_vid < offset.index)
  5625. faceVertices[v+1] = -1;
  5626. }
  5627. }
  5628. //Reindex the face.
  5629. for(var v = 0; v < 6; v+=2) {
  5630. var vid = faceVertices[v];
  5631. var new_vid = faceVertices[v+1];
  5632. if(new_vid === -1)
  5633. new_vid = vertexPtr++;
  5634. vertexMap[vid] = new_vid;
  5635. revVertexMap[new_vid] = vid;
  5636. sortedIndices[indexPtr++] = new_vid - offset.index; //XXX overflows at 16bit
  5637. offset.count++;
  5638. }
  5639. }
  5640. /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */
  5641. this.reorderBuffers(sortedIndices, revVertexMap, vertexPtr);
  5642. this.offsets = offsets;
  5643. /*
  5644. var orderTime = Date.now();
  5645. console.log("Reorder time: "+(orderTime-s)+"ms");
  5646. console.log("Duplicated "+duplicatedVertices+" vertices.");
  5647. console.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  5648. console.log("Draw offsets: "+offsets.length);
  5649. */
  5650. return offsets;
  5651. },
  5652. /*
  5653. reoderBuffers:
  5654. Reorder attributes based on a new indexBuffer and indexMap.
  5655. indexBuffer - Uint16Array of the new ordered indices.
  5656. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  5657. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack).
  5658. */
  5659. reorderBuffers: function(indexBuffer, indexMap, vertexCount) {
  5660. /* Create a copy of all attributes for reordering. */
  5661. var sortedAttributes = {};
  5662. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5663. for( var attr in this.attributes ) {
  5664. if(attr == 'index')
  5665. continue;
  5666. var sourceArray = this.attributes[attr].array;
  5667. for ( var i = 0, il = types.length; i < il; i++ ) {
  5668. var type = types[i];
  5669. if (sourceArray instanceof type) {
  5670. sortedAttributes[attr] = new type( this.attributes[attr].itemSize * vertexCount );
  5671. break;
  5672. }
  5673. }
  5674. }
  5675. /* Move attribute positions based on the new index map */
  5676. for(var new_vid = 0; new_vid < vertexCount; new_vid++) {
  5677. var vid = indexMap[new_vid];
  5678. for ( var attr in this.attributes ) {
  5679. if(attr == 'index')
  5680. continue;
  5681. var attrArray = this.attributes[attr].array;
  5682. var attrSize = this.attributes[attr].itemSize;
  5683. var sortedAttr = sortedAttributes[attr];
  5684. for(var k = 0; k < attrSize; k++)
  5685. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  5686. }
  5687. }
  5688. /* Carry the new sorted buffers locally */
  5689. this.attributes['index'].array = indexBuffer;
  5690. for ( var attr in this.attributes ) {
  5691. if(attr == 'index')
  5692. continue;
  5693. this.attributes[attr].array = sortedAttributes[attr];
  5694. this.attributes[attr].numItems = this.attributes[attr].itemSize * vertexCount;
  5695. }
  5696. },
  5697. clone: function () {
  5698. var geometry = new THREE.BufferGeometry();
  5699. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5700. for ( var attr in this.attributes ) {
  5701. var sourceAttr = this.attributes[ attr ];
  5702. var sourceArray = sourceAttr.array;
  5703. var attribute = {
  5704. itemSize: sourceAttr.itemSize,
  5705. array: null
  5706. };
  5707. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5708. var type = types[ i ];
  5709. if ( sourceArray instanceof type ) {
  5710. attribute.array = new type( sourceArray );
  5711. break;
  5712. }
  5713. }
  5714. geometry.attributes[ attr ] = attribute;
  5715. }
  5716. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5717. var offset = this.offsets[ i ];
  5718. geometry.offsets.push( {
  5719. start: offset.start,
  5720. index: offset.index,
  5721. count: offset.count
  5722. } );
  5723. }
  5724. return geometry;
  5725. },
  5726. dispose: function () {
  5727. this.dispatchEvent( { type: 'dispose' } );
  5728. }
  5729. };
  5730. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5731. /**
  5732. * @author mrdoob / http://mrdoob.com/
  5733. * @author kile / http://kile.stravaganza.org/
  5734. * @author alteredq / http://alteredqualia.com/
  5735. * @author mikael emtinger / http://gomo.se/
  5736. * @author zz85 / http://www.lab4games.net/zz85/blog
  5737. * @author bhouston / http://exocortex.com
  5738. */
  5739. THREE.Geometry = function () {
  5740. this.id = THREE.GeometryIdCount ++;
  5741. this.uuid = THREE.Math.generateUUID();
  5742. this.name = '';
  5743. this.vertices = [];
  5744. this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line
  5745. this.faces = [];
  5746. this.faceVertexUvs = [[]];
  5747. this.morphTargets = [];
  5748. this.morphColors = [];
  5749. this.morphNormals = [];
  5750. this.skinWeights = [];
  5751. this.skinIndices = [];
  5752. this.lineDistances = [];
  5753. this.boundingBox = null;
  5754. this.boundingSphere = null;
  5755. this.hasTangents = false;
  5756. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5757. // update flags
  5758. this.verticesNeedUpdate = false;
  5759. this.elementsNeedUpdate = false;
  5760. this.uvsNeedUpdate = false;
  5761. this.normalsNeedUpdate = false;
  5762. this.tangentsNeedUpdate = false;
  5763. this.colorsNeedUpdate = false;
  5764. this.lineDistancesNeedUpdate = false;
  5765. this.buffersNeedUpdate = false;
  5766. };
  5767. THREE.Geometry.prototype = {
  5768. constructor: THREE.Geometry,
  5769. applyMatrix: function ( matrix ) {
  5770. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5771. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5772. var vertex = this.vertices[ i ];
  5773. vertex.applyMatrix4( matrix );
  5774. }
  5775. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5776. var face = this.faces[ i ];
  5777. face.normal.applyMatrix3( normalMatrix ).normalize();
  5778. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5779. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5780. }
  5781. face.centroid.applyMatrix4( matrix );
  5782. }
  5783. if ( this.boundingBox instanceof THREE.Box3 ) {
  5784. this.computeBoundingBox();
  5785. }
  5786. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5787. this.computeBoundingSphere();
  5788. }
  5789. },
  5790. computeCentroids: function () {
  5791. var f, fl, face;
  5792. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5793. face = this.faces[ f ];
  5794. face.centroid.set( 0, 0, 0 );
  5795. face.centroid.add( this.vertices[ face.a ] );
  5796. face.centroid.add( this.vertices[ face.b ] );
  5797. face.centroid.add( this.vertices[ face.c ] );
  5798. face.centroid.divideScalar( 3 );
  5799. }
  5800. },
  5801. computeFaceNormals: function () {
  5802. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5803. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5804. var face = this.faces[ f ];
  5805. var vA = this.vertices[ face.a ];
  5806. var vB = this.vertices[ face.b ];
  5807. var vC = this.vertices[ face.c ];
  5808. cb.subVectors( vC, vB );
  5809. ab.subVectors( vA, vB );
  5810. cb.cross( ab );
  5811. cb.normalize();
  5812. face.normal.copy( cb );
  5813. }
  5814. },
  5815. computeVertexNormals: function ( areaWeighted ) {
  5816. var v, vl, f, fl, face, vertices;
  5817. vertices = new Array( this.vertices.length );
  5818. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5819. vertices[ v ] = new THREE.Vector3();
  5820. }
  5821. if ( areaWeighted ) {
  5822. // vertex normals weighted by triangle areas
  5823. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5824. var vA, vB, vC, vD;
  5825. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5826. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5827. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5828. face = this.faces[ f ];
  5829. vA = this.vertices[ face.a ];
  5830. vB = this.vertices[ face.b ];
  5831. vC = this.vertices[ face.c ];
  5832. cb.subVectors( vC, vB );
  5833. ab.subVectors( vA, vB );
  5834. cb.cross( ab );
  5835. vertices[ face.a ].add( cb );
  5836. vertices[ face.b ].add( cb );
  5837. vertices[ face.c ].add( cb );
  5838. }
  5839. } else {
  5840. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5841. face = this.faces[ f ];
  5842. vertices[ face.a ].add( face.normal );
  5843. vertices[ face.b ].add( face.normal );
  5844. vertices[ face.c ].add( face.normal );
  5845. }
  5846. }
  5847. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5848. vertices[ v ].normalize();
  5849. }
  5850. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5851. face = this.faces[ f ];
  5852. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5853. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5854. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5855. }
  5856. },
  5857. computeMorphNormals: function () {
  5858. var i, il, f, fl, face;
  5859. // save original normals
  5860. // - create temp variables on first access
  5861. // otherwise just copy (for faster repeated calls)
  5862. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5863. face = this.faces[ f ];
  5864. if ( ! face.__originalFaceNormal ) {
  5865. face.__originalFaceNormal = face.normal.clone();
  5866. } else {
  5867. face.__originalFaceNormal.copy( face.normal );
  5868. }
  5869. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5870. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5871. if ( ! face.__originalVertexNormals[ i ] ) {
  5872. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5873. } else {
  5874. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5875. }
  5876. }
  5877. }
  5878. // use temp geometry to compute face and vertex normals for each morph
  5879. var tmpGeo = new THREE.Geometry();
  5880. tmpGeo.faces = this.faces;
  5881. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5882. // create on first access
  5883. if ( ! this.morphNormals[ i ] ) {
  5884. this.morphNormals[ i ] = {};
  5885. this.morphNormals[ i ].faceNormals = [];
  5886. this.morphNormals[ i ].vertexNormals = [];
  5887. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5888. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5889. var faceNormal, vertexNormals;
  5890. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5891. face = this.faces[ f ];
  5892. faceNormal = new THREE.Vector3();
  5893. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5894. dstNormalsFace.push( faceNormal );
  5895. dstNormalsVertex.push( vertexNormals );
  5896. }
  5897. }
  5898. var morphNormals = this.morphNormals[ i ];
  5899. // set vertices to morph target
  5900. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5901. // compute morph normals
  5902. tmpGeo.computeFaceNormals();
  5903. tmpGeo.computeVertexNormals();
  5904. // store morph normals
  5905. var faceNormal, vertexNormals;
  5906. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5907. face = this.faces[ f ];
  5908. faceNormal = morphNormals.faceNormals[ f ];
  5909. vertexNormals = morphNormals.vertexNormals[ f ];
  5910. faceNormal.copy( face.normal );
  5911. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5912. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5913. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5914. }
  5915. }
  5916. // restore original normals
  5917. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5918. face = this.faces[ f ];
  5919. face.normal = face.__originalFaceNormal;
  5920. face.vertexNormals = face.__originalVertexNormals;
  5921. }
  5922. },
  5923. computeTangents: function () {
  5924. // based on http://www.terathon.com/code/tangent.html
  5925. // tangents go to vertices
  5926. var f, fl, v, vl, i, il, vertexIndex,
  5927. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5928. x1, x2, y1, y2, z1, z2,
  5929. s1, s2, t1, t2, r, t, test,
  5930. tan1 = [], tan2 = [],
  5931. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5932. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5933. n = new THREE.Vector3(), w;
  5934. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5935. tan1[ v ] = new THREE.Vector3();
  5936. tan2[ v ] = new THREE.Vector3();
  5937. }
  5938. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5939. vA = context.vertices[ a ];
  5940. vB = context.vertices[ b ];
  5941. vC = context.vertices[ c ];
  5942. uvA = uv[ ua ];
  5943. uvB = uv[ ub ];
  5944. uvC = uv[ uc ];
  5945. x1 = vB.x - vA.x;
  5946. x2 = vC.x - vA.x;
  5947. y1 = vB.y - vA.y;
  5948. y2 = vC.y - vA.y;
  5949. z1 = vB.z - vA.z;
  5950. z2 = vC.z - vA.z;
  5951. s1 = uvB.x - uvA.x;
  5952. s2 = uvC.x - uvA.x;
  5953. t1 = uvB.y - uvA.y;
  5954. t2 = uvC.y - uvA.y;
  5955. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5956. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5957. ( t2 * y1 - t1 * y2 ) * r,
  5958. ( t2 * z1 - t1 * z2 ) * r );
  5959. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5960. ( s1 * y2 - s2 * y1 ) * r,
  5961. ( s1 * z2 - s2 * z1 ) * r );
  5962. tan1[ a ].add( sdir );
  5963. tan1[ b ].add( sdir );
  5964. tan1[ c ].add( sdir );
  5965. tan2[ a ].add( tdir );
  5966. tan2[ b ].add( tdir );
  5967. tan2[ c ].add( tdir );
  5968. }
  5969. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5970. face = this.faces[ f ];
  5971. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5972. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5973. }
  5974. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5975. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5976. face = this.faces[ f ];
  5977. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  5978. n.copy( face.vertexNormals[ i ] );
  5979. vertexIndex = face[ faceIndex[ i ] ];
  5980. t = tan1[ vertexIndex ];
  5981. // Gram-Schmidt orthogonalize
  5982. tmp.copy( t );
  5983. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5984. // Calculate handedness
  5985. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5986. test = tmp2.dot( tan2[ vertexIndex ] );
  5987. w = (test < 0.0) ? -1.0 : 1.0;
  5988. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5989. }
  5990. }
  5991. this.hasTangents = true;
  5992. },
  5993. computeLineDistances: function ( ) {
  5994. var d = 0;
  5995. var vertices = this.vertices;
  5996. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5997. if ( i > 0 ) {
  5998. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5999. }
  6000. this.lineDistances[ i ] = d;
  6001. }
  6002. },
  6003. computeBoundingBox: function () {
  6004. if ( this.boundingBox === null ) {
  6005. this.boundingBox = new THREE.Box3();
  6006. }
  6007. this.boundingBox.setFromPoints( this.vertices );
  6008. },
  6009. computeBoundingSphere: function () {
  6010. if ( this.boundingSphere === null ) {
  6011. this.boundingSphere = new THREE.Sphere();
  6012. }
  6013. this.boundingSphere.setFromPoints( this.vertices );
  6014. },
  6015. /*
  6016. * Checks for duplicate vertices with hashmap.
  6017. * Duplicated vertices are removed
  6018. * and faces' vertices are updated.
  6019. */
  6020. mergeVertices: function () {
  6021. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  6022. var unique = [], changes = [];
  6023. var v, key;
  6024. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  6025. var precision = Math.pow( 10, precisionPoints );
  6026. var i,il, face;
  6027. var indices, k, j, jl, u;
  6028. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6029. v = this.vertices[ i ];
  6030. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6031. if ( verticesMap[ key ] === undefined ) {
  6032. verticesMap[ key ] = i;
  6033. unique.push( this.vertices[ i ] );
  6034. changes[ i ] = unique.length - 1;
  6035. } else {
  6036. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6037. changes[ i ] = changes[ verticesMap[ key ] ];
  6038. }
  6039. };
  6040. // if faces are completely degenerate after merging vertices, we
  6041. // have to remove them from the geometry.
  6042. var faceIndicesToRemove = [];
  6043. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  6044. face = this.faces[ i ];
  6045. face.a = changes[ face.a ];
  6046. face.b = changes[ face.b ];
  6047. face.c = changes[ face.c ];
  6048. indices = [ face.a, face.b, face.c ];
  6049. var dupIndex = -1;
  6050. // if any duplicate vertices are found in a Face3
  6051. // we have to remove the face as nothing can be saved
  6052. for ( var n = 0; n < 3; n ++ ) {
  6053. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  6054. dupIndex = n;
  6055. faceIndicesToRemove.push( i );
  6056. break;
  6057. }
  6058. }
  6059. }
  6060. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6061. var idx = faceIndicesToRemove[ i ];
  6062. this.faces.splice( idx, 1 );
  6063. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6064. this.faceVertexUvs[ j ].splice( idx, 1 );
  6065. }
  6066. }
  6067. // Use unique set of vertices
  6068. var diff = this.vertices.length - unique.length;
  6069. this.vertices = unique;
  6070. return diff;
  6071. },
  6072. // Geometry splitting
  6073. makeGroups: ( function () {
  6074. var geometryGroupCounter = 0;
  6075. return function ( usesFaceMaterial ) {
  6076. var f, fl, face, materialIndex,
  6077. groupHash, hash_map = {};
  6078. var numMorphTargets = this.morphTargets.length;
  6079. var numMorphNormals = this.morphNormals.length;
  6080. this.geometryGroups = {};
  6081. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6082. face = this.faces[ f ];
  6083. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  6084. if ( ! ( materialIndex in hash_map ) ) {
  6085. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  6086. }
  6087. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6088. if ( ! ( groupHash in this.geometryGroups ) ) {
  6089. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6090. }
  6091. if ( this.geometryGroups[ groupHash ].vertices + 3 > 65535 ) {
  6092. hash_map[ materialIndex ].counter += 1;
  6093. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6094. if ( ! ( groupHash in this.geometryGroups ) ) {
  6095. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6096. }
  6097. }
  6098. this.geometryGroups[ groupHash ].faces3.push( f );
  6099. this.geometryGroups[ groupHash ].vertices += 3;
  6100. }
  6101. this.geometryGroupsList = [];
  6102. for ( var g in this.geometryGroups ) {
  6103. this.geometryGroups[ g ].id = geometryGroupCounter ++;
  6104. this.geometryGroupsList.push( this.geometryGroups[ g ] );
  6105. }
  6106. };
  6107. } )(),
  6108. clone: function () {
  6109. var geometry = new THREE.Geometry();
  6110. var vertices = this.vertices;
  6111. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6112. geometry.vertices.push( vertices[ i ].clone() );
  6113. }
  6114. var faces = this.faces;
  6115. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6116. geometry.faces.push( faces[ i ].clone() );
  6117. }
  6118. var uvs = this.faceVertexUvs[ 0 ];
  6119. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  6120. var uv = uvs[ i ], uvCopy = [];
  6121. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6122. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  6123. }
  6124. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  6125. }
  6126. return geometry;
  6127. },
  6128. dispose: function () {
  6129. this.dispatchEvent( { type: 'dispose' } );
  6130. }
  6131. };
  6132. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6133. THREE.GeometryIdCount = 0;
  6134. /**
  6135. * @author mrdoob / http://mrdoob.com/
  6136. */
  6137. THREE.Geometry2 = function ( size ) {
  6138. THREE.BufferGeometry.call( this );
  6139. this.vertices = this.addAttribute( 'position', Float32Array, size, 3 ).array;
  6140. this.normals = this.addAttribute( 'normal', Float32Array, size, 3 ).array;
  6141. this.uvs = this.addAttribute( 'uv', Float32Array, size, 2 ).array;
  6142. this.boundingBox = null;
  6143. this.boundingSphere = null;
  6144. };
  6145. THREE.Geometry2.prototype = Object.create( THREE.BufferGeometry.prototype );
  6146. /**
  6147. * @author mrdoob / http://mrdoob.com/
  6148. * @author mikael emtinger / http://gomo.se/
  6149. * @author WestLangley / http://github.com/WestLangley
  6150. */
  6151. THREE.Camera = function () {
  6152. THREE.Object3D.call( this );
  6153. this.matrixWorldInverse = new THREE.Matrix4();
  6154. this.projectionMatrix = new THREE.Matrix4();
  6155. };
  6156. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  6157. THREE.Camera.prototype.lookAt = function () {
  6158. // This routine does not support cameras with rotated and/or translated parent(s)
  6159. var m1 = new THREE.Matrix4();
  6160. return function ( vector ) {
  6161. m1.lookAt( this.position, vector, this.up );
  6162. this.quaternion.setFromRotationMatrix( m1 );
  6163. };
  6164. }();
  6165. THREE.Camera.prototype.clone = function (camera) {
  6166. if ( camera === undefined ) camera = new THREE.Camera();
  6167. THREE.Object3D.prototype.clone.call( this, camera );
  6168. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  6169. camera.projectionMatrix.copy( this.projectionMatrix );
  6170. return camera;
  6171. };
  6172. /**
  6173. * @author alteredq / http://alteredqualia.com/
  6174. */
  6175. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6176. THREE.Camera.call( this );
  6177. this.left = left;
  6178. this.right = right;
  6179. this.top = top;
  6180. this.bottom = bottom;
  6181. this.near = ( near !== undefined ) ? near : 0.1;
  6182. this.far = ( far !== undefined ) ? far : 2000;
  6183. this.updateProjectionMatrix();
  6184. };
  6185. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6186. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6187. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  6188. };
  6189. THREE.OrthographicCamera.prototype.clone = function () {
  6190. var camera = new THREE.OrthographicCamera();
  6191. THREE.Camera.prototype.clone.call( this, camera );
  6192. camera.left = this.left;
  6193. camera.right = this.right;
  6194. camera.top = this.top;
  6195. camera.bottom = this.bottom;
  6196. camera.near = this.near;
  6197. camera.far = this.far;
  6198. return camera;
  6199. };
  6200. /**
  6201. * @author mrdoob / http://mrdoob.com/
  6202. * @author greggman / http://games.greggman.com/
  6203. * @author zz85 / http://www.lab4games.net/zz85/blog
  6204. */
  6205. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6206. THREE.Camera.call( this );
  6207. this.fov = fov !== undefined ? fov : 50;
  6208. this.aspect = aspect !== undefined ? aspect : 1;
  6209. this.near = near !== undefined ? near : 0.1;
  6210. this.far = far !== undefined ? far : 2000;
  6211. this.updateProjectionMatrix();
  6212. };
  6213. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6214. /**
  6215. * Uses Focal Length (in mm) to estimate and set FOV
  6216. * 35mm (fullframe) camera is used if frame size is not specified;
  6217. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6218. */
  6219. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6220. if ( frameHeight === undefined ) frameHeight = 24;
  6221. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6222. this.updateProjectionMatrix();
  6223. }
  6224. /**
  6225. * Sets an offset in a larger frustum. This is useful for multi-window or
  6226. * multi-monitor/multi-machine setups.
  6227. *
  6228. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6229. * the monitors are in grid like this
  6230. *
  6231. * +---+---+---+
  6232. * | A | B | C |
  6233. * +---+---+---+
  6234. * | D | E | F |
  6235. * +---+---+---+
  6236. *
  6237. * then for each monitor you would call it like this
  6238. *
  6239. * var w = 1920;
  6240. * var h = 1080;
  6241. * var fullWidth = w * 3;
  6242. * var fullHeight = h * 2;
  6243. *
  6244. * --A--
  6245. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6246. * --B--
  6247. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6248. * --C--
  6249. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6250. * --D--
  6251. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6252. * --E--
  6253. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6254. * --F--
  6255. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6256. *
  6257. * Note there is no reason monitors have to be the same size or in a grid.
  6258. */
  6259. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6260. this.fullWidth = fullWidth;
  6261. this.fullHeight = fullHeight;
  6262. this.x = x;
  6263. this.y = y;
  6264. this.width = width;
  6265. this.height = height;
  6266. this.updateProjectionMatrix();
  6267. };
  6268. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6269. if ( this.fullWidth ) {
  6270. var aspect = this.fullWidth / this.fullHeight;
  6271. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  6272. var bottom = -top;
  6273. var left = aspect * bottom;
  6274. var right = aspect * top;
  6275. var width = Math.abs( right - left );
  6276. var height = Math.abs( top - bottom );
  6277. this.projectionMatrix.makeFrustum(
  6278. left + this.x * width / this.fullWidth,
  6279. left + ( this.x + this.width ) * width / this.fullWidth,
  6280. top - ( this.y + this.height ) * height / this.fullHeight,
  6281. top - this.y * height / this.fullHeight,
  6282. this.near,
  6283. this.far
  6284. );
  6285. } else {
  6286. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  6287. }
  6288. };
  6289. THREE.PerspectiveCamera.prototype.clone = function () {
  6290. var camera = new THREE.PerspectiveCamera();
  6291. THREE.Camera.prototype.clone.call( this, camera );
  6292. camera.fov = this.fov;
  6293. camera.aspect = this.aspect;
  6294. camera.near = this.near;
  6295. camera.far = this.far;
  6296. return camera;
  6297. };
  6298. /**
  6299. * @author mrdoob / http://mrdoob.com/
  6300. * @author alteredq / http://alteredqualia.com/
  6301. */
  6302. THREE.Light = function ( color ) {
  6303. THREE.Object3D.call( this );
  6304. this.color = new THREE.Color( color );
  6305. };
  6306. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6307. THREE.Light.prototype.clone = function ( light ) {
  6308. if ( light === undefined ) light = new THREE.Light();
  6309. THREE.Object3D.prototype.clone.call( this, light );
  6310. light.color.copy( this.color );
  6311. return light;
  6312. };
  6313. /**
  6314. * @author mrdoob / http://mrdoob.com/
  6315. */
  6316. THREE.AmbientLight = function ( color ) {
  6317. THREE.Light.call( this, color );
  6318. };
  6319. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6320. THREE.AmbientLight.prototype.clone = function () {
  6321. var light = new THREE.AmbientLight();
  6322. THREE.Light.prototype.clone.call( this, light );
  6323. return light;
  6324. };
  6325. /**
  6326. * @author MPanknin / http://www.redplant.de/
  6327. * @author alteredq / http://alteredqualia.com/
  6328. */
  6329. THREE.AreaLight = function ( color, intensity ) {
  6330. THREE.Light.call( this, color );
  6331. this.normal = new THREE.Vector3( 0, -1, 0 );
  6332. this.right = new THREE.Vector3( 1, 0, 0 );
  6333. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6334. this.width = 1.0;
  6335. this.height = 1.0;
  6336. this.constantAttenuation = 1.5;
  6337. this.linearAttenuation = 0.5;
  6338. this.quadraticAttenuation = 0.1;
  6339. };
  6340. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6341. /**
  6342. * @author mrdoob / http://mrdoob.com/
  6343. * @author alteredq / http://alteredqualia.com/
  6344. */
  6345. THREE.DirectionalLight = function ( color, intensity ) {
  6346. THREE.Light.call( this, color );
  6347. this.position.set( 0, 1, 0 );
  6348. this.target = new THREE.Object3D();
  6349. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6350. this.castShadow = false;
  6351. this.onlyShadow = false;
  6352. //
  6353. this.shadowCameraNear = 50;
  6354. this.shadowCameraFar = 5000;
  6355. this.shadowCameraLeft = -500;
  6356. this.shadowCameraRight = 500;
  6357. this.shadowCameraTop = 500;
  6358. this.shadowCameraBottom = -500;
  6359. this.shadowCameraVisible = false;
  6360. this.shadowBias = 0;
  6361. this.shadowDarkness = 0.5;
  6362. this.shadowMapWidth = 512;
  6363. this.shadowMapHeight = 512;
  6364. //
  6365. this.shadowCascade = false;
  6366. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  6367. this.shadowCascadeCount = 2;
  6368. this.shadowCascadeBias = [ 0, 0, 0 ];
  6369. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6370. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6371. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  6372. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6373. this.shadowCascadeArray = [];
  6374. //
  6375. this.shadowMap = null;
  6376. this.shadowMapSize = null;
  6377. this.shadowCamera = null;
  6378. this.shadowMatrix = null;
  6379. };
  6380. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6381. THREE.DirectionalLight.prototype.clone = function () {
  6382. var light = new THREE.DirectionalLight();
  6383. THREE.Light.prototype.clone.call( this, light );
  6384. light.target = this.target.clone();
  6385. light.intensity = this.intensity;
  6386. light.castShadow = this.castShadow;
  6387. light.onlyShadow = this.onlyShadow;
  6388. return light;
  6389. };
  6390. /**
  6391. * @author alteredq / http://alteredqualia.com/
  6392. */
  6393. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6394. THREE.Light.call( this, skyColor );
  6395. this.position.set( 0, 100, 0 );
  6396. this.groundColor = new THREE.Color( groundColor );
  6397. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6398. };
  6399. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6400. THREE.HemisphereLight.prototype.clone = function () {
  6401. var light = new THREE.HemisphereLight();
  6402. THREE.Light.prototype.clone.call( this, light );
  6403. light.groundColor.copy( this.groundColor );
  6404. light.intensity = this.intensity;
  6405. return light;
  6406. };
  6407. /**
  6408. * @author mrdoob / http://mrdoob.com/
  6409. */
  6410. THREE.PointLight = function ( color, intensity, distance ) {
  6411. THREE.Light.call( this, color );
  6412. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6413. this.distance = ( distance !== undefined ) ? distance : 0;
  6414. };
  6415. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6416. THREE.PointLight.prototype.clone = function () {
  6417. var light = new THREE.PointLight();
  6418. THREE.Light.prototype.clone.call( this, light );
  6419. light.intensity = this.intensity;
  6420. light.distance = this.distance;
  6421. return light;
  6422. };
  6423. /**
  6424. * @author alteredq / http://alteredqualia.com/
  6425. */
  6426. THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) {
  6427. THREE.Light.call( this, color );
  6428. this.position.set( 0, 1, 0 );
  6429. this.target = new THREE.Object3D();
  6430. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6431. this.distance = ( distance !== undefined ) ? distance : 0;
  6432. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6433. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6434. this.castShadow = false;
  6435. this.onlyShadow = false;
  6436. //
  6437. this.shadowCameraNear = 50;
  6438. this.shadowCameraFar = 5000;
  6439. this.shadowCameraFov = 50;
  6440. this.shadowCameraVisible = false;
  6441. this.shadowBias = 0;
  6442. this.shadowDarkness = 0.5;
  6443. this.shadowMapWidth = 512;
  6444. this.shadowMapHeight = 512;
  6445. //
  6446. this.shadowMap = null;
  6447. this.shadowMapSize = null;
  6448. this.shadowCamera = null;
  6449. this.shadowMatrix = null;
  6450. };
  6451. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6452. THREE.SpotLight.prototype.clone = function () {
  6453. var light = new THREE.SpotLight();
  6454. THREE.Light.prototype.clone.call( this, light );
  6455. light.target = this.target.clone();
  6456. light.intensity = this.intensity;
  6457. light.distance = this.distance;
  6458. light.angle = this.angle;
  6459. light.exponent = this.exponent;
  6460. light.castShadow = this.castShadow;
  6461. light.onlyShadow = this.onlyShadow;
  6462. return light;
  6463. };
  6464. /**
  6465. * @author alteredq / http://alteredqualia.com/
  6466. */
  6467. THREE.Loader = function ( showStatus ) {
  6468. this.showStatus = showStatus;
  6469. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6470. this.onLoadStart = function () {};
  6471. this.onLoadProgress = function () {};
  6472. this.onLoadComplete = function () {};
  6473. };
  6474. THREE.Loader.prototype = {
  6475. constructor: THREE.Loader,
  6476. crossOrigin: undefined,
  6477. addStatusElement: function () {
  6478. var e = document.createElement( "div" );
  6479. e.style.position = "absolute";
  6480. e.style.right = "0px";
  6481. e.style.top = "0px";
  6482. e.style.fontSize = "0.8em";
  6483. e.style.textAlign = "left";
  6484. e.style.background = "rgba(0,0,0,0.25)";
  6485. e.style.color = "#fff";
  6486. e.style.width = "120px";
  6487. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6488. e.style.zIndex = 1000;
  6489. e.innerHTML = "Loading ...";
  6490. return e;
  6491. },
  6492. updateProgress: function ( progress ) {
  6493. var message = "Loaded ";
  6494. if ( progress.total ) {
  6495. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6496. } else {
  6497. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  6498. }
  6499. this.statusDomElement.innerHTML = message;
  6500. },
  6501. extractUrlBase: function ( url ) {
  6502. var parts = url.split( '/' );
  6503. if ( parts.length === 1 ) return './';
  6504. parts.pop();
  6505. return parts.join( '/' ) + '/';
  6506. },
  6507. initMaterials: function ( materials, texturePath ) {
  6508. var array = [];
  6509. for ( var i = 0; i < materials.length; ++ i ) {
  6510. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  6511. }
  6512. return array;
  6513. },
  6514. needsTangents: function ( materials ) {
  6515. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6516. var m = materials[ i ];
  6517. if ( m instanceof THREE.ShaderMaterial ) return true;
  6518. }
  6519. return false;
  6520. },
  6521. createMaterial: function ( m, texturePath ) {
  6522. var _this = this;
  6523. function is_pow2( n ) {
  6524. var l = Math.log( n ) / Math.LN2;
  6525. return Math.floor( l ) == l;
  6526. }
  6527. function nearest_pow2( n ) {
  6528. var l = Math.log( n ) / Math.LN2;
  6529. return Math.pow( 2, Math.round( l ) );
  6530. }
  6531. function load_image( where, url ) {
  6532. var image = new Image();
  6533. image.onload = function () {
  6534. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  6535. var width = nearest_pow2( this.width );
  6536. var height = nearest_pow2( this.height );
  6537. where.image.width = width;
  6538. where.image.height = height;
  6539. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  6540. } else {
  6541. where.image = this;
  6542. }
  6543. where.needsUpdate = true;
  6544. };
  6545. if ( _this.crossOrigin !== undefined ) image.crossOrigin = _this.crossOrigin;
  6546. image.src = url;
  6547. }
  6548. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6549. var isCompressed = /\.dds$/i.test( sourceFile );
  6550. var fullPath = texturePath + sourceFile;
  6551. if ( isCompressed ) {
  6552. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  6553. where[ name ] = texture;
  6554. } else {
  6555. var texture = document.createElement( 'canvas' );
  6556. where[ name ] = new THREE.Texture( texture );
  6557. }
  6558. where[ name ].sourceFile = sourceFile;
  6559. if( repeat ) {
  6560. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6561. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6562. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6563. }
  6564. if ( offset ) {
  6565. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6566. }
  6567. if ( wrap ) {
  6568. var wrapMap = {
  6569. "repeat": THREE.RepeatWrapping,
  6570. "mirror": THREE.MirroredRepeatWrapping
  6571. }
  6572. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6573. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6574. }
  6575. if ( anisotropy ) {
  6576. where[ name ].anisotropy = anisotropy;
  6577. }
  6578. if ( ! isCompressed ) {
  6579. load_image( where[ name ], fullPath );
  6580. }
  6581. }
  6582. function rgb2hex( rgb ) {
  6583. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6584. }
  6585. // defaults
  6586. var mtype = "MeshLambertMaterial";
  6587. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6588. // parameters from model file
  6589. if ( m.shading ) {
  6590. var shading = m.shading.toLowerCase();
  6591. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6592. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6593. }
  6594. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6595. mpars.blending = THREE[ m.blending ];
  6596. }
  6597. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6598. mpars.transparent = m.transparent;
  6599. }
  6600. if ( m.depthTest !== undefined ) {
  6601. mpars.depthTest = m.depthTest;
  6602. }
  6603. if ( m.depthWrite !== undefined ) {
  6604. mpars.depthWrite = m.depthWrite;
  6605. }
  6606. if ( m.visible !== undefined ) {
  6607. mpars.visible = m.visible;
  6608. }
  6609. if ( m.flipSided !== undefined ) {
  6610. mpars.side = THREE.BackSide;
  6611. }
  6612. if ( m.doubleSided !== undefined ) {
  6613. mpars.side = THREE.DoubleSide;
  6614. }
  6615. if ( m.wireframe !== undefined ) {
  6616. mpars.wireframe = m.wireframe;
  6617. }
  6618. if ( m.vertexColors !== undefined ) {
  6619. if ( m.vertexColors === "face" ) {
  6620. mpars.vertexColors = THREE.FaceColors;
  6621. } else if ( m.vertexColors ) {
  6622. mpars.vertexColors = THREE.VertexColors;
  6623. }
  6624. }
  6625. // colors
  6626. if ( m.colorDiffuse ) {
  6627. mpars.color = rgb2hex( m.colorDiffuse );
  6628. } else if ( m.DbgColor ) {
  6629. mpars.color = m.DbgColor;
  6630. }
  6631. if ( m.colorSpecular ) {
  6632. mpars.specular = rgb2hex( m.colorSpecular );
  6633. }
  6634. if ( m.colorAmbient ) {
  6635. mpars.ambient = rgb2hex( m.colorAmbient );
  6636. }
  6637. // modifiers
  6638. if ( m.transparency ) {
  6639. mpars.opacity = m.transparency;
  6640. }
  6641. if ( m.specularCoef ) {
  6642. mpars.shininess = m.specularCoef;
  6643. }
  6644. // textures
  6645. if ( m.mapDiffuse && texturePath ) {
  6646. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6647. }
  6648. if ( m.mapLight && texturePath ) {
  6649. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6650. }
  6651. if ( m.mapBump && texturePath ) {
  6652. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6653. }
  6654. if ( m.mapNormal && texturePath ) {
  6655. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6656. }
  6657. if ( m.mapSpecular && texturePath ) {
  6658. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6659. }
  6660. //
  6661. if ( m.mapBumpScale ) {
  6662. mpars.bumpScale = m.mapBumpScale;
  6663. }
  6664. // special case for normal mapped material
  6665. if ( m.mapNormal ) {
  6666. var shader = THREE.ShaderLib[ "normalmap" ];
  6667. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6668. uniforms[ "tNormal" ].value = mpars.normalMap;
  6669. if ( m.mapNormalFactor ) {
  6670. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6671. }
  6672. if ( mpars.map ) {
  6673. uniforms[ "tDiffuse" ].value = mpars.map;
  6674. uniforms[ "enableDiffuse" ].value = true;
  6675. }
  6676. if ( mpars.specularMap ) {
  6677. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6678. uniforms[ "enableSpecular" ].value = true;
  6679. }
  6680. if ( mpars.lightMap ) {
  6681. uniforms[ "tAO" ].value = mpars.lightMap;
  6682. uniforms[ "enableAO" ].value = true;
  6683. }
  6684. // for the moment don't handle displacement texture
  6685. uniforms[ "diffuse" ].value.setHex( mpars.color );
  6686. uniforms[ "specular" ].value.setHex( mpars.specular );
  6687. uniforms[ "ambient" ].value.setHex( mpars.ambient );
  6688. uniforms[ "shininess" ].value = mpars.shininess;
  6689. if ( mpars.opacity !== undefined ) {
  6690. uniforms[ "opacity" ].value = mpars.opacity;
  6691. }
  6692. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6693. var material = new THREE.ShaderMaterial( parameters );
  6694. if ( mpars.transparent ) {
  6695. material.transparent = true;
  6696. }
  6697. } else {
  6698. var material = new THREE[ mtype ]( mpars );
  6699. }
  6700. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6701. return material;
  6702. }
  6703. };
  6704. /**
  6705. * @author mrdoob / http://mrdoob.com/
  6706. */
  6707. THREE.XHRLoader = function ( manager ) {
  6708. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6709. };
  6710. THREE.XHRLoader.prototype = {
  6711. constructor: THREE.XHRLoader,
  6712. load: function ( url, onLoad, onProgress, onError ) {
  6713. var scope = this;
  6714. var request = new XMLHttpRequest();
  6715. if ( onLoad !== undefined ) {
  6716. request.addEventListener( 'load', function ( event ) {
  6717. onLoad( event.target.responseText );
  6718. scope.manager.itemEnd( url );
  6719. }, false );
  6720. }
  6721. if ( onProgress !== undefined ) {
  6722. request.addEventListener( 'progress', function ( event ) {
  6723. onProgress( event );
  6724. }, false );
  6725. }
  6726. if ( onError !== undefined ) {
  6727. request.addEventListener( 'error', function ( event ) {
  6728. onError( event );
  6729. }, false );
  6730. }
  6731. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6732. request.open( 'GET', url, true );
  6733. request.send( null );
  6734. scope.manager.itemStart( url );
  6735. },
  6736. setCrossOrigin: function ( value ) {
  6737. this.crossOrigin = value;
  6738. }
  6739. };
  6740. /**
  6741. * @author mrdoob / http://mrdoob.com/
  6742. */
  6743. THREE.ImageLoader = function ( manager ) {
  6744. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6745. };
  6746. THREE.ImageLoader.prototype = {
  6747. constructor: THREE.ImageLoader,
  6748. load: function ( url, onLoad, onProgress, onError ) {
  6749. var scope = this;
  6750. var image = document.createElement( 'img' );
  6751. if ( onLoad !== undefined ) {
  6752. image.addEventListener( 'load', function ( event ) {
  6753. scope.manager.itemEnd( url );
  6754. onLoad( this );
  6755. }, false );
  6756. }
  6757. if ( onProgress !== undefined ) {
  6758. image.addEventListener( 'progress', function ( event ) {
  6759. onProgress( event );
  6760. }, false );
  6761. }
  6762. if ( onError !== undefined ) {
  6763. image.addEventListener( 'error', function ( event ) {
  6764. onError( event );
  6765. }, false );
  6766. }
  6767. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6768. image.src = url;
  6769. scope.manager.itemStart( url );
  6770. return image;
  6771. },
  6772. setCrossOrigin: function ( value ) {
  6773. this.crossOrigin = value;
  6774. }
  6775. }
  6776. /**
  6777. * @author mrdoob / http://mrdoob.com/
  6778. * @author alteredq / http://alteredqualia.com/
  6779. */
  6780. THREE.JSONLoader = function ( showStatus ) {
  6781. THREE.Loader.call( this, showStatus );
  6782. this.withCredentials = false;
  6783. };
  6784. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6785. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6786. var scope = this;
  6787. // todo: unify load API to for easier SceneLoader use
  6788. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6789. this.onLoadStart();
  6790. this.loadAjaxJSON( this, url, callback, texturePath );
  6791. };
  6792. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6793. var xhr = new XMLHttpRequest();
  6794. var length = 0;
  6795. xhr.onreadystatechange = function () {
  6796. if ( xhr.readyState === xhr.DONE ) {
  6797. if ( xhr.status === 200 || xhr.status === 0 ) {
  6798. if ( xhr.responseText ) {
  6799. var json = JSON.parse( xhr.responseText );
  6800. if ( json.metadata.type === 'scene' ) {
  6801. console.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' );
  6802. return;
  6803. }
  6804. var result = context.parse( json, texturePath );
  6805. callback( result.geometry, result.materials );
  6806. } else {
  6807. console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' );
  6808. }
  6809. // in context of more complex asset initialization
  6810. // do not block on single failed file
  6811. // maybe should go even one more level up
  6812. context.onLoadComplete();
  6813. } else {
  6814. console.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' );
  6815. }
  6816. } else if ( xhr.readyState === xhr.LOADING ) {
  6817. if ( callbackProgress ) {
  6818. if ( length === 0 ) {
  6819. length = xhr.getResponseHeader( 'Content-Length' );
  6820. }
  6821. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6822. }
  6823. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6824. if ( callbackProgress !== undefined ) {
  6825. length = xhr.getResponseHeader( "Content-Length" );
  6826. }
  6827. }
  6828. };
  6829. xhr.open( "GET", url, true );
  6830. xhr.withCredentials = this.withCredentials;
  6831. xhr.send( null );
  6832. };
  6833. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6834. var scope = this,
  6835. geometry = new THREE.Geometry(),
  6836. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6837. parseModel( scale );
  6838. parseSkin();
  6839. parseMorphing( scale );
  6840. geometry.computeCentroids();
  6841. geometry.computeFaceNormals();
  6842. geometry.computeBoundingSphere();
  6843. function parseModel( scale ) {
  6844. function isBitSet( value, position ) {
  6845. return value & ( 1 << position );
  6846. }
  6847. var i, j, fi,
  6848. offset, zLength,
  6849. colorIndex, normalIndex, uvIndex, materialIndex,
  6850. type,
  6851. isQuad,
  6852. hasMaterial,
  6853. hasFaceVertexUv,
  6854. hasFaceNormal, hasFaceVertexNormal,
  6855. hasFaceColor, hasFaceVertexColor,
  6856. vertex, face, faceA, faceB, color, hex, normal,
  6857. uvLayer, uv, u, v,
  6858. faces = json.faces,
  6859. vertices = json.vertices,
  6860. normals = json.normals,
  6861. colors = json.colors,
  6862. nUvLayers = 0;
  6863. if ( json.uvs !== undefined ) {
  6864. // disregard empty arrays
  6865. for ( i = 0; i < json.uvs.length; i++ ) {
  6866. if ( json.uvs[ i ].length ) nUvLayers ++;
  6867. }
  6868. for ( i = 0; i < nUvLayers; i++ ) {
  6869. geometry.faceVertexUvs[ i ] = [];
  6870. }
  6871. }
  6872. offset = 0;
  6873. zLength = vertices.length;
  6874. while ( offset < zLength ) {
  6875. vertex = new THREE.Vector3();
  6876. vertex.x = vertices[ offset ++ ] * scale;
  6877. vertex.y = vertices[ offset ++ ] * scale;
  6878. vertex.z = vertices[ offset ++ ] * scale;
  6879. geometry.vertices.push( vertex );
  6880. }
  6881. offset = 0;
  6882. zLength = faces.length;
  6883. while ( offset < zLength ) {
  6884. type = faces[ offset ++ ];
  6885. isQuad = isBitSet( type, 0 );
  6886. hasMaterial = isBitSet( type, 1 );
  6887. hasFaceVertexUv = isBitSet( type, 3 );
  6888. hasFaceNormal = isBitSet( type, 4 );
  6889. hasFaceVertexNormal = isBitSet( type, 5 );
  6890. hasFaceColor = isBitSet( type, 6 );
  6891. hasFaceVertexColor = isBitSet( type, 7 );
  6892. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6893. if ( isQuad ) {
  6894. faceA = new THREE.Face3();
  6895. faceA.a = faces[ offset ];
  6896. faceA.b = faces[ offset + 1 ];
  6897. faceA.c = faces[ offset + 3 ];
  6898. faceB = new THREE.Face3();
  6899. faceB.a = faces[ offset + 1 ];
  6900. faceB.b = faces[ offset + 2 ];
  6901. faceB.c = faces[ offset + 3 ];
  6902. offset += 4;
  6903. if ( hasMaterial ) {
  6904. materialIndex = faces[ offset ++ ];
  6905. faceA.materialIndex = materialIndex;
  6906. faceB.materialIndex = materialIndex;
  6907. }
  6908. // to get face <=> uv index correspondence
  6909. fi = geometry.faces.length;
  6910. if ( hasFaceVertexUv ) {
  6911. for ( i = 0; i < nUvLayers; i++ ) {
  6912. uvLayer = json.uvs[ i ];
  6913. geometry.faceVertexUvs[ i ][ fi ] = [];
  6914. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  6915. for ( j = 0; j < 4; j ++ ) {
  6916. uvIndex = faces[ offset ++ ];
  6917. u = uvLayer[ uvIndex * 2 ];
  6918. v = uvLayer[ uvIndex * 2 + 1 ];
  6919. uv = new THREE.Vector2( u, v );
  6920. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6921. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  6922. }
  6923. }
  6924. }
  6925. if ( hasFaceNormal ) {
  6926. normalIndex = faces[ offset ++ ] * 3;
  6927. faceA.normal.set(
  6928. normals[ normalIndex ++ ],
  6929. normals[ normalIndex ++ ],
  6930. normals[ normalIndex ]
  6931. );
  6932. faceB.normal.copy( faceA.normal );
  6933. }
  6934. if ( hasFaceVertexNormal ) {
  6935. for ( i = 0; i < 4; i++ ) {
  6936. normalIndex = faces[ offset ++ ] * 3;
  6937. normal = new THREE.Vector3(
  6938. normals[ normalIndex ++ ],
  6939. normals[ normalIndex ++ ],
  6940. normals[ normalIndex ]
  6941. );
  6942. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  6943. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  6944. }
  6945. }
  6946. if ( hasFaceColor ) {
  6947. colorIndex = faces[ offset ++ ];
  6948. hex = colors[ colorIndex ];
  6949. faceA.color.setHex( hex );
  6950. faceB.color.setHex( hex );
  6951. }
  6952. if ( hasFaceVertexColor ) {
  6953. for ( i = 0; i < 4; i++ ) {
  6954. colorIndex = faces[ offset ++ ];
  6955. hex = colors[ colorIndex ];
  6956. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  6957. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  6958. }
  6959. }
  6960. geometry.faces.push( faceA );
  6961. geometry.faces.push( faceB );
  6962. } else {
  6963. face = new THREE.Face3();
  6964. face.a = faces[ offset ++ ];
  6965. face.b = faces[ offset ++ ];
  6966. face.c = faces[ offset ++ ];
  6967. if ( hasMaterial ) {
  6968. materialIndex = faces[ offset ++ ];
  6969. face.materialIndex = materialIndex;
  6970. }
  6971. // to get face <=> uv index correspondence
  6972. fi = geometry.faces.length;
  6973. if ( hasFaceVertexUv ) {
  6974. for ( i = 0; i < nUvLayers; i++ ) {
  6975. uvLayer = json.uvs[ i ];
  6976. geometry.faceVertexUvs[ i ][ fi ] = [];
  6977. for ( j = 0; j < 3; j ++ ) {
  6978. uvIndex = faces[ offset ++ ];
  6979. u = uvLayer[ uvIndex * 2 ];
  6980. v = uvLayer[ uvIndex * 2 + 1 ];
  6981. uv = new THREE.Vector2( u, v );
  6982. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6983. }
  6984. }
  6985. }
  6986. if ( hasFaceNormal ) {
  6987. normalIndex = faces[ offset ++ ] * 3;
  6988. face.normal.set(
  6989. normals[ normalIndex ++ ],
  6990. normals[ normalIndex ++ ],
  6991. normals[ normalIndex ]
  6992. );
  6993. }
  6994. if ( hasFaceVertexNormal ) {
  6995. for ( i = 0; i < 3; i++ ) {
  6996. normalIndex = faces[ offset ++ ] * 3;
  6997. normal = new THREE.Vector3(
  6998. normals[ normalIndex ++ ],
  6999. normals[ normalIndex ++ ],
  7000. normals[ normalIndex ]
  7001. );
  7002. face.vertexNormals.push( normal );
  7003. }
  7004. }
  7005. if ( hasFaceColor ) {
  7006. colorIndex = faces[ offset ++ ];
  7007. face.color.setHex( colors[ colorIndex ] );
  7008. }
  7009. if ( hasFaceVertexColor ) {
  7010. for ( i = 0; i < 3; i++ ) {
  7011. colorIndex = faces[ offset ++ ];
  7012. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7013. }
  7014. }
  7015. geometry.faces.push( face );
  7016. }
  7017. }
  7018. };
  7019. function parseSkin() {
  7020. if ( json.skinWeights ) {
  7021. for ( var i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  7022. var x = json.skinWeights[ i ];
  7023. var y = json.skinWeights[ i + 1 ];
  7024. var z = 0;
  7025. var w = 0;
  7026. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7027. }
  7028. }
  7029. if ( json.skinIndices ) {
  7030. for ( var i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  7031. var a = json.skinIndices[ i ];
  7032. var b = json.skinIndices[ i + 1 ];
  7033. var c = 0;
  7034. var d = 0;
  7035. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  7036. }
  7037. }
  7038. geometry.bones = json.bones;
  7039. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  7040. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  7041. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  7042. }
  7043. // could change this to json.animations[0] or remove completely
  7044. geometry.animation = json.animation;
  7045. geometry.animations = json.animations;
  7046. };
  7047. function parseMorphing( scale ) {
  7048. if ( json.morphTargets !== undefined ) {
  7049. var i, l, v, vl, dstVertices, srcVertices;
  7050. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7051. geometry.morphTargets[ i ] = {};
  7052. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7053. geometry.morphTargets[ i ].vertices = [];
  7054. dstVertices = geometry.morphTargets[ i ].vertices;
  7055. srcVertices = json.morphTargets [ i ].vertices;
  7056. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7057. var vertex = new THREE.Vector3();
  7058. vertex.x = srcVertices[ v ] * scale;
  7059. vertex.y = srcVertices[ v + 1 ] * scale;
  7060. vertex.z = srcVertices[ v + 2 ] * scale;
  7061. dstVertices.push( vertex );
  7062. }
  7063. }
  7064. }
  7065. if ( json.morphColors !== undefined ) {
  7066. var i, l, c, cl, dstColors, srcColors, color;
  7067. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  7068. geometry.morphColors[ i ] = {};
  7069. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7070. geometry.morphColors[ i ].colors = [];
  7071. dstColors = geometry.morphColors[ i ].colors;
  7072. srcColors = json.morphColors [ i ].colors;
  7073. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7074. color = new THREE.Color( 0xffaa00 );
  7075. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7076. dstColors.push( color );
  7077. }
  7078. }
  7079. }
  7080. };
  7081. if ( json.materials === undefined ) {
  7082. return { geometry: geometry };
  7083. } else {
  7084. var materials = this.initMaterials( json.materials, texturePath );
  7085. if ( this.needsTangents( materials ) ) {
  7086. geometry.computeTangents();
  7087. }
  7088. return { geometry: geometry, materials: materials };
  7089. }
  7090. };
  7091. /**
  7092. * @author mrdoob / http://mrdoob.com/
  7093. */
  7094. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7095. var scope = this;
  7096. var loaded = 0, total = 0;
  7097. this.onLoad = onLoad;
  7098. this.onProgress = onProgress;
  7099. this.onError = onError;
  7100. this.itemStart = function ( url ) {
  7101. total ++;
  7102. };
  7103. this.itemEnd = function ( url ) {
  7104. loaded ++;
  7105. if ( scope.onProgress !== undefined ) {
  7106. scope.onProgress( url, loaded, total );
  7107. }
  7108. if ( loaded === total && scope.onLoad !== undefined ) {
  7109. scope.onLoad();
  7110. }
  7111. };
  7112. };
  7113. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7114. /**
  7115. * @author mrdoob / http://mrdoob.com/
  7116. */
  7117. THREE.BufferGeometryLoader = function ( manager ) {
  7118. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7119. };
  7120. THREE.BufferGeometryLoader.prototype = {
  7121. constructor: THREE.BufferGeometryLoader,
  7122. load: function ( url, onLoad, onProgress, onError ) {
  7123. var scope = this;
  7124. var loader = new THREE.XHRLoader();
  7125. loader.setCrossOrigin( this.crossOrigin );
  7126. loader.load( url, function ( text ) {
  7127. onLoad( scope.parse( JSON.parse( text ) ) );
  7128. } );
  7129. },
  7130. setCrossOrigin: function ( value ) {
  7131. this.crossOrigin = value;
  7132. },
  7133. parse: function ( json ) {
  7134. var geometry = new THREE.BufferGeometry();
  7135. var attributes = json.attributes;
  7136. var offsets = json.offsets;
  7137. var boundingSphere = json.boundingSphere;
  7138. for ( var key in attributes ) {
  7139. var attribute = attributes[ key ];
  7140. geometry.attributes[ key ] = {
  7141. itemSize: attribute.itemSize,
  7142. array: new self[ attribute.type ]( attribute.array )
  7143. }
  7144. }
  7145. if ( offsets !== undefined ) {
  7146. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7147. }
  7148. if ( boundingSphere !== undefined ) {
  7149. geometry.boundingSphere = new THREE.Sphere(
  7150. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  7151. boundingSphere.radius
  7152. );
  7153. }
  7154. return geometry;
  7155. }
  7156. };
  7157. /**
  7158. * @author mrdoob / http://mrdoob.com/
  7159. */
  7160. THREE.Geometry2Loader = function ( manager ) {
  7161. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7162. };
  7163. THREE.Geometry2Loader.prototype = {
  7164. constructor: THREE.Geometry2Loader,
  7165. load: function ( url, onLoad, onProgress, onError ) {
  7166. var scope = this;
  7167. var loader = new THREE.XHRLoader();
  7168. loader.setCrossOrigin( this.crossOrigin );
  7169. loader.load( url, function ( text ) {
  7170. onLoad( scope.parse( JSON.parse( text ) ) );
  7171. } );
  7172. },
  7173. setCrossOrigin: function ( value ) {
  7174. this.crossOrigin = value;
  7175. },
  7176. parse: function ( json ) {
  7177. var geometry = new THREE.Geometry2( json.vertices.length / 3 );
  7178. var attributes = [ 'vertices', 'normals', 'uvs' ];
  7179. var boundingSphere = json.boundingSphere;
  7180. for ( var key in attributes ) {
  7181. var attribute = attributes[ key ];
  7182. geometry[ attribute ].set( json[ attribute ] );
  7183. }
  7184. if ( boundingSphere !== undefined ) {
  7185. geometry.boundingSphere = new THREE.Sphere(
  7186. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  7187. boundingSphere.radius
  7188. );
  7189. }
  7190. return geometry;
  7191. }
  7192. };
  7193. /**
  7194. * @author mrdoob / http://mrdoob.com/
  7195. */
  7196. THREE.MaterialLoader = function ( manager ) {
  7197. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7198. };
  7199. THREE.MaterialLoader.prototype = {
  7200. constructor: THREE.MaterialLoader,
  7201. load: function ( url, onLoad, onProgress, onError ) {
  7202. var scope = this;
  7203. var loader = new THREE.XHRLoader();
  7204. loader.setCrossOrigin( this.crossOrigin );
  7205. loader.load( url, function ( text ) {
  7206. onLoad( scope.parse( JSON.parse( text ) ) );
  7207. } );
  7208. },
  7209. setCrossOrigin: function ( value ) {
  7210. this.crossOrigin = value;
  7211. },
  7212. parse: function ( json ) {
  7213. var material = new THREE[ json.type ];
  7214. if ( json.color !== undefined ) material.color.setHex( json.color );
  7215. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  7216. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7217. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7218. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7219. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7220. if ( json.blending !== undefined ) material.blending = json.blending;
  7221. if ( json.side !== undefined ) material.side = json.side;
  7222. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  7223. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  7224. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  7225. if ( json.materials !== undefined ) {
  7226. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  7227. material.materials.push( this.parse( json.materials[ i ] ) );
  7228. }
  7229. }
  7230. return material;
  7231. }
  7232. };
  7233. /**
  7234. * @author mrdoob / http://mrdoob.com/
  7235. */
  7236. THREE.ObjectLoader = function ( manager ) {
  7237. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7238. };
  7239. THREE.ObjectLoader.prototype = {
  7240. constructor: THREE.ObjectLoader,
  7241. load: function ( url, onLoad, onProgress, onError ) {
  7242. var scope = this;
  7243. var loader = new THREE.XHRLoader( scope.manager );
  7244. loader.setCrossOrigin( this.crossOrigin );
  7245. loader.load( url, function ( text ) {
  7246. onLoad( scope.parse( JSON.parse( text ) ) );
  7247. } );
  7248. },
  7249. setCrossOrigin: function ( value ) {
  7250. this.crossOrigin = value;
  7251. },
  7252. parse: function ( json ) {
  7253. var geometries = this.parseGeometries( json.geometries );
  7254. var materials = this.parseMaterials( json.materials );
  7255. var object = this.parseObject( json.object, geometries, materials );
  7256. return object;
  7257. },
  7258. parseGeometries: function ( json ) {
  7259. var geometries = {};
  7260. if ( json !== undefined ) {
  7261. var geometryLoader = new THREE.JSONLoader();
  7262. var geometry2Loader = new THREE.Geometry2Loader();
  7263. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7264. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7265. var geometry;
  7266. var data = json[ i ];
  7267. switch ( data.type ) {
  7268. case 'PlaneGeometry':
  7269. geometry = new THREE.PlaneGeometry(
  7270. data.width,
  7271. data.height,
  7272. data.widthSegments,
  7273. data.heightSegments
  7274. );
  7275. break;
  7276. case 'BoxGeometry':
  7277. case 'CubeGeometry': // DEPRECATED
  7278. geometry = new THREE.BoxGeometry(
  7279. data.width,
  7280. data.height,
  7281. data.depth,
  7282. data.widthSegments,
  7283. data.heightSegments,
  7284. data.depthSegments
  7285. );
  7286. break;
  7287. case 'CircleGeometry':
  7288. geometry = new THREE.CircleGeometry(
  7289. data.radius,
  7290. data.segments
  7291. );
  7292. break;
  7293. case 'CylinderGeometry':
  7294. geometry = new THREE.CylinderGeometry(
  7295. data.radiusTop,
  7296. data.radiusBottom,
  7297. data.height,
  7298. data.radialSegments,
  7299. data.heightSegments,
  7300. data.openEnded
  7301. );
  7302. break;
  7303. case 'SphereGeometry':
  7304. geometry = new THREE.SphereGeometry(
  7305. data.radius,
  7306. data.widthSegments,
  7307. data.heightSegments,
  7308. data.phiStart,
  7309. data.phiLength,
  7310. data.thetaStart,
  7311. data.thetaLength
  7312. );
  7313. break;
  7314. case 'IcosahedronGeometry':
  7315. geometry = new THREE.IcosahedronGeometry(
  7316. data.radius,
  7317. data.detail
  7318. );
  7319. break;
  7320. case 'TorusGeometry':
  7321. geometry = new THREE.TorusGeometry(
  7322. data.radius,
  7323. data.tube,
  7324. data.radialSegments,
  7325. data.tubularSegments,
  7326. data.arc
  7327. );
  7328. break;
  7329. case 'TorusKnotGeometry':
  7330. geometry = new THREE.TorusKnotGeometry(
  7331. data.radius,
  7332. data.tube,
  7333. data.radialSegments,
  7334. data.tubularSegments,
  7335. data.p,
  7336. data.q,
  7337. data.heightScale
  7338. );
  7339. break;
  7340. case 'BufferGeometry':
  7341. geometry = bufferGeometryLoader.parse( data.data );
  7342. break;
  7343. case 'Geometry2':
  7344. geometry = geometry2Loader.parse( data.data );
  7345. break;
  7346. case 'Geometry':
  7347. geometry = geometryLoader.parse( data.data ).geometry;
  7348. break;
  7349. }
  7350. geometry.uuid = data.uuid;
  7351. if ( data.name !== undefined ) geometry.name = data.name;
  7352. geometries[ data.uuid ] = geometry;
  7353. }
  7354. }
  7355. return geometries;
  7356. },
  7357. parseMaterials: function ( json ) {
  7358. var materials = {};
  7359. if ( json !== undefined ) {
  7360. var loader = new THREE.MaterialLoader();
  7361. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7362. var data = json[ i ];
  7363. var material = loader.parse( data );
  7364. material.uuid = data.uuid;
  7365. if ( data.name !== undefined ) material.name = data.name;
  7366. materials[ data.uuid ] = material;
  7367. }
  7368. }
  7369. return materials;
  7370. },
  7371. parseObject: function () {
  7372. var matrix = new THREE.Matrix4();
  7373. return function ( data, geometries, materials ) {
  7374. var object;
  7375. switch ( data.type ) {
  7376. case 'Scene':
  7377. object = new THREE.Scene();
  7378. break;
  7379. case 'PerspectiveCamera':
  7380. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7381. break;
  7382. case 'OrthographicCamera':
  7383. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7384. break;
  7385. case 'AmbientLight':
  7386. object = new THREE.AmbientLight( data.color );
  7387. break;
  7388. case 'DirectionalLight':
  7389. object = new THREE.DirectionalLight( data.color, data.intensity );
  7390. break;
  7391. case 'PointLight':
  7392. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  7393. break;
  7394. case 'SpotLight':
  7395. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  7396. break;
  7397. case 'HemisphereLight':
  7398. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7399. break;
  7400. case 'Mesh':
  7401. var geometry = geometries[ data.geometry ];
  7402. var material = materials[ data.material ];
  7403. if ( geometry === undefined ) {
  7404. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  7405. }
  7406. if ( material === undefined ) {
  7407. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7408. }
  7409. object = new THREE.Mesh( geometry, material );
  7410. break;
  7411. case 'Sprite':
  7412. var material = materials[ data.material ];
  7413. if ( material === undefined ) {
  7414. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7415. }
  7416. object = new THREE.Sprite( material );
  7417. break;
  7418. default:
  7419. object = new THREE.Object3D();
  7420. }
  7421. object.uuid = data.uuid;
  7422. if ( data.name !== undefined ) object.name = data.name;
  7423. if ( data.matrix !== undefined ) {
  7424. matrix.fromArray( data.matrix );
  7425. matrix.decompose( object.position, object.quaternion, object.scale );
  7426. } else {
  7427. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7428. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7429. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7430. }
  7431. if ( data.visible !== undefined ) object.visible = data.visible;
  7432. if ( data.userData !== undefined ) object.userData = data.userData;
  7433. if ( data.children !== undefined ) {
  7434. for ( var child in data.children ) {
  7435. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7436. }
  7437. }
  7438. return object;
  7439. }
  7440. }()
  7441. };
  7442. /**
  7443. * @author alteredq / http://alteredqualia.com/
  7444. */
  7445. THREE.SceneLoader = function () {
  7446. this.onLoadStart = function () {};
  7447. this.onLoadProgress = function() {};
  7448. this.onLoadComplete = function () {};
  7449. this.callbackSync = function () {};
  7450. this.callbackProgress = function () {};
  7451. this.geometryHandlers = {};
  7452. this.hierarchyHandlers = {};
  7453. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  7454. };
  7455. THREE.SceneLoader.prototype = {
  7456. constructor: THREE.SceneLoader,
  7457. load: function ( url, onLoad, onProgress, onError ) {
  7458. var scope = this;
  7459. var loader = new THREE.XHRLoader( scope.manager );
  7460. loader.setCrossOrigin( this.crossOrigin );
  7461. loader.load( url, function ( text ) {
  7462. scope.parse( JSON.parse( text ), onLoad, url );
  7463. } );
  7464. },
  7465. setCrossOrigin: function ( value ) {
  7466. this.crossOrigin = value;
  7467. },
  7468. addGeometryHandler: function ( typeID, loaderClass ) {
  7469. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  7470. },
  7471. addHierarchyHandler: function ( typeID, loaderClass ) {
  7472. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  7473. },
  7474. parse: function ( json, callbackFinished, url ) {
  7475. var scope = this;
  7476. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  7477. var geometry, material, camera, fog,
  7478. texture, images, color,
  7479. light, hex, intensity,
  7480. counter_models, counter_textures,
  7481. total_models, total_textures,
  7482. result;
  7483. var target_array = [];
  7484. var data = json;
  7485. // async geometry loaders
  7486. for ( var typeID in this.geometryHandlers ) {
  7487. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  7488. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7489. }
  7490. // async hierachy loaders
  7491. for ( var typeID in this.hierarchyHandlers ) {
  7492. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  7493. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7494. }
  7495. counter_models = 0;
  7496. counter_textures = 0;
  7497. result = {
  7498. scene: new THREE.Scene(),
  7499. geometries: {},
  7500. face_materials: {},
  7501. materials: {},
  7502. textures: {},
  7503. objects: {},
  7504. cameras: {},
  7505. lights: {},
  7506. fogs: {},
  7507. empties: {},
  7508. groups: {}
  7509. };
  7510. if ( data.transform ) {
  7511. var position = data.transform.position,
  7512. rotation = data.transform.rotation,
  7513. scale = data.transform.scale;
  7514. if ( position ) {
  7515. result.scene.position.fromArray( position );
  7516. }
  7517. if ( rotation ) {
  7518. result.scene.rotation.fromArray( rotation );
  7519. }
  7520. if ( scale ) {
  7521. result.scene.scale.fromArray( scale );
  7522. }
  7523. if ( position || rotation || scale ) {
  7524. result.scene.updateMatrix();
  7525. result.scene.updateMatrixWorld();
  7526. }
  7527. }
  7528. function get_url( source_url, url_type ) {
  7529. if ( url_type == "relativeToHTML" ) {
  7530. return source_url;
  7531. } else {
  7532. return urlBase + source_url;
  7533. }
  7534. };
  7535. // toplevel loader function, delegates to handle_children
  7536. function handle_objects() {
  7537. handle_children( result.scene, data.objects );
  7538. }
  7539. // handle all the children from the loaded json and attach them to given parent
  7540. function handle_children( parent, children ) {
  7541. var mat, dst, pos, rot, scl, quat;
  7542. for ( var objID in children ) {
  7543. // check by id if child has already been handled,
  7544. // if not, create new object
  7545. var object = result.objects[ objID ];
  7546. var objJSON = children[ objID ];
  7547. if ( object === undefined ) {
  7548. // meshes
  7549. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7550. if ( objJSON.loading === undefined ) {
  7551. var reservedTypes = {
  7552. "type": 1, "url": 1, "material": 1,
  7553. "position": 1, "rotation": 1, "scale" : 1,
  7554. "visible": 1, "children": 1, "userData": 1,
  7555. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  7556. };
  7557. var loaderParameters = {};
  7558. for ( var parType in objJSON ) {
  7559. if ( ! ( parType in reservedTypes ) ) {
  7560. loaderParameters[ parType ] = objJSON[ parType ];
  7561. }
  7562. }
  7563. material = result.materials[ objJSON.material ];
  7564. objJSON.loading = true;
  7565. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  7566. // ColladaLoader
  7567. if ( loader.options ) {
  7568. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  7569. // UTF8Loader
  7570. // OBJLoader
  7571. } else {
  7572. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  7573. }
  7574. }
  7575. } else if ( objJSON.geometry !== undefined ) {
  7576. geometry = result.geometries[ objJSON.geometry ];
  7577. // geometry already loaded
  7578. if ( geometry ) {
  7579. var needsTangents = false;
  7580. material = result.materials[ objJSON.material ];
  7581. needsTangents = material instanceof THREE.ShaderMaterial;
  7582. pos = objJSON.position;
  7583. rot = objJSON.rotation;
  7584. scl = objJSON.scale;
  7585. mat = objJSON.matrix;
  7586. quat = objJSON.quaternion;
  7587. // use materials from the model file
  7588. // if there is no material specified in the object
  7589. if ( ! objJSON.material ) {
  7590. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7591. }
  7592. // use materials from the model file
  7593. // if there is just empty face material
  7594. // (must create new material as each model has its own face material)
  7595. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  7596. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7597. }
  7598. if ( material instanceof THREE.MeshFaceMaterial ) {
  7599. for ( var i = 0; i < material.materials.length; i ++ ) {
  7600. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  7601. }
  7602. }
  7603. if ( needsTangents ) {
  7604. geometry.computeTangents();
  7605. }
  7606. if ( objJSON.skin ) {
  7607. object = new THREE.SkinnedMesh( geometry, material );
  7608. } else if ( objJSON.morph ) {
  7609. object = new THREE.MorphAnimMesh( geometry, material );
  7610. if ( objJSON.duration !== undefined ) {
  7611. object.duration = objJSON.duration;
  7612. }
  7613. if ( objJSON.time !== undefined ) {
  7614. object.time = objJSON.time;
  7615. }
  7616. if ( objJSON.mirroredLoop !== undefined ) {
  7617. object.mirroredLoop = objJSON.mirroredLoop;
  7618. }
  7619. if ( material.morphNormals ) {
  7620. geometry.computeMorphNormals();
  7621. }
  7622. } else {
  7623. object = new THREE.Mesh( geometry, material );
  7624. }
  7625. object.name = objID;
  7626. if ( mat ) {
  7627. object.matrixAutoUpdate = false;
  7628. object.matrix.set(
  7629. mat[0], mat[1], mat[2], mat[3],
  7630. mat[4], mat[5], mat[6], mat[7],
  7631. mat[8], mat[9], mat[10], mat[11],
  7632. mat[12], mat[13], mat[14], mat[15]
  7633. );
  7634. } else {
  7635. object.position.fromArray( pos );
  7636. if ( quat ) {
  7637. object.quaternion.fromArray( quat );
  7638. } else {
  7639. object.rotation.fromArray( rot );
  7640. }
  7641. object.scale.fromArray( scl );
  7642. }
  7643. object.visible = objJSON.visible;
  7644. object.castShadow = objJSON.castShadow;
  7645. object.receiveShadow = objJSON.receiveShadow;
  7646. parent.add( object );
  7647. result.objects[ objID ] = object;
  7648. }
  7649. // lights
  7650. } else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" ||
  7651. objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" ||
  7652. objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) {
  7653. var color = objJSON.color;
  7654. var intensity = objJSON.intensity;
  7655. var distance = objJSON.distance;
  7656. var position = objJSON.position;
  7657. var rotation = objJSON.rotation;
  7658. switch ( objJSON.type ) {
  7659. case 'AmbientLight':
  7660. light = new THREE.AmbientLight( color );
  7661. break;
  7662. case 'PointLight':
  7663. light = new THREE.PointLight( color, intensity, distance );
  7664. light.position.fromArray( position );
  7665. break;
  7666. case 'DirectionalLight':
  7667. light = new THREE.DirectionalLight( color, intensity );
  7668. light.position.fromArray( objJSON.direction );
  7669. break;
  7670. case 'SpotLight':
  7671. light = new THREE.SpotLight( color, intensity, distance, 1 );
  7672. light.angle = objJSON.angle;
  7673. light.position.fromArray( position );
  7674. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7675. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7676. break;
  7677. case 'HemisphereLight':
  7678. light = new THREE.DirectionalLight( color, intensity, distance );
  7679. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7680. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7681. break;
  7682. case 'AreaLight':
  7683. light = new THREE.AreaLight(color, intensity);
  7684. light.position.fromArray( position );
  7685. light.width = objJSON.size;
  7686. light.height = objJSON.size_y;
  7687. break;
  7688. }
  7689. parent.add( light );
  7690. light.name = objID;
  7691. result.lights[ objID ] = light;
  7692. result.objects[ objID ] = light;
  7693. // cameras
  7694. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  7695. pos = objJSON.position;
  7696. rot = objJSON.rotation;
  7697. quat = objJSON.quaternion;
  7698. if ( objJSON.type === "PerspectiveCamera" ) {
  7699. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  7700. } else if ( objJSON.type === "OrthographicCamera" ) {
  7701. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  7702. }
  7703. camera.name = objID;
  7704. camera.position.fromArray( pos );
  7705. if ( quat !== undefined ) {
  7706. camera.quaternion.fromArray( quat );
  7707. } else if ( rot !== undefined ) {
  7708. camera.rotation.fromArray( rot );
  7709. }
  7710. parent.add( camera );
  7711. result.cameras[ objID ] = camera;
  7712. result.objects[ objID ] = camera;
  7713. // pure Object3D
  7714. } else {
  7715. pos = objJSON.position;
  7716. rot = objJSON.rotation;
  7717. scl = objJSON.scale;
  7718. quat = objJSON.quaternion;
  7719. object = new THREE.Object3D();
  7720. object.name = objID;
  7721. object.position.fromArray( pos );
  7722. if ( quat ) {
  7723. object.quaternion.fromArray( quat );
  7724. } else {
  7725. object.rotation.fromArray( rot );
  7726. }
  7727. object.scale.fromArray( scl );
  7728. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  7729. parent.add( object );
  7730. result.objects[ objID ] = object;
  7731. result.empties[ objID ] = object;
  7732. }
  7733. if ( object ) {
  7734. if ( objJSON.userData !== undefined ) {
  7735. for ( var key in objJSON.userData ) {
  7736. var value = objJSON.userData[ key ];
  7737. object.userData[ key ] = value;
  7738. }
  7739. }
  7740. if ( objJSON.groups !== undefined ) {
  7741. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  7742. var groupID = objJSON.groups[ i ];
  7743. if ( result.groups[ groupID ] === undefined ) {
  7744. result.groups[ groupID ] = [];
  7745. }
  7746. result.groups[ groupID ].push( objID );
  7747. }
  7748. }
  7749. }
  7750. }
  7751. if ( object !== undefined && objJSON.children !== undefined ) {
  7752. handle_children( object, objJSON.children );
  7753. }
  7754. }
  7755. };
  7756. function handle_mesh( geo, mat, id ) {
  7757. result.geometries[ id ] = geo;
  7758. result.face_materials[ id ] = mat;
  7759. handle_objects();
  7760. };
  7761. function handle_hierarchy( node, id, parent, material, obj ) {
  7762. var p = obj.position;
  7763. var r = obj.rotation;
  7764. var q = obj.quaternion;
  7765. var s = obj.scale;
  7766. node.position.fromArray( p );
  7767. if ( q ) {
  7768. node.quaternion.fromArray( q );
  7769. } else {
  7770. node.rotation.fromArray( r );
  7771. }
  7772. node.scale.fromArray( s );
  7773. // override children materials
  7774. // if object material was specified in JSON explicitly
  7775. if ( material ) {
  7776. node.traverse( function ( child ) {
  7777. child.material = material;
  7778. } );
  7779. }
  7780. // override children visibility
  7781. // with root node visibility as specified in JSON
  7782. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  7783. node.traverse( function ( child ) {
  7784. child.visible = visible;
  7785. } );
  7786. parent.add( node );
  7787. node.name = id;
  7788. result.objects[ id ] = node;
  7789. handle_objects();
  7790. };
  7791. function create_callback_geometry( id ) {
  7792. return function ( geo, mat ) {
  7793. geo.name = id;
  7794. handle_mesh( geo, mat, id );
  7795. counter_models -= 1;
  7796. scope.onLoadComplete();
  7797. async_callback_gate();
  7798. }
  7799. };
  7800. function create_callback_hierachy( id, parent, material, obj ) {
  7801. return function ( event ) {
  7802. var result;
  7803. // loaders which use EventDispatcher
  7804. if ( event.content ) {
  7805. result = event.content;
  7806. // ColladaLoader
  7807. } else if ( event.dae ) {
  7808. result = event.scene;
  7809. // UTF8Loader
  7810. } else {
  7811. result = event;
  7812. }
  7813. handle_hierarchy( result, id, parent, material, obj );
  7814. counter_models -= 1;
  7815. scope.onLoadComplete();
  7816. async_callback_gate();
  7817. }
  7818. };
  7819. function create_callback_embed( id ) {
  7820. return function ( geo, mat ) {
  7821. geo.name = id;
  7822. result.geometries[ id ] = geo;
  7823. result.face_materials[ id ] = mat;
  7824. }
  7825. };
  7826. function async_callback_gate() {
  7827. var progress = {
  7828. totalModels : total_models,
  7829. totalTextures : total_textures,
  7830. loadedModels : total_models - counter_models,
  7831. loadedTextures : total_textures - counter_textures
  7832. };
  7833. scope.callbackProgress( progress, result );
  7834. scope.onLoadProgress();
  7835. if ( counter_models === 0 && counter_textures === 0 ) {
  7836. finalize();
  7837. callbackFinished( result );
  7838. }
  7839. };
  7840. function finalize() {
  7841. // take care of targets which could be asynchronously loaded objects
  7842. for ( var i = 0; i < target_array.length; i ++ ) {
  7843. var ta = target_array[ i ];
  7844. var target = result.objects[ ta.targetName ];
  7845. if ( target ) {
  7846. ta.object.target = target;
  7847. } else {
  7848. // if there was error and target of specified name doesn't exist in the scene file
  7849. // create instead dummy target
  7850. // (target must be added to scene explicitly as parent is already added)
  7851. ta.object.target = new THREE.Object3D();
  7852. result.scene.add( ta.object.target );
  7853. }
  7854. ta.object.target.userData.targetInverse = ta.object;
  7855. }
  7856. };
  7857. var callbackTexture = function ( count ) {
  7858. counter_textures -= count;
  7859. async_callback_gate();
  7860. scope.onLoadComplete();
  7861. };
  7862. // must use this instead of just directly calling callbackTexture
  7863. // because of closure in the calling context loop
  7864. var generateTextureCallback = function ( count ) {
  7865. return function () {
  7866. callbackTexture( count );
  7867. };
  7868. };
  7869. function traverse_json_hierarchy( objJSON, callback ) {
  7870. callback( objJSON );
  7871. if ( objJSON.children !== undefined ) {
  7872. for ( var objChildID in objJSON.children ) {
  7873. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7874. }
  7875. }
  7876. };
  7877. // first go synchronous elements
  7878. // fogs
  7879. var fogID, fogJSON;
  7880. for ( fogID in data.fogs ) {
  7881. fogJSON = data.fogs[ fogID ];
  7882. if ( fogJSON.type === "linear" ) {
  7883. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7884. } else if ( fogJSON.type === "exp2" ) {
  7885. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7886. }
  7887. color = fogJSON.color;
  7888. fog.color.setRGB( color[0], color[1], color[2] );
  7889. result.fogs[ fogID ] = fog;
  7890. }
  7891. // now come potentially asynchronous elements
  7892. // geometries
  7893. // count how many geometries will be loaded asynchronously
  7894. var geoID, geoJSON;
  7895. for ( geoID in data.geometries ) {
  7896. geoJSON = data.geometries[ geoID ];
  7897. if ( geoJSON.type in this.geometryHandlers ) {
  7898. counter_models += 1;
  7899. scope.onLoadStart();
  7900. }
  7901. }
  7902. // count how many hierarchies will be loaded asynchronously
  7903. for ( var objID in data.objects ) {
  7904. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7905. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7906. counter_models += 1;
  7907. scope.onLoadStart();
  7908. }
  7909. });
  7910. }
  7911. total_models = counter_models;
  7912. for ( geoID in data.geometries ) {
  7913. geoJSON = data.geometries[ geoID ];
  7914. if ( geoJSON.type === "cube" ) {
  7915. geometry = new THREE.BoxGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7916. geometry.name = geoID;
  7917. result.geometries[ geoID ] = geometry;
  7918. } else if ( geoJSON.type === "plane" ) {
  7919. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7920. geometry.name = geoID;
  7921. result.geometries[ geoID ] = geometry;
  7922. } else if ( geoJSON.type === "sphere" ) {
  7923. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7924. geometry.name = geoID;
  7925. result.geometries[ geoID ] = geometry;
  7926. } else if ( geoJSON.type === "cylinder" ) {
  7927. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  7928. geometry.name = geoID;
  7929. result.geometries[ geoID ] = geometry;
  7930. } else if ( geoJSON.type === "torus" ) {
  7931. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  7932. geometry.name = geoID;
  7933. result.geometries[ geoID ] = geometry;
  7934. } else if ( geoJSON.type === "icosahedron" ) {
  7935. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  7936. geometry.name = geoID;
  7937. result.geometries[ geoID ] = geometry;
  7938. } else if ( geoJSON.type in this.geometryHandlers ) {
  7939. var loaderParameters = {};
  7940. for ( var parType in geoJSON ) {
  7941. if ( parType !== "type" && parType !== "url" ) {
  7942. loaderParameters[ parType ] = geoJSON[ parType ];
  7943. }
  7944. }
  7945. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7946. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7947. } else if ( geoJSON.type === "embedded" ) {
  7948. var modelJson = data.embeds[ geoJSON.id ],
  7949. texture_path = "";
  7950. // pass metadata along to jsonLoader so it knows the format version
  7951. modelJson.metadata = data.metadata;
  7952. if ( modelJson ) {
  7953. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7954. var model = jsonLoader.parse( modelJson, texture_path );
  7955. create_callback_embed( geoID )( model.geometry, model.materials );
  7956. }
  7957. }
  7958. }
  7959. // textures
  7960. // count how many textures will be loaded asynchronously
  7961. var textureID, textureJSON;
  7962. for ( textureID in data.textures ) {
  7963. textureJSON = data.textures[ textureID ];
  7964. if ( textureJSON.url instanceof Array ) {
  7965. counter_textures += textureJSON.url.length;
  7966. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  7967. scope.onLoadStart();
  7968. }
  7969. } else {
  7970. counter_textures += 1;
  7971. scope.onLoadStart();
  7972. }
  7973. }
  7974. total_textures = counter_textures;
  7975. for ( textureID in data.textures ) {
  7976. textureJSON = data.textures[ textureID ];
  7977. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  7978. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  7979. }
  7980. if ( textureJSON.url instanceof Array ) {
  7981. var count = textureJSON.url.length;
  7982. var url_array = [];
  7983. for( var i = 0; i < count; i ++ ) {
  7984. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  7985. }
  7986. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  7987. if ( isCompressed ) {
  7988. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7989. } else {
  7990. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7991. }
  7992. } else {
  7993. var isCompressed = /\.dds$/i.test( textureJSON.url );
  7994. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  7995. var textureCallback = generateTextureCallback( 1 );
  7996. if ( isCompressed ) {
  7997. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  7998. } else {
  7999. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  8000. }
  8001. if ( THREE[ textureJSON.minFilter ] !== undefined )
  8002. texture.minFilter = THREE[ textureJSON.minFilter ];
  8003. if ( THREE[ textureJSON.magFilter ] !== undefined )
  8004. texture.magFilter = THREE[ textureJSON.magFilter ];
  8005. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  8006. if ( textureJSON.repeat ) {
  8007. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  8008. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  8009. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  8010. }
  8011. if ( textureJSON.offset ) {
  8012. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  8013. }
  8014. // handle wrap after repeat so that default repeat can be overriden
  8015. if ( textureJSON.wrap ) {
  8016. var wrapMap = {
  8017. "repeat": THREE.RepeatWrapping,
  8018. "mirror": THREE.MirroredRepeatWrapping
  8019. }
  8020. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  8021. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  8022. }
  8023. }
  8024. result.textures[ textureID ] = texture;
  8025. }
  8026. // materials
  8027. var matID, matJSON;
  8028. var parID;
  8029. for ( matID in data.materials ) {
  8030. matJSON = data.materials[ matID ];
  8031. for ( parID in matJSON.parameters ) {
  8032. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  8033. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  8034. } else if ( parID === "shading" ) {
  8035. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  8036. } else if ( parID === "side" ) {
  8037. if ( matJSON.parameters[ parID ] == "double" ) {
  8038. matJSON.parameters[ parID ] = THREE.DoubleSide;
  8039. } else if ( matJSON.parameters[ parID ] == "back" ) {
  8040. matJSON.parameters[ parID ] = THREE.BackSide;
  8041. } else {
  8042. matJSON.parameters[ parID ] = THREE.FrontSide;
  8043. }
  8044. } else if ( parID === "blending" ) {
  8045. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  8046. } else if ( parID === "combine" ) {
  8047. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  8048. } else if ( parID === "vertexColors" ) {
  8049. if ( matJSON.parameters[ parID ] == "face" ) {
  8050. matJSON.parameters[ parID ] = THREE.FaceColors;
  8051. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  8052. } else if ( matJSON.parameters[ parID ] ) {
  8053. matJSON.parameters[ parID ] = THREE.VertexColors;
  8054. }
  8055. } else if ( parID === "wrapRGB" ) {
  8056. var v3 = matJSON.parameters[ parID ];
  8057. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  8058. }
  8059. }
  8060. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  8061. matJSON.parameters.transparent = true;
  8062. }
  8063. if ( matJSON.parameters.normalMap ) {
  8064. var shader = THREE.ShaderLib[ "normalmap" ];
  8065. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  8066. var diffuse = matJSON.parameters.color;
  8067. var specular = matJSON.parameters.specular;
  8068. var ambient = matJSON.parameters.ambient;
  8069. var shininess = matJSON.parameters.shininess;
  8070. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  8071. if ( matJSON.parameters.normalScale ) {
  8072. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  8073. }
  8074. if ( matJSON.parameters.map ) {
  8075. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  8076. uniforms[ "enableDiffuse" ].value = true;
  8077. }
  8078. if ( matJSON.parameters.envMap ) {
  8079. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  8080. uniforms[ "enableReflection" ].value = true;
  8081. uniforms[ "reflectivity" ].value = matJSON.parameters.reflectivity;
  8082. }
  8083. if ( matJSON.parameters.lightMap ) {
  8084. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  8085. uniforms[ "enableAO" ].value = true;
  8086. }
  8087. if ( matJSON.parameters.specularMap ) {
  8088. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  8089. uniforms[ "enableSpecular" ].value = true;
  8090. }
  8091. if ( matJSON.parameters.displacementMap ) {
  8092. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  8093. uniforms[ "enableDisplacement" ].value = true;
  8094. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  8095. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  8096. }
  8097. uniforms[ "diffuse" ].value.setHex( diffuse );
  8098. uniforms[ "specular" ].value.setHex( specular );
  8099. uniforms[ "ambient" ].value.setHex( ambient );
  8100. uniforms[ "shininess" ].value = shininess;
  8101. if ( matJSON.parameters.opacity ) {
  8102. uniforms[ "opacity" ].value = matJSON.parameters.opacity;
  8103. }
  8104. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  8105. material = new THREE.ShaderMaterial( parameters );
  8106. } else {
  8107. material = new THREE[ matJSON.type ]( matJSON.parameters );
  8108. }
  8109. material.name = matID;
  8110. result.materials[ matID ] = material;
  8111. }
  8112. // second pass through all materials to initialize MeshFaceMaterials
  8113. // that could be referring to other materials out of order
  8114. for ( matID in data.materials ) {
  8115. matJSON = data.materials[ matID ];
  8116. if ( matJSON.parameters.materials ) {
  8117. var materialArray = [];
  8118. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  8119. var label = matJSON.parameters.materials[ i ];
  8120. materialArray.push( result.materials[ label ] );
  8121. }
  8122. result.materials[ matID ].materials = materialArray;
  8123. }
  8124. }
  8125. // objects ( synchronous init of procedural primitives )
  8126. handle_objects();
  8127. // defaults
  8128. if ( result.cameras && data.defaults.camera ) {
  8129. result.currentCamera = result.cameras[ data.defaults.camera ];
  8130. }
  8131. if ( result.fogs && data.defaults.fog ) {
  8132. result.scene.fog = result.fogs[ data.defaults.fog ];
  8133. }
  8134. // synchronous callback
  8135. scope.callbackSync( result );
  8136. // just in case there are no async elements
  8137. async_callback_gate();
  8138. }
  8139. }
  8140. /**
  8141. * @author mrdoob / http://mrdoob.com/
  8142. */
  8143. THREE.TextureLoader = function ( manager ) {
  8144. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  8145. };
  8146. THREE.TextureLoader.prototype = {
  8147. constructor: THREE.TextureLoader,
  8148. load: function ( url, onLoad, onProgress, onError ) {
  8149. var scope = this;
  8150. var loader = new THREE.ImageLoader( scope.manager );
  8151. loader.setCrossOrigin( this.crossOrigin );
  8152. loader.load( url, function ( image ) {
  8153. var texture = new THREE.Texture( image );
  8154. texture.needsUpdate = true;
  8155. if ( onLoad !== undefined ) {
  8156. onLoad( texture );
  8157. }
  8158. } );
  8159. },
  8160. setCrossOrigin: function ( value ) {
  8161. this.crossOrigin = value;
  8162. }
  8163. };
  8164. /**
  8165. * @author mrdoob / http://mrdoob.com/
  8166. * @author alteredq / http://alteredqualia.com/
  8167. */
  8168. THREE.Material = function () {
  8169. this.id = THREE.MaterialIdCount ++;
  8170. this.uuid = THREE.Math.generateUUID();
  8171. this.name = '';
  8172. this.side = THREE.FrontSide;
  8173. this.opacity = 1;
  8174. this.transparent = false;
  8175. this.blending = THREE.NormalBlending;
  8176. this.blendSrc = THREE.SrcAlphaFactor;
  8177. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  8178. this.blendEquation = THREE.AddEquation;
  8179. this.depthTest = true;
  8180. this.depthWrite = true;
  8181. this.polygonOffset = false;
  8182. this.polygonOffsetFactor = 0;
  8183. this.polygonOffsetUnits = 0;
  8184. this.alphaTest = 0;
  8185. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  8186. this.visible = true;
  8187. this.needsUpdate = true;
  8188. };
  8189. THREE.Material.prototype = {
  8190. constructor: THREE.Material,
  8191. setValues: function ( values ) {
  8192. if ( values === undefined ) return;
  8193. for ( var key in values ) {
  8194. var newValue = values[ key ];
  8195. if ( newValue === undefined ) {
  8196. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  8197. continue;
  8198. }
  8199. if ( key in this ) {
  8200. var currentValue = this[ key ];
  8201. if ( currentValue instanceof THREE.Color ) {
  8202. currentValue.set( newValue );
  8203. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  8204. currentValue.copy( newValue );
  8205. } else if ( key == 'overdraw') {
  8206. // ensure overdraw is backwards-compatable with legacy boolean type
  8207. this[ key ] = Number(newValue);
  8208. } else {
  8209. this[ key ] = newValue;
  8210. }
  8211. }
  8212. }
  8213. },
  8214. clone: function ( material ) {
  8215. if ( material === undefined ) material = new THREE.Material();
  8216. material.name = this.name;
  8217. material.side = this.side;
  8218. material.opacity = this.opacity;
  8219. material.transparent = this.transparent;
  8220. material.blending = this.blending;
  8221. material.blendSrc = this.blendSrc;
  8222. material.blendDst = this.blendDst;
  8223. material.blendEquation = this.blendEquation;
  8224. material.depthTest = this.depthTest;
  8225. material.depthWrite = this.depthWrite;
  8226. material.polygonOffset = this.polygonOffset;
  8227. material.polygonOffsetFactor = this.polygonOffsetFactor;
  8228. material.polygonOffsetUnits = this.polygonOffsetUnits;
  8229. material.alphaTest = this.alphaTest;
  8230. material.overdraw = this.overdraw;
  8231. material.visible = this.visible;
  8232. return material;
  8233. },
  8234. dispose: function () {
  8235. this.dispatchEvent( { type: 'dispose' } );
  8236. }
  8237. };
  8238. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  8239. THREE.MaterialIdCount = 0;
  8240. /**
  8241. * @author mrdoob / http://mrdoob.com/
  8242. * @author alteredq / http://alteredqualia.com/
  8243. *
  8244. * parameters = {
  8245. * color: <hex>,
  8246. * opacity: <float>,
  8247. *
  8248. * blending: THREE.NormalBlending,
  8249. * depthTest: <bool>,
  8250. * depthWrite: <bool>,
  8251. *
  8252. * linewidth: <float>,
  8253. * linecap: "round",
  8254. * linejoin: "round",
  8255. *
  8256. * vertexColors: <bool>
  8257. *
  8258. * fog: <bool>
  8259. * }
  8260. */
  8261. THREE.LineBasicMaterial = function ( parameters ) {
  8262. THREE.Material.call( this );
  8263. this.color = new THREE.Color( 0xffffff );
  8264. this.linewidth = 1;
  8265. this.linecap = 'round';
  8266. this.linejoin = 'round';
  8267. this.vertexColors = false;
  8268. this.fog = true;
  8269. this.setValues( parameters );
  8270. };
  8271. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8272. THREE.LineBasicMaterial.prototype.clone = function () {
  8273. var material = new THREE.LineBasicMaterial();
  8274. THREE.Material.prototype.clone.call( this, material );
  8275. material.color.copy( this.color );
  8276. material.linewidth = this.linewidth;
  8277. material.linecap = this.linecap;
  8278. material.linejoin = this.linejoin;
  8279. material.vertexColors = this.vertexColors;
  8280. material.fog = this.fog;
  8281. return material;
  8282. };
  8283. /**
  8284. * @author alteredq / http://alteredqualia.com/
  8285. *
  8286. * parameters = {
  8287. * color: <hex>,
  8288. * opacity: <float>,
  8289. *
  8290. * blending: THREE.NormalBlending,
  8291. * depthTest: <bool>,
  8292. * depthWrite: <bool>,
  8293. *
  8294. * linewidth: <float>,
  8295. *
  8296. * scale: <float>,
  8297. * dashSize: <float>,
  8298. * gapSize: <float>,
  8299. *
  8300. * vertexColors: <bool>
  8301. *
  8302. * fog: <bool>
  8303. * }
  8304. */
  8305. THREE.LineDashedMaterial = function ( parameters ) {
  8306. THREE.Material.call( this );
  8307. this.color = new THREE.Color( 0xffffff );
  8308. this.linewidth = 1;
  8309. this.scale = 1;
  8310. this.dashSize = 3;
  8311. this.gapSize = 1;
  8312. this.vertexColors = false;
  8313. this.fog = true;
  8314. this.setValues( parameters );
  8315. };
  8316. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  8317. THREE.LineDashedMaterial.prototype.clone = function () {
  8318. var material = new THREE.LineDashedMaterial();
  8319. THREE.Material.prototype.clone.call( this, material );
  8320. material.color.copy( this.color );
  8321. material.linewidth = this.linewidth;
  8322. material.scale = this.scale;
  8323. material.dashSize = this.dashSize;
  8324. material.gapSize = this.gapSize;
  8325. material.vertexColors = this.vertexColors;
  8326. material.fog = this.fog;
  8327. return material;
  8328. };
  8329. /**
  8330. * @author mrdoob / http://mrdoob.com/
  8331. * @author alteredq / http://alteredqualia.com/
  8332. *
  8333. * parameters = {
  8334. * color: <hex>,
  8335. * opacity: <float>,
  8336. * map: new THREE.Texture( <Image> ),
  8337. *
  8338. * lightMap: new THREE.Texture( <Image> ),
  8339. *
  8340. * specularMap: new THREE.Texture( <Image> ),
  8341. *
  8342. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8343. * combine: THREE.Multiply,
  8344. * reflectivity: <float>,
  8345. * refractionRatio: <float>,
  8346. *
  8347. * shading: THREE.SmoothShading,
  8348. * blending: THREE.NormalBlending,
  8349. * depthTest: <bool>,
  8350. * depthWrite: <bool>,
  8351. *
  8352. * wireframe: <boolean>,
  8353. * wireframeLinewidth: <float>,
  8354. *
  8355. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8356. *
  8357. * skinning: <bool>,
  8358. * morphTargets: <bool>,
  8359. *
  8360. * fog: <bool>
  8361. * }
  8362. */
  8363. THREE.MeshBasicMaterial = function ( parameters ) {
  8364. THREE.Material.call( this );
  8365. this.color = new THREE.Color( 0xffffff ); // emissive
  8366. this.map = null;
  8367. this.lightMap = null;
  8368. this.specularMap = null;
  8369. this.envMap = null;
  8370. this.combine = THREE.MultiplyOperation;
  8371. this.reflectivity = 1;
  8372. this.refractionRatio = 0.98;
  8373. this.fog = true;
  8374. this.shading = THREE.SmoothShading;
  8375. this.wireframe = false;
  8376. this.wireframeLinewidth = 1;
  8377. this.wireframeLinecap = 'round';
  8378. this.wireframeLinejoin = 'round';
  8379. this.vertexColors = THREE.NoColors;
  8380. this.skinning = false;
  8381. this.morphTargets = false;
  8382. this.setValues( parameters );
  8383. };
  8384. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8385. THREE.MeshBasicMaterial.prototype.clone = function () {
  8386. var material = new THREE.MeshBasicMaterial();
  8387. THREE.Material.prototype.clone.call( this, material );
  8388. material.color.copy( this.color );
  8389. material.map = this.map;
  8390. material.lightMap = this.lightMap;
  8391. material.specularMap = this.specularMap;
  8392. material.envMap = this.envMap;
  8393. material.combine = this.combine;
  8394. material.reflectivity = this.reflectivity;
  8395. material.refractionRatio = this.refractionRatio;
  8396. material.fog = this.fog;
  8397. material.shading = this.shading;
  8398. material.wireframe = this.wireframe;
  8399. material.wireframeLinewidth = this.wireframeLinewidth;
  8400. material.wireframeLinecap = this.wireframeLinecap;
  8401. material.wireframeLinejoin = this.wireframeLinejoin;
  8402. material.vertexColors = this.vertexColors;
  8403. material.skinning = this.skinning;
  8404. material.morphTargets = this.morphTargets;
  8405. return material;
  8406. };
  8407. /**
  8408. * @author mrdoob / http://mrdoob.com/
  8409. * @author alteredq / http://alteredqualia.com/
  8410. *
  8411. * parameters = {
  8412. * color: <hex>,
  8413. * ambient: <hex>,
  8414. * emissive: <hex>,
  8415. * opacity: <float>,
  8416. *
  8417. * map: new THREE.Texture( <Image> ),
  8418. *
  8419. * lightMap: new THREE.Texture( <Image> ),
  8420. *
  8421. * specularMap: new THREE.Texture( <Image> ),
  8422. *
  8423. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8424. * combine: THREE.Multiply,
  8425. * reflectivity: <float>,
  8426. * refractionRatio: <float>,
  8427. *
  8428. * shading: THREE.SmoothShading,
  8429. * blending: THREE.NormalBlending,
  8430. * depthTest: <bool>,
  8431. * depthWrite: <bool>,
  8432. *
  8433. * wireframe: <boolean>,
  8434. * wireframeLinewidth: <float>,
  8435. *
  8436. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8437. *
  8438. * skinning: <bool>,
  8439. * morphTargets: <bool>,
  8440. * morphNormals: <bool>,
  8441. *
  8442. * fog: <bool>
  8443. * }
  8444. */
  8445. THREE.MeshLambertMaterial = function ( parameters ) {
  8446. THREE.Material.call( this );
  8447. this.color = new THREE.Color( 0xffffff ); // diffuse
  8448. this.ambient = new THREE.Color( 0xffffff );
  8449. this.emissive = new THREE.Color( 0x000000 );
  8450. this.wrapAround = false;
  8451. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8452. this.map = null;
  8453. this.lightMap = null;
  8454. this.specularMap = null;
  8455. this.envMap = null;
  8456. this.combine = THREE.MultiplyOperation;
  8457. this.reflectivity = 1;
  8458. this.refractionRatio = 0.98;
  8459. this.fog = true;
  8460. this.shading = THREE.SmoothShading;
  8461. this.wireframe = false;
  8462. this.wireframeLinewidth = 1;
  8463. this.wireframeLinecap = 'round';
  8464. this.wireframeLinejoin = 'round';
  8465. this.vertexColors = THREE.NoColors;
  8466. this.skinning = false;
  8467. this.morphTargets = false;
  8468. this.morphNormals = false;
  8469. this.setValues( parameters );
  8470. };
  8471. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8472. THREE.MeshLambertMaterial.prototype.clone = function () {
  8473. var material = new THREE.MeshLambertMaterial();
  8474. THREE.Material.prototype.clone.call( this, material );
  8475. material.color.copy( this.color );
  8476. material.ambient.copy( this.ambient );
  8477. material.emissive.copy( this.emissive );
  8478. material.wrapAround = this.wrapAround;
  8479. material.wrapRGB.copy( this.wrapRGB );
  8480. material.map = this.map;
  8481. material.lightMap = this.lightMap;
  8482. material.specularMap = this.specularMap;
  8483. material.envMap = this.envMap;
  8484. material.combine = this.combine;
  8485. material.reflectivity = this.reflectivity;
  8486. material.refractionRatio = this.refractionRatio;
  8487. material.fog = this.fog;
  8488. material.shading = this.shading;
  8489. material.wireframe = this.wireframe;
  8490. material.wireframeLinewidth = this.wireframeLinewidth;
  8491. material.wireframeLinecap = this.wireframeLinecap;
  8492. material.wireframeLinejoin = this.wireframeLinejoin;
  8493. material.vertexColors = this.vertexColors;
  8494. material.skinning = this.skinning;
  8495. material.morphTargets = this.morphTargets;
  8496. material.morphNormals = this.morphNormals;
  8497. return material;
  8498. };
  8499. /**
  8500. * @author mrdoob / http://mrdoob.com/
  8501. * @author alteredq / http://alteredqualia.com/
  8502. *
  8503. * parameters = {
  8504. * color: <hex>,
  8505. * ambient: <hex>,
  8506. * emissive: <hex>,
  8507. * specular: <hex>,
  8508. * shininess: <float>,
  8509. * opacity: <float>,
  8510. *
  8511. * map: new THREE.Texture( <Image> ),
  8512. *
  8513. * lightMap: new THREE.Texture( <Image> ),
  8514. *
  8515. * bumpMap: new THREE.Texture( <Image> ),
  8516. * bumpScale: <float>,
  8517. *
  8518. * normalMap: new THREE.Texture( <Image> ),
  8519. * normalScale: <Vector2>,
  8520. *
  8521. * specularMap: new THREE.Texture( <Image> ),
  8522. *
  8523. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8524. * combine: THREE.Multiply,
  8525. * reflectivity: <float>,
  8526. * refractionRatio: <float>,
  8527. *
  8528. * shading: THREE.SmoothShading,
  8529. * blending: THREE.NormalBlending,
  8530. * depthTest: <bool>,
  8531. * depthWrite: <bool>,
  8532. *
  8533. * wireframe: <boolean>,
  8534. * wireframeLinewidth: <float>,
  8535. *
  8536. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8537. *
  8538. * skinning: <bool>,
  8539. * morphTargets: <bool>,
  8540. * morphNormals: <bool>,
  8541. *
  8542. * fog: <bool>
  8543. * }
  8544. */
  8545. THREE.MeshPhongMaterial = function ( parameters ) {
  8546. THREE.Material.call( this );
  8547. this.color = new THREE.Color( 0xffffff ); // diffuse
  8548. this.ambient = new THREE.Color( 0xffffff );
  8549. this.emissive = new THREE.Color( 0x000000 );
  8550. this.specular = new THREE.Color( 0x111111 );
  8551. this.shininess = 30;
  8552. this.metal = false;
  8553. this.wrapAround = false;
  8554. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8555. this.map = null;
  8556. this.lightMap = null;
  8557. this.bumpMap = null;
  8558. this.bumpScale = 1;
  8559. this.normalMap = null;
  8560. this.normalScale = new THREE.Vector2( 1, 1 );
  8561. this.specularMap = null;
  8562. this.envMap = null;
  8563. this.combine = THREE.MultiplyOperation;
  8564. this.reflectivity = 1;
  8565. this.refractionRatio = 0.98;
  8566. this.fog = true;
  8567. this.shading = THREE.SmoothShading;
  8568. this.wireframe = false;
  8569. this.wireframeLinewidth = 1;
  8570. this.wireframeLinecap = 'round';
  8571. this.wireframeLinejoin = 'round';
  8572. this.vertexColors = THREE.NoColors;
  8573. this.skinning = false;
  8574. this.morphTargets = false;
  8575. this.morphNormals = false;
  8576. this.setValues( parameters );
  8577. };
  8578. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8579. THREE.MeshPhongMaterial.prototype.clone = function () {
  8580. var material = new THREE.MeshPhongMaterial();
  8581. THREE.Material.prototype.clone.call( this, material );
  8582. material.color.copy( this.color );
  8583. material.ambient.copy( this.ambient );
  8584. material.emissive.copy( this.emissive );
  8585. material.specular.copy( this.specular );
  8586. material.shininess = this.shininess;
  8587. material.metal = this.metal;
  8588. material.wrapAround = this.wrapAround;
  8589. material.wrapRGB.copy( this.wrapRGB );
  8590. material.map = this.map;
  8591. material.lightMap = this.lightMap;
  8592. material.bumpMap = this.bumpMap;
  8593. material.bumpScale = this.bumpScale;
  8594. material.normalMap = this.normalMap;
  8595. material.normalScale.copy( this.normalScale );
  8596. material.specularMap = this.specularMap;
  8597. material.envMap = this.envMap;
  8598. material.combine = this.combine;
  8599. material.reflectivity = this.reflectivity;
  8600. material.refractionRatio = this.refractionRatio;
  8601. material.fog = this.fog;
  8602. material.shading = this.shading;
  8603. material.wireframe = this.wireframe;
  8604. material.wireframeLinewidth = this.wireframeLinewidth;
  8605. material.wireframeLinecap = this.wireframeLinecap;
  8606. material.wireframeLinejoin = this.wireframeLinejoin;
  8607. material.vertexColors = this.vertexColors;
  8608. material.skinning = this.skinning;
  8609. material.morphTargets = this.morphTargets;
  8610. material.morphNormals = this.morphNormals;
  8611. return material;
  8612. };
  8613. /**
  8614. * @author mrdoob / http://mrdoob.com/
  8615. * @author alteredq / http://alteredqualia.com/
  8616. *
  8617. * parameters = {
  8618. * opacity: <float>,
  8619. *
  8620. * blending: THREE.NormalBlending,
  8621. * depthTest: <bool>,
  8622. * depthWrite: <bool>,
  8623. *
  8624. * wireframe: <boolean>,
  8625. * wireframeLinewidth: <float>
  8626. * }
  8627. */
  8628. THREE.MeshDepthMaterial = function ( parameters ) {
  8629. THREE.Material.call( this );
  8630. this.wireframe = false;
  8631. this.wireframeLinewidth = 1;
  8632. this.setValues( parameters );
  8633. };
  8634. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8635. THREE.MeshDepthMaterial.prototype.clone = function () {
  8636. var material = new THREE.MeshDepthMaterial();
  8637. THREE.Material.prototype.clone.call( this, material );
  8638. material.wireframe = this.wireframe;
  8639. material.wireframeLinewidth = this.wireframeLinewidth;
  8640. return material;
  8641. };
  8642. /**
  8643. * @author mrdoob / http://mrdoob.com/
  8644. *
  8645. * parameters = {
  8646. * opacity: <float>,
  8647. *
  8648. * shading: THREE.FlatShading,
  8649. * blending: THREE.NormalBlending,
  8650. * depthTest: <bool>,
  8651. * depthWrite: <bool>,
  8652. *
  8653. * wireframe: <boolean>,
  8654. * wireframeLinewidth: <float>
  8655. * }
  8656. */
  8657. THREE.MeshNormalMaterial = function ( parameters ) {
  8658. THREE.Material.call( this, parameters );
  8659. this.shading = THREE.FlatShading;
  8660. this.wireframe = false;
  8661. this.wireframeLinewidth = 1;
  8662. this.morphTargets = false;
  8663. this.setValues( parameters );
  8664. };
  8665. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8666. THREE.MeshNormalMaterial.prototype.clone = function () {
  8667. var material = new THREE.MeshNormalMaterial();
  8668. THREE.Material.prototype.clone.call( this, material );
  8669. material.shading = this.shading;
  8670. material.wireframe = this.wireframe;
  8671. material.wireframeLinewidth = this.wireframeLinewidth;
  8672. return material;
  8673. };
  8674. /**
  8675. * @author mrdoob / http://mrdoob.com/
  8676. */
  8677. THREE.MeshFaceMaterial = function ( materials ) {
  8678. this.materials = materials instanceof Array ? materials : [];
  8679. };
  8680. THREE.MeshFaceMaterial.prototype.clone = function () {
  8681. var material = new THREE.MeshFaceMaterial();
  8682. for ( var i = 0; i < this.materials.length; i ++ ) {
  8683. material.materials.push( this.materials[ i ].clone() );
  8684. }
  8685. return material;
  8686. };
  8687. /**
  8688. * @author mrdoob / http://mrdoob.com/
  8689. * @author alteredq / http://alteredqualia.com/
  8690. *
  8691. * parameters = {
  8692. * color: <hex>,
  8693. * opacity: <float>,
  8694. * map: new THREE.Texture( <Image> ),
  8695. *
  8696. * size: <float>,
  8697. *
  8698. * blending: THREE.NormalBlending,
  8699. * depthTest: <bool>,
  8700. * depthWrite: <bool>,
  8701. *
  8702. * vertexColors: <bool>,
  8703. *
  8704. * fog: <bool>
  8705. * }
  8706. */
  8707. THREE.ParticleSystemMaterial = function ( parameters ) {
  8708. THREE.Material.call( this );
  8709. this.color = new THREE.Color( 0xffffff );
  8710. this.map = null;
  8711. this.size = 1;
  8712. this.sizeAttenuation = true;
  8713. this.vertexColors = false;
  8714. this.fog = true;
  8715. this.setValues( parameters );
  8716. };
  8717. THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype );
  8718. THREE.ParticleSystemMaterial.prototype.clone = function () {
  8719. var material = new THREE.ParticleSystemMaterial();
  8720. THREE.Material.prototype.clone.call( this, material );
  8721. material.color.copy( this.color );
  8722. material.map = this.map;
  8723. material.size = this.size;
  8724. material.sizeAttenuation = this.sizeAttenuation;
  8725. material.vertexColors = this.vertexColors;
  8726. material.fog = this.fog;
  8727. return material;
  8728. };
  8729. // backwards compatibility
  8730. THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial;
  8731. /**
  8732. * @author alteredq / http://alteredqualia.com/
  8733. *
  8734. * parameters = {
  8735. * fragmentShader: <string>,
  8736. * vertexShader: <string>,
  8737. *
  8738. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8739. *
  8740. * defines: { "label" : "value" },
  8741. *
  8742. * shading: THREE.SmoothShading,
  8743. * blending: THREE.NormalBlending,
  8744. * depthTest: <bool>,
  8745. * depthWrite: <bool>,
  8746. *
  8747. * wireframe: <boolean>,
  8748. * wireframeLinewidth: <float>,
  8749. *
  8750. * lights: <bool>,
  8751. *
  8752. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8753. *
  8754. * skinning: <bool>,
  8755. * morphTargets: <bool>,
  8756. * morphNormals: <bool>,
  8757. *
  8758. * fog: <bool>
  8759. * }
  8760. */
  8761. THREE.ShaderMaterial = function ( parameters ) {
  8762. THREE.Material.call( this );
  8763. this.fragmentShader = "void main() {}";
  8764. this.vertexShader = "void main() {}";
  8765. this.uniforms = {};
  8766. this.defines = {};
  8767. this.attributes = null;
  8768. this.shading = THREE.SmoothShading;
  8769. this.linewidth = 1;
  8770. this.wireframe = false;
  8771. this.wireframeLinewidth = 1;
  8772. this.fog = false; // set to use scene fog
  8773. this.lights = false; // set to use scene lights
  8774. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8775. this.skinning = false; // set to use skinning attribute streams
  8776. this.morphTargets = false; // set to use morph targets
  8777. this.morphNormals = false; // set to use morph normals
  8778. // When rendered geometry doesn't include these attributes but the material does,
  8779. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8780. this.defaultAttributeValues = {
  8781. "color" : [ 1, 1, 1],
  8782. "uv" : [ 0, 0 ],
  8783. "uv2" : [ 0, 0 ]
  8784. };
  8785. // By default, bind position to attribute index 0. In WebGL, attribute 0
  8786. // should always be used to avoid potentially expensive emulation.
  8787. this.index0AttributeName = "position";
  8788. this.setValues( parameters );
  8789. };
  8790. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8791. THREE.ShaderMaterial.prototype.clone = function () {
  8792. var material = new THREE.ShaderMaterial();
  8793. THREE.Material.prototype.clone.call( this, material );
  8794. material.fragmentShader = this.fragmentShader;
  8795. material.vertexShader = this.vertexShader;
  8796. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8797. material.attributes = this.attributes;
  8798. material.defines = this.defines;
  8799. material.shading = this.shading;
  8800. material.wireframe = this.wireframe;
  8801. material.wireframeLinewidth = this.wireframeLinewidth;
  8802. material.fog = this.fog;
  8803. material.lights = this.lights;
  8804. material.vertexColors = this.vertexColors;
  8805. material.skinning = this.skinning;
  8806. material.morphTargets = this.morphTargets;
  8807. material.morphNormals = this.morphNormals;
  8808. return material;
  8809. };
  8810. /**
  8811. * @author alteredq / http://alteredqualia.com/
  8812. *
  8813. * parameters = {
  8814. * color: <hex>,
  8815. * opacity: <float>,
  8816. * map: new THREE.Texture( <Image> ),
  8817. *
  8818. * blending: THREE.NormalBlending,
  8819. * depthTest: <bool>,
  8820. * depthWrite: <bool>,
  8821. *
  8822. * uvOffset: new THREE.Vector2(),
  8823. * uvScale: new THREE.Vector2(),
  8824. *
  8825. * fog: <bool>
  8826. * }
  8827. */
  8828. THREE.SpriteMaterial = function ( parameters ) {
  8829. THREE.Material.call( this );
  8830. // defaults
  8831. this.color = new THREE.Color( 0xffffff );
  8832. this.map = null;
  8833. this.rotation = 0;
  8834. this.fog = false;
  8835. // set parameters
  8836. this.setValues( parameters );
  8837. };
  8838. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8839. THREE.SpriteMaterial.prototype.clone = function () {
  8840. var material = new THREE.SpriteMaterial();
  8841. THREE.Material.prototype.clone.call( this, material );
  8842. material.color.copy( this.color );
  8843. material.map = this.map;
  8844. material.rotation = this.rotation;
  8845. material.fog = this.fog;
  8846. return material;
  8847. };
  8848. /**
  8849. * @author mrdoob / http://mrdoob.com/
  8850. *
  8851. * parameters = {
  8852. * color: <hex>,
  8853. * program: <function>,
  8854. * opacity: <float>,
  8855. * blending: THREE.NormalBlending
  8856. * }
  8857. */
  8858. THREE.SpriteCanvasMaterial = function ( parameters ) {
  8859. THREE.Material.call( this );
  8860. this.color = new THREE.Color( 0xffffff );
  8861. this.program = function ( context, color ) {};
  8862. this.setValues( parameters );
  8863. };
  8864. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8865. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  8866. var material = new THREE.SpriteCanvasMaterial();
  8867. THREE.Material.prototype.clone.call( this, material );
  8868. material.color.copy( this.color );
  8869. material.program = this.program;
  8870. return material;
  8871. };
  8872. // backwards compatibility
  8873. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  8874. /**
  8875. * @author mrdoob / http://mrdoob.com/
  8876. * @author alteredq / http://alteredqualia.com/
  8877. * @author szimek / https://github.com/szimek/
  8878. */
  8879. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8880. this.id = THREE.TextureIdCount ++;
  8881. this.uuid = THREE.Math.generateUUID();
  8882. this.name = '';
  8883. this.image = image;
  8884. this.mipmaps = [];
  8885. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8886. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8887. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8888. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8889. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8890. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8891. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8892. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8893. this.offset = new THREE.Vector2( 0, 0 );
  8894. this.repeat = new THREE.Vector2( 1, 1 );
  8895. this.generateMipmaps = true;
  8896. this.premultiplyAlpha = false;
  8897. this.flipY = true;
  8898. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8899. this._needsUpdate = false;
  8900. this.onUpdate = null;
  8901. };
  8902. THREE.Texture.prototype = {
  8903. constructor: THREE.Texture,
  8904. get needsUpdate () {
  8905. return this._needsUpdate;
  8906. },
  8907. set needsUpdate ( value ) {
  8908. if ( value === true ) this.update();
  8909. this._needsUpdate = value;
  8910. },
  8911. clone: function ( texture ) {
  8912. if ( texture === undefined ) texture = new THREE.Texture();
  8913. texture.image = this.image;
  8914. texture.mipmaps = this.mipmaps.slice(0);
  8915. texture.mapping = this.mapping;
  8916. texture.wrapS = this.wrapS;
  8917. texture.wrapT = this.wrapT;
  8918. texture.magFilter = this.magFilter;
  8919. texture.minFilter = this.minFilter;
  8920. texture.anisotropy = this.anisotropy;
  8921. texture.format = this.format;
  8922. texture.type = this.type;
  8923. texture.offset.copy( this.offset );
  8924. texture.repeat.copy( this.repeat );
  8925. texture.generateMipmaps = this.generateMipmaps;
  8926. texture.premultiplyAlpha = this.premultiplyAlpha;
  8927. texture.flipY = this.flipY;
  8928. texture.unpackAlignment = this.unpackAlignment;
  8929. return texture;
  8930. },
  8931. update: function () {
  8932. this.dispatchEvent( { type: 'update' } );
  8933. },
  8934. dispose: function () {
  8935. this.dispatchEvent( { type: 'dispose' } );
  8936. }
  8937. };
  8938. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8939. THREE.TextureIdCount = 0;
  8940. /**
  8941. * @author alteredq / http://alteredqualia.com/
  8942. */
  8943. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8944. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8945. this.image = { width: width, height: height };
  8946. this.mipmaps = mipmaps;
  8947. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8948. };
  8949. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8950. THREE.CompressedTexture.prototype.clone = function () {
  8951. var texture = new THREE.CompressedTexture();
  8952. THREE.Texture.prototype.clone.call( this, texture );
  8953. return texture;
  8954. };
  8955. /**
  8956. * @author alteredq / http://alteredqualia.com/
  8957. */
  8958. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8959. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8960. this.image = { data: data, width: width, height: height };
  8961. };
  8962. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8963. THREE.DataTexture.prototype.clone = function () {
  8964. var texture = new THREE.DataTexture();
  8965. THREE.Texture.prototype.clone.call( this, texture );
  8966. return texture;
  8967. };
  8968. /**
  8969. * @author alteredq / http://alteredqualia.com/
  8970. */
  8971. THREE.ParticleSystem = function ( geometry, material ) {
  8972. THREE.Object3D.call( this );
  8973. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8974. this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } );
  8975. this.sortParticles = false;
  8976. this.frustumCulled = false;
  8977. };
  8978. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  8979. THREE.ParticleSystem.prototype.clone = function ( object ) {
  8980. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  8981. object.sortParticles = this.sortParticles;
  8982. THREE.Object3D.prototype.clone.call( this, object );
  8983. return object;
  8984. };
  8985. /**
  8986. * @author mrdoob / http://mrdoob.com/
  8987. */
  8988. THREE.Line = function ( geometry, material, type ) {
  8989. THREE.Object3D.call( this );
  8990. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8991. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8992. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8993. };
  8994. THREE.LineStrip = 0;
  8995. THREE.LinePieces = 1;
  8996. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8997. THREE.Line.prototype.clone = function ( object ) {
  8998. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8999. THREE.Object3D.prototype.clone.call( this, object );
  9000. return object;
  9001. };
  9002. /**
  9003. * @author mrdoob / http://mrdoob.com/
  9004. * @author alteredq / http://alteredqualia.com/
  9005. * @author mikael emtinger / http://gomo.se/
  9006. * @author jonobr1 / http://jonobr1.com/
  9007. */
  9008. THREE.Mesh = function ( geometry, material ) {
  9009. THREE.Object3D.call( this );
  9010. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9011. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9012. this.updateMorphTargets();
  9013. };
  9014. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  9015. THREE.Mesh.prototype.updateMorphTargets = function () {
  9016. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  9017. this.morphTargetBase = -1;
  9018. this.morphTargetForcedOrder = [];
  9019. this.morphTargetInfluences = [];
  9020. this.morphTargetDictionary = {};
  9021. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  9022. this.morphTargetInfluences.push( 0 );
  9023. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  9024. }
  9025. }
  9026. };
  9027. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  9028. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  9029. return this.morphTargetDictionary[ name ];
  9030. }
  9031. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  9032. return 0;
  9033. };
  9034. THREE.Mesh.prototype.clone = function ( object ) {
  9035. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  9036. THREE.Object3D.prototype.clone.call( this, object );
  9037. return object;
  9038. };
  9039. /**
  9040. * @author mikael emtinger / http://gomo.se/
  9041. * @author alteredq / http://alteredqualia.com/
  9042. */
  9043. THREE.Bone = function( belongsToSkin ) {
  9044. THREE.Object3D.call( this );
  9045. this.skin = belongsToSkin;
  9046. this.skinMatrix = new THREE.Matrix4();
  9047. };
  9048. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  9049. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  9050. // update local
  9051. if ( this.matrixAutoUpdate ) {
  9052. forceUpdate |= this.updateMatrix();
  9053. }
  9054. // update skin matrix
  9055. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  9056. if( parentSkinMatrix ) {
  9057. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  9058. } else {
  9059. this.skinMatrix.copy( this.matrix );
  9060. }
  9061. this.matrixWorldNeedsUpdate = false;
  9062. forceUpdate = true;
  9063. }
  9064. // update children
  9065. var child, i, l = this.children.length;
  9066. for ( i = 0; i < l; i ++ ) {
  9067. this.children[ i ].update( this.skinMatrix, forceUpdate );
  9068. }
  9069. };
  9070. /**
  9071. * @author mikael emtinger / http://gomo.se/
  9072. * @author alteredq / http://alteredqualia.com/
  9073. */
  9074. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  9075. THREE.Mesh.call( this, geometry, material );
  9076. //
  9077. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  9078. // init bones
  9079. this.identityMatrix = new THREE.Matrix4();
  9080. this.bones = [];
  9081. this.boneMatrices = [];
  9082. var b, bone, gbone, p, q, s;
  9083. if ( this.geometry && this.geometry.bones !== undefined ) {
  9084. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  9085. gbone = this.geometry.bones[ b ];
  9086. p = gbone.pos;
  9087. q = gbone.rotq;
  9088. s = gbone.scl;
  9089. bone = this.addBone();
  9090. bone.name = gbone.name;
  9091. bone.position.set( p[0], p[1], p[2] );
  9092. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  9093. if ( s !== undefined ) {
  9094. bone.scale.set( s[0], s[1], s[2] );
  9095. } else {
  9096. bone.scale.set( 1, 1, 1 );
  9097. }
  9098. }
  9099. for ( b = 0; b < this.bones.length; b ++ ) {
  9100. gbone = this.geometry.bones[ b ];
  9101. bone = this.bones[ b ];
  9102. if ( gbone.parent === -1 ) {
  9103. this.add( bone );
  9104. } else {
  9105. this.bones[ gbone.parent ].add( bone );
  9106. }
  9107. }
  9108. //
  9109. var nBones = this.bones.length;
  9110. if ( this.useVertexTexture ) {
  9111. // layout (1 matrix = 4 pixels)
  9112. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9113. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  9114. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  9115. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  9116. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  9117. var size;
  9118. if ( nBones > 256 )
  9119. size = 64;
  9120. else if ( nBones > 64 )
  9121. size = 32;
  9122. else if ( nBones > 16 )
  9123. size = 16;
  9124. else
  9125. size = 8;
  9126. this.boneTextureWidth = size;
  9127. this.boneTextureHeight = size;
  9128. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  9129. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  9130. this.boneTexture.minFilter = THREE.NearestFilter;
  9131. this.boneTexture.magFilter = THREE.NearestFilter;
  9132. this.boneTexture.generateMipmaps = false;
  9133. this.boneTexture.flipY = false;
  9134. } else {
  9135. this.boneMatrices = new Float32Array( 16 * nBones );
  9136. }
  9137. this.pose();
  9138. }
  9139. };
  9140. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  9141. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  9142. if ( bone === undefined ) {
  9143. bone = new THREE.Bone( this );
  9144. }
  9145. this.bones.push( bone );
  9146. return bone;
  9147. };
  9148. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  9149. var offsetMatrix = new THREE.Matrix4();
  9150. return function ( force ) {
  9151. this.matrixAutoUpdate && this.updateMatrix();
  9152. // update matrixWorld
  9153. if ( this.matrixWorldNeedsUpdate || force ) {
  9154. if ( this.parent ) {
  9155. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9156. } else {
  9157. this.matrixWorld.copy( this.matrix );
  9158. }
  9159. this.matrixWorldNeedsUpdate = false;
  9160. force = true;
  9161. }
  9162. // update children
  9163. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9164. var child = this.children[ i ];
  9165. if ( child instanceof THREE.Bone ) {
  9166. child.update( this.identityMatrix, false );
  9167. } else {
  9168. child.updateMatrixWorld( true );
  9169. }
  9170. }
  9171. // make a snapshot of the bones' rest position
  9172. if ( this.boneInverses == undefined ) {
  9173. this.boneInverses = [];
  9174. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9175. var inverse = new THREE.Matrix4();
  9176. inverse.getInverse( this.bones[ b ].skinMatrix );
  9177. this.boneInverses.push( inverse );
  9178. }
  9179. }
  9180. // flatten bone matrices to array
  9181. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9182. // compute the offset between the current and the original transform;
  9183. // TODO: we could get rid of this multiplication step if the skinMatrix
  9184. // was already representing the offset; however, this requires some
  9185. // major changes to the animation system
  9186. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  9187. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  9188. }
  9189. if ( this.useVertexTexture ) {
  9190. this.boneTexture.needsUpdate = true;
  9191. }
  9192. };
  9193. }();
  9194. THREE.SkinnedMesh.prototype.pose = function () {
  9195. this.updateMatrixWorld( true );
  9196. this.normalizeSkinWeights();
  9197. };
  9198. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  9199. if ( this.geometry instanceof THREE.Geometry ) {
  9200. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  9201. var sw = this.geometry.skinWeights[ i ];
  9202. var scale = 1.0 / sw.lengthManhattan();
  9203. if ( scale !== Infinity ) {
  9204. sw.multiplyScalar( scale );
  9205. } else {
  9206. sw.set( 1 ); // this will be normalized by the shader anyway
  9207. }
  9208. }
  9209. } else {
  9210. // skinning weights assumed to be normalized for THREE.BufferGeometry
  9211. }
  9212. };
  9213. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  9214. if ( object === undefined ) {
  9215. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  9216. }
  9217. THREE.Mesh.prototype.clone.call( this, object );
  9218. return object;
  9219. };
  9220. /**
  9221. * @author alteredq / http://alteredqualia.com/
  9222. */
  9223. THREE.MorphAnimMesh = function ( geometry, material ) {
  9224. THREE.Mesh.call( this, geometry, material );
  9225. // API
  9226. this.duration = 1000; // milliseconds
  9227. this.mirroredLoop = false;
  9228. this.time = 0;
  9229. // internals
  9230. this.lastKeyframe = 0;
  9231. this.currentKeyframe = 0;
  9232. this.direction = 1;
  9233. this.directionBackwards = false;
  9234. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  9235. };
  9236. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  9237. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  9238. this.startKeyframe = start;
  9239. this.endKeyframe = end;
  9240. this.length = this.endKeyframe - this.startKeyframe + 1;
  9241. };
  9242. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  9243. this.direction = 1;
  9244. this.directionBackwards = false;
  9245. };
  9246. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  9247. this.direction = -1;
  9248. this.directionBackwards = true;
  9249. };
  9250. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  9251. var geometry = this.geometry;
  9252. if ( ! geometry.animations ) geometry.animations = {};
  9253. var firstAnimation, animations = geometry.animations;
  9254. var pattern = /([a-z]+)(\d+)/;
  9255. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  9256. var morph = geometry.morphTargets[ i ];
  9257. var parts = morph.name.match( pattern );
  9258. if ( parts && parts.length > 1 ) {
  9259. var label = parts[ 1 ];
  9260. var num = parts[ 2 ];
  9261. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  9262. var animation = animations[ label ];
  9263. if ( i < animation.start ) animation.start = i;
  9264. if ( i > animation.end ) animation.end = i;
  9265. if ( ! firstAnimation ) firstAnimation = label;
  9266. }
  9267. }
  9268. geometry.firstAnimation = firstAnimation;
  9269. };
  9270. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  9271. if ( ! this.geometry.animations ) this.geometry.animations = {};
  9272. this.geometry.animations[ label ] = { start: start, end: end };
  9273. };
  9274. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  9275. var animation = this.geometry.animations[ label ];
  9276. if ( animation ) {
  9277. this.setFrameRange( animation.start, animation.end );
  9278. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  9279. this.time = 0;
  9280. } else {
  9281. console.warn( "animation[" + label + "] undefined" );
  9282. }
  9283. };
  9284. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  9285. var frameTime = this.duration / this.length;
  9286. this.time += this.direction * delta;
  9287. if ( this.mirroredLoop ) {
  9288. if ( this.time > this.duration || this.time < 0 ) {
  9289. this.direction *= -1;
  9290. if ( this.time > this.duration ) {
  9291. this.time = this.duration;
  9292. this.directionBackwards = true;
  9293. }
  9294. if ( this.time < 0 ) {
  9295. this.time = 0;
  9296. this.directionBackwards = false;
  9297. }
  9298. }
  9299. } else {
  9300. this.time = this.time % this.duration;
  9301. if ( this.time < 0 ) this.time += this.duration;
  9302. }
  9303. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  9304. if ( keyframe !== this.currentKeyframe ) {
  9305. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  9306. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  9307. this.morphTargetInfluences[ keyframe ] = 0;
  9308. this.lastKeyframe = this.currentKeyframe;
  9309. this.currentKeyframe = keyframe;
  9310. }
  9311. var mix = ( this.time % frameTime ) / frameTime;
  9312. if ( this.directionBackwards ) {
  9313. mix = 1 - mix;
  9314. }
  9315. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  9316. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  9317. };
  9318. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  9319. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  9320. object.duration = this.duration;
  9321. object.mirroredLoop = this.mirroredLoop;
  9322. object.time = this.time;
  9323. object.lastKeyframe = this.lastKeyframe;
  9324. object.currentKeyframe = this.currentKeyframe;
  9325. object.direction = this.direction;
  9326. object.directionBackwards = this.directionBackwards;
  9327. THREE.Mesh.prototype.clone.call( this, object );
  9328. return object;
  9329. };
  9330. /**
  9331. * @author mikael emtinger / http://gomo.se/
  9332. * @author alteredq / http://alteredqualia.com/
  9333. * @author mrdoob / http://mrdoob.com/
  9334. */
  9335. THREE.LOD = function () {
  9336. THREE.Object3D.call( this );
  9337. this.objects = [];
  9338. };
  9339. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  9340. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  9341. if ( distance === undefined ) distance = 0;
  9342. distance = Math.abs( distance );
  9343. for ( var l = 0; l < this.objects.length; l ++ ) {
  9344. if ( distance < this.objects[ l ].distance ) {
  9345. break;
  9346. }
  9347. }
  9348. this.objects.splice( l, 0, { distance: distance, object: object } );
  9349. this.add( object );
  9350. };
  9351. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  9352. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9353. if ( distance < this.objects[ i ].distance ) {
  9354. break;
  9355. }
  9356. }
  9357. return this.objects[ i - 1 ].object;
  9358. };
  9359. THREE.LOD.prototype.update = function () {
  9360. var v1 = new THREE.Vector3();
  9361. var v2 = new THREE.Vector3();
  9362. return function ( camera ) {
  9363. if ( this.objects.length > 1 ) {
  9364. v1.setFromMatrixPosition( camera.matrixWorld );
  9365. v2.setFromMatrixPosition( this.matrixWorld );
  9366. var distance = v1.distanceTo( v2 );
  9367. this.objects[ 0 ].object.visible = true;
  9368. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9369. if ( distance >= this.objects[ i ].distance ) {
  9370. this.objects[ i - 1 ].object.visible = false;
  9371. this.objects[ i ].object.visible = true;
  9372. } else {
  9373. break;
  9374. }
  9375. }
  9376. for( ; i < l; i ++ ) {
  9377. this.objects[ i ].object.visible = false;
  9378. }
  9379. }
  9380. };
  9381. }();
  9382. THREE.LOD.prototype.clone = function ( object ) {
  9383. if ( object === undefined ) object = new THREE.LOD();
  9384. THREE.Object3D.prototype.clone.call( this, object );
  9385. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  9386. var x = this.objects[i].object.clone();
  9387. x.visible = i === 0;
  9388. object.addLevel( x, this.objects[i].distance );
  9389. }
  9390. return object;
  9391. };
  9392. /**
  9393. * @author mikael emtinger / http://gomo.se/
  9394. * @author alteredq / http://alteredqualia.com/
  9395. */
  9396. THREE.Sprite = ( function () {
  9397. var geometry = new THREE.Geometry2( 3 );
  9398. geometry.vertices.set( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0 ] );
  9399. return function ( material ) {
  9400. THREE.Object3D.call( this );
  9401. this.geometry = geometry;
  9402. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  9403. };
  9404. } )();
  9405. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  9406. /*
  9407. * Custom update matrix
  9408. */
  9409. THREE.Sprite.prototype.updateMatrix = function () {
  9410. this.matrix.compose( this.position, this.quaternion, this.scale );
  9411. this.matrixWorldNeedsUpdate = true;
  9412. };
  9413. THREE.Sprite.prototype.clone = function ( object ) {
  9414. if ( object === undefined ) object = new THREE.Sprite( this.material );
  9415. THREE.Object3D.prototype.clone.call( this, object );
  9416. return object;
  9417. };
  9418. // Backwards compatibility
  9419. THREE.Particle = THREE.Sprite;
  9420. /**
  9421. * @author mrdoob / http://mrdoob.com/
  9422. */
  9423. THREE.Scene = function () {
  9424. THREE.Object3D.call( this );
  9425. this.fog = null;
  9426. this.overrideMaterial = null;
  9427. this.autoUpdate = true; // checked by the renderer
  9428. this.matrixAutoUpdate = false;
  9429. this.__lights = [];
  9430. this.__objectsAdded = [];
  9431. this.__objectsRemoved = [];
  9432. };
  9433. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9434. THREE.Scene.prototype.__addObject = function ( object ) {
  9435. if ( object instanceof THREE.Light ) {
  9436. if ( this.__lights.indexOf( object ) === - 1 ) {
  9437. this.__lights.push( object );
  9438. }
  9439. if ( object.target && object.target.parent === undefined ) {
  9440. this.add( object.target );
  9441. }
  9442. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  9443. this.__objectsAdded.push( object );
  9444. // check if previously removed
  9445. var i = this.__objectsRemoved.indexOf( object );
  9446. if ( i !== -1 ) {
  9447. this.__objectsRemoved.splice( i, 1 );
  9448. }
  9449. }
  9450. this.dispatchEvent( { type: 'objectAdded', object: object } );
  9451. object.dispatchEvent( { type: 'addedToScene', scene: this } );
  9452. for ( var c = 0; c < object.children.length; c ++ ) {
  9453. this.__addObject( object.children[ c ] );
  9454. }
  9455. };
  9456. THREE.Scene.prototype.__removeObject = function ( object ) {
  9457. if ( object instanceof THREE.Light ) {
  9458. var i = this.__lights.indexOf( object );
  9459. if ( i !== -1 ) {
  9460. this.__lights.splice( i, 1 );
  9461. }
  9462. if ( object.shadowCascadeArray ) {
  9463. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  9464. this.__removeObject( object.shadowCascadeArray[ x ] );
  9465. }
  9466. }
  9467. } else if ( !( object instanceof THREE.Camera ) ) {
  9468. this.__objectsRemoved.push( object );
  9469. // check if previously added
  9470. var i = this.__objectsAdded.indexOf( object );
  9471. if ( i !== -1 ) {
  9472. this.__objectsAdded.splice( i, 1 );
  9473. }
  9474. }
  9475. this.dispatchEvent( { type: 'objectRemoved', object: object } );
  9476. object.dispatchEvent( { type: 'removedFromScene', scene: this } );
  9477. for ( var c = 0; c < object.children.length; c ++ ) {
  9478. this.__removeObject( object.children[ c ] );
  9479. }
  9480. };
  9481. THREE.Scene.prototype.clone = function ( object ) {
  9482. if ( object === undefined ) object = new THREE.Scene();
  9483. THREE.Object3D.prototype.clone.call(this, object);
  9484. if ( this.fog !== null ) object.fog = this.fog.clone();
  9485. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9486. object.autoUpdate = this.autoUpdate;
  9487. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9488. return object;
  9489. };
  9490. /**
  9491. * @author mrdoob / http://mrdoob.com/
  9492. * @author alteredq / http://alteredqualia.com/
  9493. */
  9494. THREE.Fog = function ( color, near, far ) {
  9495. this.name = '';
  9496. this.color = new THREE.Color( color );
  9497. this.near = ( near !== undefined ) ? near : 1;
  9498. this.far = ( far !== undefined ) ? far : 1000;
  9499. };
  9500. THREE.Fog.prototype.clone = function () {
  9501. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9502. };
  9503. /**
  9504. * @author mrdoob / http://mrdoob.com/
  9505. * @author alteredq / http://alteredqualia.com/
  9506. */
  9507. THREE.FogExp2 = function ( color, density ) {
  9508. this.name = '';
  9509. this.color = new THREE.Color( color );
  9510. this.density = ( density !== undefined ) ? density : 0.00025;
  9511. };
  9512. THREE.FogExp2.prototype.clone = function () {
  9513. return new THREE.FogExp2( this.color.getHex(), this.density );
  9514. };
  9515. /**
  9516. * @author mrdoob / http://mrdoob.com/
  9517. */
  9518. THREE.CanvasRenderer = function ( parameters ) {
  9519. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9520. var smoothstep = THREE.Math.smoothstep;
  9521. parameters = parameters || {};
  9522. var _this = this,
  9523. _renderData, _elements, _lights,
  9524. _projector = new THREE.Projector(),
  9525. _canvas = parameters.canvas !== undefined
  9526. ? parameters.canvas
  9527. : document.createElement( 'canvas' ),
  9528. _canvasWidth = _canvas.width,
  9529. _canvasHeight = _canvas.height,
  9530. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9531. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9532. _context = _canvas.getContext( '2d', {
  9533. alpha: parameters.alpha === true
  9534. } ),
  9535. _clearColor = new THREE.Color( 0x000000 ),
  9536. _clearAlpha = 0,
  9537. _contextGlobalAlpha = 1,
  9538. _contextGlobalCompositeOperation = 0,
  9539. _contextStrokeStyle = null,
  9540. _contextFillStyle = null,
  9541. _contextLineWidth = null,
  9542. _contextLineCap = null,
  9543. _contextLineJoin = null,
  9544. _contextDashSize = null,
  9545. _contextGapSize = 0,
  9546. _camera,
  9547. _v1, _v2, _v3, _v4,
  9548. _v5 = new THREE.RenderableVertex(),
  9549. _v6 = new THREE.RenderableVertex(),
  9550. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9551. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9552. _color = new THREE.Color(),
  9553. _color1 = new THREE.Color(),
  9554. _color2 = new THREE.Color(),
  9555. _color3 = new THREE.Color(),
  9556. _color4 = new THREE.Color(),
  9557. _diffuseColor = new THREE.Color(),
  9558. _emissiveColor = new THREE.Color(),
  9559. _lightColor = new THREE.Color(),
  9560. _patterns = {},
  9561. _near, _far,
  9562. _image, _uvs,
  9563. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9564. _clipBox = new THREE.Box2(),
  9565. _clearBox = new THREE.Box2(),
  9566. _elemBox = new THREE.Box2(),
  9567. _ambientLight = new THREE.Color(),
  9568. _directionalLights = new THREE.Color(),
  9569. _pointLights = new THREE.Color(),
  9570. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9571. _normal = new THREE.Vector3(),
  9572. _normalViewMatrix = new THREE.Matrix3(),
  9573. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  9574. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  9575. _pixelMap = document.createElement( 'canvas' );
  9576. _pixelMap.width = _pixelMap.height = 2;
  9577. _pixelMapContext = _pixelMap.getContext( '2d' );
  9578. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  9579. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  9580. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  9581. _pixelMapData = _pixelMapImage.data;
  9582. _gradientMap = document.createElement( 'canvas' );
  9583. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  9584. _gradientMapContext = _gradientMap.getContext( '2d' );
  9585. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  9586. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  9587. _gradientMapQuality --; // Fix UVs
  9588. // dash+gap fallbacks for Firefox and everything else
  9589. if ( _context.setLineDash === undefined ) {
  9590. if ( _context.mozDash !== undefined ) {
  9591. _context.setLineDash = function ( values ) {
  9592. _context.mozDash = values[ 0 ] !== null ? values : null;
  9593. }
  9594. } else {
  9595. _context.setLineDash = function () {}
  9596. }
  9597. }
  9598. this.domElement = _canvas;
  9599. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9600. ? parameters.devicePixelRatio
  9601. : self.devicePixelRatio !== undefined
  9602. ? self.devicePixelRatio
  9603. : 1;
  9604. this.autoClear = true;
  9605. this.sortObjects = true;
  9606. this.sortElements = true;
  9607. this.info = {
  9608. render: {
  9609. vertices: 0,
  9610. faces: 0
  9611. }
  9612. }
  9613. // WebGLRenderer compatibility
  9614. this.supportsVertexTextures = function () {};
  9615. this.setFaceCulling = function () {};
  9616. this.setSize = function ( width, height, updateStyle ) {
  9617. _canvasWidth = width * this.devicePixelRatio;
  9618. _canvasHeight = height * this.devicePixelRatio;
  9619. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9620. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9621. _canvas.width = _canvasWidth;
  9622. _canvas.height = _canvasHeight;
  9623. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  9624. _canvas.style.width = width + 'px';
  9625. _canvas.style.height = height + 'px';
  9626. }
  9627. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ),
  9628. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9629. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9630. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9631. _contextGlobalAlpha = 1;
  9632. _contextGlobalCompositeOperation = 0;
  9633. _contextStrokeStyle = null;
  9634. _contextFillStyle = null;
  9635. _contextLineWidth = null;
  9636. _contextLineCap = null;
  9637. _contextLineJoin = null;
  9638. };
  9639. this.setClearColor = function ( color, alpha ) {
  9640. _clearColor.set( color );
  9641. _clearAlpha = alpha !== undefined ? alpha : 1;
  9642. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9643. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9644. };
  9645. this.setClearColorHex = function ( hex, alpha ) {
  9646. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9647. this.setClearColor( hex, alpha );
  9648. };
  9649. this.getMaxAnisotropy = function () {
  9650. return 0;
  9651. };
  9652. this.clear = function () {
  9653. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9654. if ( _clearBox.empty() === false ) {
  9655. _clearBox.intersect( _clipBox );
  9656. _clearBox.expandByScalar( 2 );
  9657. if ( _clearAlpha < 1 ) {
  9658. _context.clearRect(
  9659. _clearBox.min.x | 0,
  9660. _clearBox.min.y | 0,
  9661. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9662. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9663. );
  9664. }
  9665. if ( _clearAlpha > 0 ) {
  9666. setBlending( THREE.NormalBlending );
  9667. setOpacity( 1 );
  9668. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9669. _context.fillRect(
  9670. _clearBox.min.x | 0,
  9671. _clearBox.min.y | 0,
  9672. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9673. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9674. );
  9675. }
  9676. _clearBox.makeEmpty();
  9677. }
  9678. };
  9679. // compatibility
  9680. this.clearColor = function () {};
  9681. this.clearDepth = function () {};
  9682. this.clearStencil = function () {};
  9683. this.render = function ( scene, camera ) {
  9684. if ( camera instanceof THREE.Camera === false ) {
  9685. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9686. return;
  9687. }
  9688. if ( this.autoClear === true ) this.clear();
  9689. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9690. _this.info.render.vertices = 0;
  9691. _this.info.render.faces = 0;
  9692. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9693. _elements = _renderData.elements;
  9694. _lights = _renderData.lights;
  9695. _camera = camera;
  9696. _normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse );
  9697. /* DEBUG
  9698. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9699. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9700. */
  9701. calculateLights();
  9702. for ( var e = 0, el = _elements.length; e < el; e ++ ) {
  9703. var element = _elements[ e ];
  9704. var material = element.material;
  9705. if ( material === undefined || material.visible === false ) continue;
  9706. _elemBox.makeEmpty();
  9707. if ( element instanceof THREE.RenderableSprite ) {
  9708. _v1 = element;
  9709. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9710. renderSprite( _v1, element, material );
  9711. } else if ( element instanceof THREE.RenderableLine ) {
  9712. _v1 = element.v1; _v2 = element.v2;
  9713. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9714. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9715. _elemBox.setFromPoints( [
  9716. _v1.positionScreen,
  9717. _v2.positionScreen
  9718. ] );
  9719. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9720. renderLine( _v1, _v2, element, material );
  9721. }
  9722. } else if ( element instanceof THREE.RenderableFace ) {
  9723. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9724. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9725. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9726. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9727. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9728. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9729. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9730. if ( material.overdraw > 0 ) {
  9731. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9732. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9733. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9734. }
  9735. _elemBox.setFromPoints( [
  9736. _v1.positionScreen,
  9737. _v2.positionScreen,
  9738. _v3.positionScreen
  9739. ] );
  9740. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9741. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9742. }
  9743. }
  9744. /* DEBUG
  9745. setLineWidth( 1 );
  9746. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9747. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9748. */
  9749. _clearBox.union( _elemBox );
  9750. }
  9751. /* DEBUG
  9752. setLineWidth( 1 );
  9753. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9754. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9755. */
  9756. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9757. };
  9758. //
  9759. function calculateLights() {
  9760. _ambientLight.setRGB( 0, 0, 0 );
  9761. _directionalLights.setRGB( 0, 0, 0 );
  9762. _pointLights.setRGB( 0, 0, 0 );
  9763. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9764. var light = _lights[ l ];
  9765. var lightColor = light.color;
  9766. if ( light instanceof THREE.AmbientLight ) {
  9767. _ambientLight.add( lightColor );
  9768. } else if ( light instanceof THREE.DirectionalLight ) {
  9769. // for sprites
  9770. _directionalLights.add( lightColor );
  9771. } else if ( light instanceof THREE.PointLight ) {
  9772. // for sprites
  9773. _pointLights.add( lightColor );
  9774. }
  9775. }
  9776. }
  9777. function calculateLight( position, normal, color ) {
  9778. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9779. var light = _lights[ l ];
  9780. _lightColor.copy( light.color );
  9781. if ( light instanceof THREE.DirectionalLight ) {
  9782. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  9783. var amount = normal.dot( lightPosition );
  9784. if ( amount <= 0 ) continue;
  9785. amount *= light.intensity;
  9786. color.add( _lightColor.multiplyScalar( amount ) );
  9787. } else if ( light instanceof THREE.PointLight ) {
  9788. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  9789. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9790. if ( amount <= 0 ) continue;
  9791. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9792. if ( amount == 0 ) continue;
  9793. amount *= light.intensity;
  9794. color.add( _lightColor.multiplyScalar( amount ) );
  9795. }
  9796. }
  9797. }
  9798. function renderSprite( v1, element, material ) {
  9799. setOpacity( material.opacity );
  9800. setBlending( material.blending );
  9801. var scaleX = element.scale.x * _canvasWidthHalf;
  9802. var scaleY = element.scale.y * _canvasHeightHalf;
  9803. var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
  9804. _elemBox.min.set( v1.x - dist, v1.y - dist );
  9805. _elemBox.max.set( v1.x + dist, v1.y + dist );
  9806. if ( material instanceof THREE.SpriteMaterial ||
  9807. material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility
  9808. var texture = material.map;
  9809. if ( texture !== null ) {
  9810. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9811. if ( texture.image !== undefined && texture.image.width > 0 ) {
  9812. textureToPattern( texture );
  9813. }
  9814. texture.addEventListener( 'update', onTextureUpdate );
  9815. }
  9816. var pattern = _patterns[ texture.id ];
  9817. if ( pattern !== undefined ) {
  9818. setFillStyle( pattern );
  9819. } else {
  9820. setFillStyle( 'rgba( 0, 0, 0, 1 )' );
  9821. }
  9822. //
  9823. var bitmap = texture.image;
  9824. var ox = bitmap.width * texture.offset.x;
  9825. var oy = bitmap.height * texture.offset.y;
  9826. var sx = bitmap.width * texture.repeat.x;
  9827. var sy = bitmap.height * texture.repeat.y;
  9828. var cx = scaleX / sx;
  9829. var cy = scaleY / sy;
  9830. _context.save();
  9831. _context.translate( v1.x, v1.y );
  9832. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9833. _context.translate( - scaleX / 2, - scaleY / 2 );
  9834. _context.scale( cx, cy );
  9835. _context.translate( - ox, - oy );
  9836. _context.fillRect( ox, oy, sx, sy );
  9837. _context.restore();
  9838. } else { // no texture
  9839. setFillStyle( material.color.getStyle() );
  9840. _context.save();
  9841. _context.translate( v1.x, v1.y );
  9842. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9843. _context.scale( scaleX, - scaleY );
  9844. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  9845. _context.restore();
  9846. }
  9847. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  9848. setStrokeStyle( material.color.getStyle() );
  9849. setFillStyle( material.color.getStyle() );
  9850. _context.save();
  9851. _context.translate( v1.x, v1.y );
  9852. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9853. _context.scale( scaleX, scaleY );
  9854. material.program( _context );
  9855. _context.restore();
  9856. }
  9857. /* DEBUG
  9858. setStrokeStyle( 'rgb(255,255,0)' );
  9859. _context.beginPath();
  9860. _context.moveTo( v1.x - 10, v1.y );
  9861. _context.lineTo( v1.x + 10, v1.y );
  9862. _context.moveTo( v1.x, v1.y - 10 );
  9863. _context.lineTo( v1.x, v1.y + 10 );
  9864. _context.stroke();
  9865. */
  9866. }
  9867. function renderLine( v1, v2, element, material ) {
  9868. setOpacity( material.opacity );
  9869. setBlending( material.blending );
  9870. _context.beginPath();
  9871. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9872. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9873. if ( material instanceof THREE.LineBasicMaterial ) {
  9874. setLineWidth( material.linewidth );
  9875. setLineCap( material.linecap );
  9876. setLineJoin( material.linejoin );
  9877. if ( material.vertexColors !== THREE.VertexColors ) {
  9878. setStrokeStyle( material.color.getStyle() );
  9879. } else {
  9880. var colorStyle1 = element.vertexColors[0].getStyle();
  9881. var colorStyle2 = element.vertexColors[1].getStyle();
  9882. if ( colorStyle1 === colorStyle2 ) {
  9883. setStrokeStyle( colorStyle1 );
  9884. } else {
  9885. try {
  9886. var grad = _context.createLinearGradient(
  9887. v1.positionScreen.x,
  9888. v1.positionScreen.y,
  9889. v2.positionScreen.x,
  9890. v2.positionScreen.y
  9891. );
  9892. grad.addColorStop( 0, colorStyle1 );
  9893. grad.addColorStop( 1, colorStyle2 );
  9894. } catch ( exception ) {
  9895. grad = colorStyle1;
  9896. }
  9897. setStrokeStyle( grad );
  9898. }
  9899. }
  9900. _context.stroke();
  9901. _elemBox.expandByScalar( material.linewidth * 2 );
  9902. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9903. setLineWidth( material.linewidth );
  9904. setLineCap( material.linecap );
  9905. setLineJoin( material.linejoin );
  9906. setStrokeStyle( material.color.getStyle() );
  9907. setDashAndGap( material.dashSize, material.gapSize );
  9908. _context.stroke();
  9909. _elemBox.expandByScalar( material.linewidth * 2 );
  9910. setDashAndGap( null, null );
  9911. }
  9912. }
  9913. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9914. _this.info.render.vertices += 3;
  9915. _this.info.render.faces ++;
  9916. setOpacity( material.opacity );
  9917. setBlending( material.blending );
  9918. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9919. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9920. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9921. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9922. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9923. _diffuseColor.copy( material.color );
  9924. _emissiveColor.copy( material.emissive );
  9925. if ( material.vertexColors === THREE.FaceColors ) {
  9926. _diffuseColor.multiply( element.color );
  9927. }
  9928. if ( material.wireframe === false && material.shading === THREE.SmoothShading && element.vertexNormalsLength === 3 ) {
  9929. _color1.copy( _ambientLight );
  9930. _color2.copy( _ambientLight );
  9931. _color3.copy( _ambientLight );
  9932. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9933. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9934. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  9935. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9936. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9937. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9938. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9939. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9940. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9941. } else {
  9942. _color.copy( _ambientLight );
  9943. calculateLight( element.centroidModel, element.normalModel, _color );
  9944. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9945. material.wireframe === true
  9946. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9947. : fillPath( _color );
  9948. }
  9949. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9950. if ( material.map !== null ) {
  9951. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9952. _uvs = element.uvs[ 0 ];
  9953. 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 );
  9954. }
  9955. } else if ( material.envMap !== null ) {
  9956. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9957. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  9958. _uv1x = 0.5 * _normal.x + 0.5;
  9959. _uv1y = 0.5 * _normal.y + 0.5;
  9960. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  9961. _uv2x = 0.5 * _normal.x + 0.5;
  9962. _uv2y = 0.5 * _normal.y + 0.5;
  9963. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  9964. _uv3x = 0.5 * _normal.x + 0.5;
  9965. _uv3y = 0.5 * _normal.y + 0.5;
  9966. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9967. }/* else if ( material.envMap.mapping === THREE.SphericalRefractionMapping ) {
  9968. }*/
  9969. } else {
  9970. _color.copy( material.color );
  9971. if ( material.vertexColors === THREE.FaceColors ) {
  9972. _color.multiply( element.color );
  9973. }
  9974. material.wireframe === true
  9975. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9976. : fillPath( _color );
  9977. }
  9978. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9979. _near = _camera.near;
  9980. _far = _camera.far;
  9981. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9982. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9983. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9984. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9985. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9986. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9987. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9988. if ( material.shading === THREE.FlatShading ) {
  9989. _normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix );
  9990. _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9991. material.wireframe === true
  9992. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9993. : fillPath( _color );
  9994. } else if ( material.shading === THREE.SmoothShading ) {
  9995. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  9996. _color1.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9997. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  9998. _color2.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9999. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  10000. _color3.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  10001. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  10002. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  10003. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  10004. }
  10005. }
  10006. }
  10007. //
  10008. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  10009. _context.beginPath();
  10010. _context.moveTo( x0, y0 );
  10011. _context.lineTo( x1, y1 );
  10012. _context.lineTo( x2, y2 );
  10013. _context.closePath();
  10014. }
  10015. function strokePath( color, linewidth, linecap, linejoin ) {
  10016. setLineWidth( linewidth );
  10017. setLineCap( linecap );
  10018. setLineJoin( linejoin );
  10019. setStrokeStyle( color.getStyle() );
  10020. _context.stroke();
  10021. _elemBox.expandByScalar( linewidth * 2 );
  10022. }
  10023. function fillPath( color ) {
  10024. setFillStyle( color.getStyle() );
  10025. _context.fill();
  10026. }
  10027. function onTextureUpdate ( event ) {
  10028. textureToPattern( event.target );
  10029. }
  10030. function textureToPattern( texture ) {
  10031. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  10032. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  10033. var image = texture.image;
  10034. var canvas = document.createElement( 'canvas' );
  10035. canvas.width = image.width;
  10036. canvas.height = image.height;
  10037. var context = canvas.getContext( '2d' );
  10038. context.setTransform( 1, 0, 0, - 1, 0, image.height );
  10039. context.drawImage( image, 0, 0 );
  10040. _patterns[ texture.id ] = _context.createPattern(
  10041. canvas, repeatX === true && repeatY === true
  10042. ? 'repeat'
  10043. : repeatX === true && repeatY === false
  10044. ? 'repeat-x'
  10045. : repeatX === false && repeatY === true
  10046. ? 'repeat-y'
  10047. : 'no-repeat'
  10048. );
  10049. }
  10050. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  10051. if ( texture instanceof THREE.DataTexture ) return;
  10052. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  10053. if ( texture.image !== undefined && texture.image.width > 0 ) {
  10054. textureToPattern( texture );
  10055. }
  10056. texture.addEventListener( 'update', onTextureUpdate );
  10057. }
  10058. var pattern = _patterns[ texture.id ];
  10059. if ( pattern !== undefined ) {
  10060. setFillStyle( pattern );
  10061. } else {
  10062. setFillStyle( 'rgba(0,0,0,1)' );
  10063. _context.fill();
  10064. return;
  10065. }
  10066. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  10067. var a, b, c, d, e, f, det, idet,
  10068. offsetX = texture.offset.x / texture.repeat.x,
  10069. offsetY = texture.offset.y / texture.repeat.y,
  10070. width = texture.image.width * texture.repeat.x,
  10071. height = texture.image.height * texture.repeat.y;
  10072. u0 = ( u0 + offsetX ) * width;
  10073. v0 = ( v0 + offsetY ) * height;
  10074. u1 = ( u1 + offsetX ) * width;
  10075. v1 = ( v1 + offsetY ) * height;
  10076. u2 = ( u2 + offsetX ) * width;
  10077. v2 = ( v2 + offsetY ) * height;
  10078. x1 -= x0; y1 -= y0;
  10079. x2 -= x0; y2 -= y0;
  10080. u1 -= u0; v1 -= v0;
  10081. u2 -= u0; v2 -= v0;
  10082. det = u1 * v2 - u2 * v1;
  10083. if ( det === 0 ) return;
  10084. idet = 1 / det;
  10085. a = ( v2 * x1 - v1 * x2 ) * idet;
  10086. b = ( v2 * y1 - v1 * y2 ) * idet;
  10087. c = ( u1 * x2 - u2 * x1 ) * idet;
  10088. d = ( u1 * y2 - u2 * y1 ) * idet;
  10089. e = x0 - a * u0 - c * v0;
  10090. f = y0 - b * u0 - d * v0;
  10091. _context.save();
  10092. _context.transform( a, b, c, d, e, f );
  10093. _context.fill();
  10094. _context.restore();
  10095. }
  10096. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  10097. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  10098. var a, b, c, d, e, f, det, idet,
  10099. width = image.width - 1,
  10100. height = image.height - 1;
  10101. u0 *= width; v0 *= height;
  10102. u1 *= width; v1 *= height;
  10103. u2 *= width; v2 *= height;
  10104. x1 -= x0; y1 -= y0;
  10105. x2 -= x0; y2 -= y0;
  10106. u1 -= u0; v1 -= v0;
  10107. u2 -= u0; v2 -= v0;
  10108. det = u1 * v2 - u2 * v1;
  10109. idet = 1 / det;
  10110. a = ( v2 * x1 - v1 * x2 ) * idet;
  10111. b = ( v2 * y1 - v1 * y2 ) * idet;
  10112. c = ( u1 * x2 - u2 * x1 ) * idet;
  10113. d = ( u1 * y2 - u2 * y1 ) * idet;
  10114. e = x0 - a * u0 - c * v0;
  10115. f = y0 - b * u0 - d * v0;
  10116. _context.save();
  10117. _context.transform( a, b, c, d, e, f );
  10118. _context.clip();
  10119. _context.drawImage( image, 0, 0 );
  10120. _context.restore();
  10121. }
  10122. function getGradientTexture( color1, color2, color3, color4 ) {
  10123. // http://mrdoob.com/blog/post/710
  10124. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  10125. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  10126. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  10127. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  10128. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  10129. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  10130. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  10131. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  10132. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  10133. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  10134. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  10135. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  10136. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  10137. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  10138. return _gradientMap;
  10139. }
  10140. // Hide anti-alias gaps
  10141. function expand( v1, v2, pixels ) {
  10142. var x = v2.x - v1.x, y = v2.y - v1.y,
  10143. det = x * x + y * y, idet;
  10144. if ( det === 0 ) return;
  10145. idet = pixels / Math.sqrt( det );
  10146. x *= idet; y *= idet;
  10147. v2.x += x; v2.y += y;
  10148. v1.x -= x; v1.y -= y;
  10149. }
  10150. // Context cached methods.
  10151. function setOpacity( value ) {
  10152. if ( _contextGlobalAlpha !== value ) {
  10153. _context.globalAlpha = value;
  10154. _contextGlobalAlpha = value;
  10155. }
  10156. }
  10157. function setBlending( value ) {
  10158. if ( _contextGlobalCompositeOperation !== value ) {
  10159. if ( value === THREE.NormalBlending ) {
  10160. _context.globalCompositeOperation = 'source-over';
  10161. } else if ( value === THREE.AdditiveBlending ) {
  10162. _context.globalCompositeOperation = 'lighter';
  10163. } else if ( value === THREE.SubtractiveBlending ) {
  10164. _context.globalCompositeOperation = 'darker';
  10165. }
  10166. _contextGlobalCompositeOperation = value;
  10167. }
  10168. }
  10169. function setLineWidth( value ) {
  10170. if ( _contextLineWidth !== value ) {
  10171. _context.lineWidth = value;
  10172. _contextLineWidth = value;
  10173. }
  10174. }
  10175. function setLineCap( value ) {
  10176. // "butt", "round", "square"
  10177. if ( _contextLineCap !== value ) {
  10178. _context.lineCap = value;
  10179. _contextLineCap = value;
  10180. }
  10181. }
  10182. function setLineJoin( value ) {
  10183. // "round", "bevel", "miter"
  10184. if ( _contextLineJoin !== value ) {
  10185. _context.lineJoin = value;
  10186. _contextLineJoin = value;
  10187. }
  10188. }
  10189. function setStrokeStyle( value ) {
  10190. if ( _contextStrokeStyle !== value ) {
  10191. _context.strokeStyle = value;
  10192. _contextStrokeStyle = value;
  10193. }
  10194. }
  10195. function setFillStyle( value ) {
  10196. if ( _contextFillStyle !== value ) {
  10197. _context.fillStyle = value;
  10198. _contextFillStyle = value;
  10199. }
  10200. }
  10201. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  10202. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  10203. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  10204. _contextDashSize = dashSizeValue;
  10205. _contextGapSize = gapSizeValue;
  10206. }
  10207. }
  10208. };
  10209. /**
  10210. * Shader chunks for WebLG Shader library
  10211. *
  10212. * @author alteredq / http://alteredqualia.com/
  10213. * @author mrdoob / http://mrdoob.com/
  10214. * @author mikael emtinger / http://gomo.se/
  10215. */
  10216. THREE.ShaderChunk = {
  10217. // FOG
  10218. fog_pars_fragment: [
  10219. "#ifdef USE_FOG",
  10220. "uniform vec3 fogColor;",
  10221. "#ifdef FOG_EXP2",
  10222. "uniform float fogDensity;",
  10223. "#else",
  10224. "uniform float fogNear;",
  10225. "uniform float fogFar;",
  10226. "#endif",
  10227. "#endif"
  10228. ].join("\n"),
  10229. fog_fragment: [
  10230. "#ifdef USE_FOG",
  10231. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10232. "#ifdef FOG_EXP2",
  10233. "const float LOG2 = 1.442695;",
  10234. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  10235. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  10236. "#else",
  10237. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  10238. "#endif",
  10239. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  10240. "#endif"
  10241. ].join("\n"),
  10242. // ENVIRONMENT MAP
  10243. envmap_pars_fragment: [
  10244. "#ifdef USE_ENVMAP",
  10245. "uniform float reflectivity;",
  10246. "uniform samplerCube envMap;",
  10247. "uniform float flipEnvMap;",
  10248. "uniform int combine;",
  10249. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10250. "uniform bool useRefract;",
  10251. "uniform float refractionRatio;",
  10252. "#else",
  10253. "varying vec3 vReflect;",
  10254. "#endif",
  10255. "#endif"
  10256. ].join("\n"),
  10257. envmap_fragment: [
  10258. "#ifdef USE_ENVMAP",
  10259. "vec3 reflectVec;",
  10260. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10261. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10262. "if ( useRefract ) {",
  10263. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  10264. "} else { ",
  10265. "reflectVec = reflect( cameraToVertex, normal );",
  10266. "}",
  10267. "#else",
  10268. "reflectVec = vReflect;",
  10269. "#endif",
  10270. "#ifdef DOUBLE_SIDED",
  10271. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10272. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10273. "#else",
  10274. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10275. "#endif",
  10276. "#ifdef GAMMA_INPUT",
  10277. "cubeColor.xyz *= cubeColor.xyz;",
  10278. "#endif",
  10279. "if ( combine == 1 ) {",
  10280. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  10281. "} else if ( combine == 2 ) {",
  10282. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  10283. "} else {",
  10284. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  10285. "}",
  10286. "#endif"
  10287. ].join("\n"),
  10288. envmap_pars_vertex: [
  10289. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10290. "varying vec3 vReflect;",
  10291. "uniform float refractionRatio;",
  10292. "uniform bool useRefract;",
  10293. "#endif"
  10294. ].join("\n"),
  10295. worldpos_vertex : [
  10296. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  10297. "#ifdef USE_SKINNING",
  10298. "vec4 worldPosition = modelMatrix * skinned;",
  10299. "#endif",
  10300. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10301. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  10302. "#endif",
  10303. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10304. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10305. "#endif",
  10306. "#endif"
  10307. ].join("\n"),
  10308. envmap_vertex : [
  10309. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10310. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  10311. "worldNormal = normalize( worldNormal );",
  10312. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  10313. "if ( useRefract ) {",
  10314. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  10315. "} else {",
  10316. "vReflect = reflect( cameraToVertex, worldNormal );",
  10317. "}",
  10318. "#endif"
  10319. ].join("\n"),
  10320. // COLOR MAP (particles)
  10321. map_particle_pars_fragment: [
  10322. "#ifdef USE_MAP",
  10323. "uniform sampler2D map;",
  10324. "#endif"
  10325. ].join("\n"),
  10326. map_particle_fragment: [
  10327. "#ifdef USE_MAP",
  10328. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  10329. "#endif"
  10330. ].join("\n"),
  10331. // COLOR MAP (triangles)
  10332. map_pars_vertex: [
  10333. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10334. "varying vec2 vUv;",
  10335. "uniform vec4 offsetRepeat;",
  10336. "#endif"
  10337. ].join("\n"),
  10338. map_pars_fragment: [
  10339. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10340. "varying vec2 vUv;",
  10341. "#endif",
  10342. "#ifdef USE_MAP",
  10343. "uniform sampler2D map;",
  10344. "#endif"
  10345. ].join("\n"),
  10346. map_vertex: [
  10347. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10348. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  10349. "#endif"
  10350. ].join("\n"),
  10351. map_fragment: [
  10352. "#ifdef USE_MAP",
  10353. "vec4 texelColor = texture2D( map, vUv );",
  10354. "#ifdef GAMMA_INPUT",
  10355. "texelColor.xyz *= texelColor.xyz;",
  10356. "#endif",
  10357. "gl_FragColor = gl_FragColor * texelColor;",
  10358. "#endif"
  10359. ].join("\n"),
  10360. // LIGHT MAP
  10361. lightmap_pars_fragment: [
  10362. "#ifdef USE_LIGHTMAP",
  10363. "varying vec2 vUv2;",
  10364. "uniform sampler2D lightMap;",
  10365. "#endif"
  10366. ].join("\n"),
  10367. lightmap_pars_vertex: [
  10368. "#ifdef USE_LIGHTMAP",
  10369. "varying vec2 vUv2;",
  10370. "#endif"
  10371. ].join("\n"),
  10372. lightmap_fragment: [
  10373. "#ifdef USE_LIGHTMAP",
  10374. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  10375. "#endif"
  10376. ].join("\n"),
  10377. lightmap_vertex: [
  10378. "#ifdef USE_LIGHTMAP",
  10379. "vUv2 = uv2;",
  10380. "#endif"
  10381. ].join("\n"),
  10382. // BUMP MAP
  10383. bumpmap_pars_fragment: [
  10384. "#ifdef USE_BUMPMAP",
  10385. "uniform sampler2D bumpMap;",
  10386. "uniform float bumpScale;",
  10387. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  10388. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  10389. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10390. "vec2 dHdxy_fwd() {",
  10391. "vec2 dSTdx = dFdx( vUv );",
  10392. "vec2 dSTdy = dFdy( vUv );",
  10393. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  10394. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  10395. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  10396. "return vec2( dBx, dBy );",
  10397. "}",
  10398. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  10399. "vec3 vSigmaX = dFdx( surf_pos );",
  10400. "vec3 vSigmaY = dFdy( surf_pos );",
  10401. "vec3 vN = surf_norm;", // normalized
  10402. "vec3 R1 = cross( vSigmaY, vN );",
  10403. "vec3 R2 = cross( vN, vSigmaX );",
  10404. "float fDet = dot( vSigmaX, R1 );",
  10405. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  10406. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  10407. "}",
  10408. "#endif"
  10409. ].join("\n"),
  10410. // NORMAL MAP
  10411. normalmap_pars_fragment: [
  10412. "#ifdef USE_NORMALMAP",
  10413. "uniform sampler2D normalMap;",
  10414. "uniform vec2 normalScale;",
  10415. // Per-Pixel Tangent Space Normal Mapping
  10416. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  10417. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  10418. "vec3 q0 = dFdx( eye_pos.xyz );",
  10419. "vec3 q1 = dFdy( eye_pos.xyz );",
  10420. "vec2 st0 = dFdx( vUv.st );",
  10421. "vec2 st1 = dFdy( vUv.st );",
  10422. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  10423. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  10424. "vec3 N = normalize( surf_norm );",
  10425. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  10426. "mapN.xy = normalScale * mapN.xy;",
  10427. "mat3 tsn = mat3( S, T, N );",
  10428. "return normalize( tsn * mapN );",
  10429. "}",
  10430. "#endif"
  10431. ].join("\n"),
  10432. // SPECULAR MAP
  10433. specularmap_pars_fragment: [
  10434. "#ifdef USE_SPECULARMAP",
  10435. "uniform sampler2D specularMap;",
  10436. "#endif"
  10437. ].join("\n"),
  10438. specularmap_fragment: [
  10439. "float specularStrength;",
  10440. "#ifdef USE_SPECULARMAP",
  10441. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  10442. "specularStrength = texelSpecular.r;",
  10443. "#else",
  10444. "specularStrength = 1.0;",
  10445. "#endif"
  10446. ].join("\n"),
  10447. // LIGHTS LAMBERT
  10448. lights_lambert_pars_vertex: [
  10449. "uniform vec3 ambient;",
  10450. "uniform vec3 diffuse;",
  10451. "uniform vec3 emissive;",
  10452. "uniform vec3 ambientLightColor;",
  10453. "#if MAX_DIR_LIGHTS > 0",
  10454. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10455. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10456. "#endif",
  10457. "#if MAX_HEMI_LIGHTS > 0",
  10458. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10459. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10460. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10461. "#endif",
  10462. "#if MAX_POINT_LIGHTS > 0",
  10463. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10464. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10465. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10466. "#endif",
  10467. "#if MAX_SPOT_LIGHTS > 0",
  10468. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10469. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10470. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10471. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10472. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10473. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10474. "#endif",
  10475. "#ifdef WRAP_AROUND",
  10476. "uniform vec3 wrapRGB;",
  10477. "#endif"
  10478. ].join("\n"),
  10479. lights_lambert_vertex: [
  10480. "vLightFront = vec3( 0.0 );",
  10481. "#ifdef DOUBLE_SIDED",
  10482. "vLightBack = vec3( 0.0 );",
  10483. "#endif",
  10484. "transformedNormal = normalize( transformedNormal );",
  10485. "#if MAX_DIR_LIGHTS > 0",
  10486. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10487. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10488. "vec3 dirVector = normalize( lDirection.xyz );",
  10489. "float dotProduct = dot( transformedNormal, dirVector );",
  10490. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10491. "#ifdef DOUBLE_SIDED",
  10492. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10493. "#ifdef WRAP_AROUND",
  10494. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10495. "#endif",
  10496. "#endif",
  10497. "#ifdef WRAP_AROUND",
  10498. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10499. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  10500. "#ifdef DOUBLE_SIDED",
  10501. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  10502. "#endif",
  10503. "#endif",
  10504. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  10505. "#ifdef DOUBLE_SIDED",
  10506. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  10507. "#endif",
  10508. "}",
  10509. "#endif",
  10510. "#if MAX_POINT_LIGHTS > 0",
  10511. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10512. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10513. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10514. "float lDistance = 1.0;",
  10515. "if ( pointLightDistance[ i ] > 0.0 )",
  10516. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10517. "lVector = normalize( lVector );",
  10518. "float dotProduct = dot( transformedNormal, lVector );",
  10519. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10520. "#ifdef DOUBLE_SIDED",
  10521. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10522. "#ifdef WRAP_AROUND",
  10523. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10524. "#endif",
  10525. "#endif",
  10526. "#ifdef WRAP_AROUND",
  10527. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10528. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10529. "#ifdef DOUBLE_SIDED",
  10530. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10531. "#endif",
  10532. "#endif",
  10533. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10534. "#ifdef DOUBLE_SIDED",
  10535. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10536. "#endif",
  10537. "}",
  10538. "#endif",
  10539. "#if MAX_SPOT_LIGHTS > 0",
  10540. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10541. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10542. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10543. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10544. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10545. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10546. "float lDistance = 1.0;",
  10547. "if ( spotLightDistance[ i ] > 0.0 )",
  10548. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10549. "lVector = normalize( lVector );",
  10550. "float dotProduct = dot( transformedNormal, lVector );",
  10551. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10552. "#ifdef DOUBLE_SIDED",
  10553. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10554. "#ifdef WRAP_AROUND",
  10555. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10556. "#endif",
  10557. "#endif",
  10558. "#ifdef WRAP_AROUND",
  10559. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10560. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10561. "#ifdef DOUBLE_SIDED",
  10562. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10563. "#endif",
  10564. "#endif",
  10565. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10566. "#ifdef DOUBLE_SIDED",
  10567. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10568. "#endif",
  10569. "}",
  10570. "}",
  10571. "#endif",
  10572. "#if MAX_HEMI_LIGHTS > 0",
  10573. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10574. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10575. "vec3 lVector = normalize( lDirection.xyz );",
  10576. "float dotProduct = dot( transformedNormal, lVector );",
  10577. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10578. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10579. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10580. "#ifdef DOUBLE_SIDED",
  10581. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10582. "#endif",
  10583. "}",
  10584. "#endif",
  10585. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10586. "#ifdef DOUBLE_SIDED",
  10587. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10588. "#endif"
  10589. ].join("\n"),
  10590. // LIGHTS PHONG
  10591. lights_phong_pars_vertex: [
  10592. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10593. "varying vec3 vWorldPosition;",
  10594. "#endif"
  10595. ].join("\n"),
  10596. lights_phong_vertex: [
  10597. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10598. "vWorldPosition = worldPosition.xyz;",
  10599. "#endif"
  10600. ].join("\n"),
  10601. lights_phong_pars_fragment: [
  10602. "uniform vec3 ambientLightColor;",
  10603. "#if MAX_DIR_LIGHTS > 0",
  10604. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10605. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10606. "#endif",
  10607. "#if MAX_HEMI_LIGHTS > 0",
  10608. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10609. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10610. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10611. "#endif",
  10612. "#if MAX_POINT_LIGHTS > 0",
  10613. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10614. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10615. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10616. "#endif",
  10617. "#if MAX_SPOT_LIGHTS > 0",
  10618. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10619. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10620. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10621. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10622. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10623. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10624. "#endif",
  10625. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10626. "varying vec3 vWorldPosition;",
  10627. "#endif",
  10628. "#ifdef WRAP_AROUND",
  10629. "uniform vec3 wrapRGB;",
  10630. "#endif",
  10631. "varying vec3 vViewPosition;",
  10632. "varying vec3 vNormal;"
  10633. ].join("\n"),
  10634. lights_phong_fragment: [
  10635. "vec3 normal = normalize( vNormal );",
  10636. "vec3 viewPosition = normalize( vViewPosition );",
  10637. "#ifdef DOUBLE_SIDED",
  10638. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10639. "#endif",
  10640. "#ifdef USE_NORMALMAP",
  10641. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  10642. "#elif defined( USE_BUMPMAP )",
  10643. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10644. "#endif",
  10645. "#if MAX_POINT_LIGHTS > 0",
  10646. "vec3 pointDiffuse = vec3( 0.0 );",
  10647. "vec3 pointSpecular = vec3( 0.0 );",
  10648. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10649. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10650. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10651. "float lDistance = 1.0;",
  10652. "if ( pointLightDistance[ i ] > 0.0 )",
  10653. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10654. "lVector = normalize( lVector );",
  10655. // diffuse
  10656. "float dotProduct = dot( normal, lVector );",
  10657. "#ifdef WRAP_AROUND",
  10658. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10659. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10660. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10661. "#else",
  10662. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10663. "#endif",
  10664. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10665. // specular
  10666. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10667. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10668. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10669. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10670. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10671. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );",
  10672. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10673. "}",
  10674. "#endif",
  10675. "#if MAX_SPOT_LIGHTS > 0",
  10676. "vec3 spotDiffuse = vec3( 0.0 );",
  10677. "vec3 spotSpecular = vec3( 0.0 );",
  10678. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10679. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10680. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10681. "float lDistance = 1.0;",
  10682. "if ( spotLightDistance[ i ] > 0.0 )",
  10683. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10684. "lVector = normalize( lVector );",
  10685. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10686. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10687. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10688. // diffuse
  10689. "float dotProduct = dot( normal, lVector );",
  10690. "#ifdef WRAP_AROUND",
  10691. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10692. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10693. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10694. "#else",
  10695. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10696. "#endif",
  10697. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10698. // specular
  10699. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10700. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10701. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10702. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10703. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10704. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );",
  10705. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10706. "}",
  10707. "}",
  10708. "#endif",
  10709. "#if MAX_DIR_LIGHTS > 0",
  10710. "vec3 dirDiffuse = vec3( 0.0 );",
  10711. "vec3 dirSpecular = vec3( 0.0 );" ,
  10712. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10713. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10714. "vec3 dirVector = normalize( lDirection.xyz );",
  10715. // diffuse
  10716. "float dotProduct = dot( normal, dirVector );",
  10717. "#ifdef WRAP_AROUND",
  10718. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10719. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10720. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10721. "#else",
  10722. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10723. "#endif",
  10724. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10725. // specular
  10726. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10727. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10728. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10729. /*
  10730. // fresnel term from skin shader
  10731. "const float F0 = 0.128;",
  10732. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10733. "float exponential = pow( base, 5.0 );",
  10734. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10735. */
  10736. /*
  10737. // fresnel term from fresnel shader
  10738. "const float mFresnelBias = 0.08;",
  10739. "const float mFresnelScale = 0.3;",
  10740. "const float mFresnelPower = 5.0;",
  10741. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10742. */
  10743. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10744. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10745. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10746. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );",
  10747. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10748. "}",
  10749. "#endif",
  10750. "#if MAX_HEMI_LIGHTS > 0",
  10751. "vec3 hemiDiffuse = vec3( 0.0 );",
  10752. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10753. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10754. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10755. "vec3 lVector = normalize( lDirection.xyz );",
  10756. // diffuse
  10757. "float dotProduct = dot( normal, lVector );",
  10758. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10759. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10760. "hemiDiffuse += diffuse * hemiColor;",
  10761. // specular (sky light)
  10762. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10763. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10764. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10765. // specular (ground light)
  10766. "vec3 lVectorGround = -lVector;",
  10767. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10768. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10769. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10770. "float dotProductGround = dot( normal, lVectorGround );",
  10771. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10772. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10773. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );",
  10774. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );",
  10775. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10776. "}",
  10777. "#endif",
  10778. "vec3 totalDiffuse = vec3( 0.0 );",
  10779. "vec3 totalSpecular = vec3( 0.0 );",
  10780. "#if MAX_DIR_LIGHTS > 0",
  10781. "totalDiffuse += dirDiffuse;",
  10782. "totalSpecular += dirSpecular;",
  10783. "#endif",
  10784. "#if MAX_HEMI_LIGHTS > 0",
  10785. "totalDiffuse += hemiDiffuse;",
  10786. "totalSpecular += hemiSpecular;",
  10787. "#endif",
  10788. "#if MAX_POINT_LIGHTS > 0",
  10789. "totalDiffuse += pointDiffuse;",
  10790. "totalSpecular += pointSpecular;",
  10791. "#endif",
  10792. "#if MAX_SPOT_LIGHTS > 0",
  10793. "totalDiffuse += spotDiffuse;",
  10794. "totalSpecular += spotSpecular;",
  10795. "#endif",
  10796. "#ifdef METAL",
  10797. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10798. "#else",
  10799. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10800. "#endif"
  10801. ].join("\n"),
  10802. // VERTEX COLORS
  10803. color_pars_fragment: [
  10804. "#ifdef USE_COLOR",
  10805. "varying vec3 vColor;",
  10806. "#endif"
  10807. ].join("\n"),
  10808. color_fragment: [
  10809. "#ifdef USE_COLOR",
  10810. "gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  10811. "#endif"
  10812. ].join("\n"),
  10813. color_pars_vertex: [
  10814. "#ifdef USE_COLOR",
  10815. "varying vec3 vColor;",
  10816. "#endif"
  10817. ].join("\n"),
  10818. color_vertex: [
  10819. "#ifdef USE_COLOR",
  10820. "#ifdef GAMMA_INPUT",
  10821. "vColor = color * color;",
  10822. "#else",
  10823. "vColor = color;",
  10824. "#endif",
  10825. "#endif"
  10826. ].join("\n"),
  10827. // SKINNING
  10828. skinning_pars_vertex: [
  10829. "#ifdef USE_SKINNING",
  10830. "#ifdef BONE_TEXTURE",
  10831. "uniform sampler2D boneTexture;",
  10832. "uniform int boneTextureWidth;",
  10833. "uniform int boneTextureHeight;",
  10834. "mat4 getBoneMatrix( const in float i ) {",
  10835. "float j = i * 4.0;",
  10836. "float x = mod( j, float( boneTextureWidth ) );",
  10837. "float y = floor( j / float( boneTextureWidth ) );",
  10838. "float dx = 1.0 / float( boneTextureWidth );",
  10839. "float dy = 1.0 / float( boneTextureHeight );",
  10840. "y = dy * ( y + 0.5 );",
  10841. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10842. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10843. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10844. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10845. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10846. "return bone;",
  10847. "}",
  10848. "#else",
  10849. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10850. "mat4 getBoneMatrix( const in float i ) {",
  10851. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10852. "return bone;",
  10853. "}",
  10854. "#endif",
  10855. "#endif"
  10856. ].join("\n"),
  10857. skinbase_vertex: [
  10858. "#ifdef USE_SKINNING",
  10859. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10860. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10861. "mat4 boneMatZ = getBoneMatrix( skinIndex.z );",
  10862. "mat4 boneMatW = getBoneMatrix( skinIndex.w );",
  10863. "#endif"
  10864. ].join("\n"),
  10865. skinning_vertex: [
  10866. "#ifdef USE_SKINNING",
  10867. "#ifdef USE_MORPHTARGETS",
  10868. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10869. "#else",
  10870. "vec4 skinVertex = vec4( position, 1.0 );",
  10871. "#endif",
  10872. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10873. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10874. "skinned += boneMatZ * skinVertex * skinWeight.z;",
  10875. "skinned += boneMatW * skinVertex * skinWeight.w;",
  10876. "#endif"
  10877. ].join("\n"),
  10878. // MORPHING
  10879. morphtarget_pars_vertex: [
  10880. "#ifdef USE_MORPHTARGETS",
  10881. "#ifndef USE_MORPHNORMALS",
  10882. "uniform float morphTargetInfluences[ 8 ];",
  10883. "#else",
  10884. "uniform float morphTargetInfluences[ 4 ];",
  10885. "#endif",
  10886. "#endif"
  10887. ].join("\n"),
  10888. morphtarget_vertex: [
  10889. "#ifdef USE_MORPHTARGETS",
  10890. "vec3 morphed = vec3( 0.0 );",
  10891. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10892. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10893. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10894. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10895. "#ifndef USE_MORPHNORMALS",
  10896. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10897. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10898. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10899. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10900. "#endif",
  10901. "morphed += position;",
  10902. "#endif"
  10903. ].join("\n"),
  10904. default_vertex : [
  10905. "vec4 mvPosition;",
  10906. "#ifdef USE_SKINNING",
  10907. "mvPosition = modelViewMatrix * skinned;",
  10908. "#endif",
  10909. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10910. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10911. "#endif",
  10912. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10913. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10914. "#endif",
  10915. "gl_Position = projectionMatrix * mvPosition;"
  10916. ].join("\n"),
  10917. morphnormal_vertex: [
  10918. "#ifdef USE_MORPHNORMALS",
  10919. "vec3 morphedNormal = vec3( 0.0 );",
  10920. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10921. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10922. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10923. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10924. "morphedNormal += normal;",
  10925. "#endif"
  10926. ].join("\n"),
  10927. skinnormal_vertex: [
  10928. "#ifdef USE_SKINNING",
  10929. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  10930. "skinMatrix += skinWeight.y * boneMatY;",
  10931. "#ifdef USE_MORPHNORMALS",
  10932. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10933. "#else",
  10934. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10935. "#endif",
  10936. "#endif"
  10937. ].join("\n"),
  10938. defaultnormal_vertex: [
  10939. "vec3 objectNormal;",
  10940. "#ifdef USE_SKINNING",
  10941. "objectNormal = skinnedNormal.xyz;",
  10942. "#endif",
  10943. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10944. "objectNormal = morphedNormal;",
  10945. "#endif",
  10946. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10947. "objectNormal = normal;",
  10948. "#endif",
  10949. "#ifdef FLIP_SIDED",
  10950. "objectNormal = -objectNormal;",
  10951. "#endif",
  10952. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10953. ].join("\n"),
  10954. // SHADOW MAP
  10955. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10956. // http://spidergl.org/example.php?id=6
  10957. // http://fabiensanglard.net/shadowmapping
  10958. shadowmap_pars_fragment: [
  10959. "#ifdef USE_SHADOWMAP",
  10960. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10961. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10962. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10963. "uniform float shadowBias[ MAX_SHADOWS ];",
  10964. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10965. "float unpackDepth( const in vec4 rgba_depth ) {",
  10966. "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 );",
  10967. "float depth = dot( rgba_depth, bit_shift );",
  10968. "return depth;",
  10969. "}",
  10970. "#endif"
  10971. ].join("\n"),
  10972. shadowmap_fragment: [
  10973. "#ifdef USE_SHADOWMAP",
  10974. "#ifdef SHADOWMAP_DEBUG",
  10975. "vec3 frustumColors[3];",
  10976. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10977. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10978. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10979. "#endif",
  10980. "#ifdef SHADOWMAP_CASCADE",
  10981. "int inFrustumCount = 0;",
  10982. "#endif",
  10983. "float fDepth;",
  10984. "vec3 shadowColor = vec3( 1.0 );",
  10985. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10986. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10987. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10988. // "if ( all( something, something ) )" using this instead
  10989. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10990. "bool inFrustum = all( inFrustumVec );",
  10991. // don't shadow pixels outside of light frustum
  10992. // use just first frustum (for cascades)
  10993. // don't shadow pixels behind far plane of light frustum
  10994. "#ifdef SHADOWMAP_CASCADE",
  10995. "inFrustumCount += int( inFrustum );",
  10996. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10997. "#else",
  10998. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10999. "#endif",
  11000. "bool frustumTest = all( frustumTestVec );",
  11001. "if ( frustumTest ) {",
  11002. "shadowCoord.z += shadowBias[ i ];",
  11003. "#if defined( SHADOWMAP_TYPE_PCF )",
  11004. // Percentage-close filtering
  11005. // (9 pixel kernel)
  11006. // http://fabiensanglard.net/shadowmappingPCF/
  11007. "float shadow = 0.0;",
  11008. /*
  11009. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  11010. // must enroll loop manually
  11011. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  11012. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  11013. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  11014. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  11015. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  11016. "float fDepth = unpackDepth( rgbaDepth );",
  11017. "if ( fDepth < shadowCoord.z )",
  11018. "shadow += 1.0;",
  11019. "}",
  11020. "shadow /= 9.0;",
  11021. */
  11022. "const float shadowDelta = 1.0 / 9.0;",
  11023. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  11024. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  11025. "float dx0 = -1.25 * xPixelOffset;",
  11026. "float dy0 = -1.25 * yPixelOffset;",
  11027. "float dx1 = 1.25 * xPixelOffset;",
  11028. "float dy1 = 1.25 * yPixelOffset;",
  11029. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  11030. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11031. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  11032. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11033. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  11034. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11035. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  11036. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11037. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  11038. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11039. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  11040. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11041. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  11042. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11043. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  11044. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11045. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  11046. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11047. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  11048. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  11049. // Percentage-close filtering
  11050. // (9 pixel kernel)
  11051. // http://fabiensanglard.net/shadowmappingPCF/
  11052. "float shadow = 0.0;",
  11053. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  11054. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  11055. "float dx0 = -1.0 * xPixelOffset;",
  11056. "float dy0 = -1.0 * yPixelOffset;",
  11057. "float dx1 = 1.0 * xPixelOffset;",
  11058. "float dy1 = 1.0 * yPixelOffset;",
  11059. "mat3 shadowKernel;",
  11060. "mat3 depthKernel;",
  11061. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  11062. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  11063. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  11064. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  11065. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  11066. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  11067. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  11068. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  11069. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  11070. "vec3 shadowZ = vec3( shadowCoord.z );",
  11071. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  11072. "shadowKernel[0] *= vec3(0.25);",
  11073. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  11074. "shadowKernel[1] *= vec3(0.25);",
  11075. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  11076. "shadowKernel[2] *= vec3(0.25);",
  11077. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  11078. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  11079. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  11080. "vec4 shadowValues;",
  11081. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  11082. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  11083. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  11084. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  11085. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  11086. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  11087. "#else",
  11088. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  11089. "float fDepth = unpackDepth( rgbaDepth );",
  11090. "if ( fDepth < shadowCoord.z )",
  11091. // spot with multiple shadows is darker
  11092. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  11093. // spot with multiple shadows has the same color as single shadow spot
  11094. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  11095. "#endif",
  11096. "}",
  11097. "#ifdef SHADOWMAP_DEBUG",
  11098. "#ifdef SHADOWMAP_CASCADE",
  11099. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  11100. "#else",
  11101. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  11102. "#endif",
  11103. "#endif",
  11104. "}",
  11105. "#ifdef GAMMA_OUTPUT",
  11106. "shadowColor *= shadowColor;",
  11107. "#endif",
  11108. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  11109. "#endif"
  11110. ].join("\n"),
  11111. shadowmap_pars_vertex: [
  11112. "#ifdef USE_SHADOWMAP",
  11113. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  11114. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  11115. "#endif"
  11116. ].join("\n"),
  11117. shadowmap_vertex: [
  11118. "#ifdef USE_SHADOWMAP",
  11119. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11120. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11121. "}",
  11122. "#endif"
  11123. ].join("\n"),
  11124. // ALPHATEST
  11125. alphatest_fragment: [
  11126. "#ifdef ALPHATEST",
  11127. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  11128. "#endif"
  11129. ].join("\n"),
  11130. // LINEAR SPACE
  11131. linear_to_gamma_fragment: [
  11132. "#ifdef GAMMA_OUTPUT",
  11133. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  11134. "#endif"
  11135. ].join("\n")
  11136. };
  11137. /**
  11138. * Uniform Utilities
  11139. */
  11140. THREE.UniformsUtils = {
  11141. merge: function ( uniforms ) {
  11142. var u, p, tmp, merged = {};
  11143. for ( u = 0; u < uniforms.length; u ++ ) {
  11144. tmp = this.clone( uniforms[ u ] );
  11145. for ( p in tmp ) {
  11146. merged[ p ] = tmp[ p ];
  11147. }
  11148. }
  11149. return merged;
  11150. },
  11151. clone: function ( uniforms_src ) {
  11152. var u, p, parameter, parameter_src, uniforms_dst = {};
  11153. for ( u in uniforms_src ) {
  11154. uniforms_dst[ u ] = {};
  11155. for ( p in uniforms_src[ u ] ) {
  11156. parameter_src = uniforms_src[ u ][ p ];
  11157. if ( parameter_src instanceof THREE.Color ||
  11158. parameter_src instanceof THREE.Vector2 ||
  11159. parameter_src instanceof THREE.Vector3 ||
  11160. parameter_src instanceof THREE.Vector4 ||
  11161. parameter_src instanceof THREE.Matrix4 ||
  11162. parameter_src instanceof THREE.Texture ) {
  11163. uniforms_dst[ u ][ p ] = parameter_src.clone();
  11164. } else if ( parameter_src instanceof Array ) {
  11165. uniforms_dst[ u ][ p ] = parameter_src.slice();
  11166. } else {
  11167. uniforms_dst[ u ][ p ] = parameter_src;
  11168. }
  11169. }
  11170. }
  11171. return uniforms_dst;
  11172. }
  11173. };
  11174. /**
  11175. * Uniforms library for shared webgl shaders
  11176. */
  11177. THREE.UniformsLib = {
  11178. common: {
  11179. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11180. "opacity" : { type: "f", value: 1.0 },
  11181. "map" : { type: "t", value: null },
  11182. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  11183. "lightMap" : { type: "t", value: null },
  11184. "specularMap" : { type: "t", value: null },
  11185. "envMap" : { type: "t", value: null },
  11186. "flipEnvMap" : { type: "f", value: -1 },
  11187. "useRefract" : { type: "i", value: 0 },
  11188. "reflectivity" : { type: "f", value: 1.0 },
  11189. "refractionRatio" : { type: "f", value: 0.98 },
  11190. "combine" : { type: "i", value: 0 },
  11191. "morphTargetInfluences" : { type: "f", value: 0 }
  11192. },
  11193. bump: {
  11194. "bumpMap" : { type: "t", value: null },
  11195. "bumpScale" : { type: "f", value: 1 }
  11196. },
  11197. normalmap: {
  11198. "normalMap" : { type: "t", value: null },
  11199. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  11200. },
  11201. fog : {
  11202. "fogDensity" : { type: "f", value: 0.00025 },
  11203. "fogNear" : { type: "f", value: 1 },
  11204. "fogFar" : { type: "f", value: 2000 },
  11205. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11206. },
  11207. lights: {
  11208. "ambientLightColor" : { type: "fv", value: [] },
  11209. "directionalLightDirection" : { type: "fv", value: [] },
  11210. "directionalLightColor" : { type: "fv", value: [] },
  11211. "hemisphereLightDirection" : { type: "fv", value: [] },
  11212. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  11213. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  11214. "pointLightColor" : { type: "fv", value: [] },
  11215. "pointLightPosition" : { type: "fv", value: [] },
  11216. "pointLightDistance" : { type: "fv1", value: [] },
  11217. "spotLightColor" : { type: "fv", value: [] },
  11218. "spotLightPosition" : { type: "fv", value: [] },
  11219. "spotLightDirection" : { type: "fv", value: [] },
  11220. "spotLightDistance" : { type: "fv1", value: [] },
  11221. "spotLightAngleCos" : { type: "fv1", value: [] },
  11222. "spotLightExponent" : { type: "fv1", value: [] }
  11223. },
  11224. particle: {
  11225. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11226. "opacity" : { type: "f", value: 1.0 },
  11227. "size" : { type: "f", value: 1.0 },
  11228. "scale" : { type: "f", value: 1.0 },
  11229. "map" : { type: "t", value: null },
  11230. "fogDensity" : { type: "f", value: 0.00025 },
  11231. "fogNear" : { type: "f", value: 1 },
  11232. "fogFar" : { type: "f", value: 2000 },
  11233. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11234. },
  11235. shadowmap: {
  11236. "shadowMap": { type: "tv", value: [] },
  11237. "shadowMapSize": { type: "v2v", value: [] },
  11238. "shadowBias" : { type: "fv1", value: [] },
  11239. "shadowDarkness": { type: "fv1", value: [] },
  11240. "shadowMatrix" : { type: "m4v", value: [] }
  11241. }
  11242. };
  11243. /**
  11244. * Webgl Shader Library for three.js
  11245. *
  11246. * @author alteredq / http://alteredqualia.com/
  11247. * @author mrdoob / http://mrdoob.com/
  11248. * @author mikael emtinger / http://gomo.se/
  11249. */
  11250. THREE.ShaderLib = {
  11251. 'basic': {
  11252. uniforms: THREE.UniformsUtils.merge( [
  11253. THREE.UniformsLib[ "common" ],
  11254. THREE.UniformsLib[ "fog" ],
  11255. THREE.UniformsLib[ "shadowmap" ]
  11256. ] ),
  11257. vertexShader: [
  11258. THREE.ShaderChunk[ "map_pars_vertex" ],
  11259. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11260. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11261. THREE.ShaderChunk[ "color_pars_vertex" ],
  11262. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11263. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11264. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11265. "void main() {",
  11266. THREE.ShaderChunk[ "map_vertex" ],
  11267. THREE.ShaderChunk[ "lightmap_vertex" ],
  11268. THREE.ShaderChunk[ "color_vertex" ],
  11269. THREE.ShaderChunk[ "skinbase_vertex" ],
  11270. "#ifdef USE_ENVMAP",
  11271. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11272. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11273. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11274. "#endif",
  11275. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11276. THREE.ShaderChunk[ "skinning_vertex" ],
  11277. THREE.ShaderChunk[ "default_vertex" ],
  11278. THREE.ShaderChunk[ "worldpos_vertex" ],
  11279. THREE.ShaderChunk[ "envmap_vertex" ],
  11280. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11281. "}"
  11282. ].join("\n"),
  11283. fragmentShader: [
  11284. "uniform vec3 diffuse;",
  11285. "uniform float opacity;",
  11286. THREE.ShaderChunk[ "color_pars_fragment" ],
  11287. THREE.ShaderChunk[ "map_pars_fragment" ],
  11288. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11289. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11290. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11291. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11292. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11293. "void main() {",
  11294. "gl_FragColor = vec4( diffuse, opacity );",
  11295. THREE.ShaderChunk[ "map_fragment" ],
  11296. THREE.ShaderChunk[ "alphatest_fragment" ],
  11297. THREE.ShaderChunk[ "specularmap_fragment" ],
  11298. THREE.ShaderChunk[ "lightmap_fragment" ],
  11299. THREE.ShaderChunk[ "color_fragment" ],
  11300. THREE.ShaderChunk[ "envmap_fragment" ],
  11301. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11302. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11303. THREE.ShaderChunk[ "fog_fragment" ],
  11304. "}"
  11305. ].join("\n")
  11306. },
  11307. 'lambert': {
  11308. uniforms: THREE.UniformsUtils.merge( [
  11309. THREE.UniformsLib[ "common" ],
  11310. THREE.UniformsLib[ "fog" ],
  11311. THREE.UniformsLib[ "lights" ],
  11312. THREE.UniformsLib[ "shadowmap" ],
  11313. {
  11314. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11315. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11316. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11317. }
  11318. ] ),
  11319. vertexShader: [
  11320. "#define LAMBERT",
  11321. "varying vec3 vLightFront;",
  11322. "#ifdef DOUBLE_SIDED",
  11323. "varying vec3 vLightBack;",
  11324. "#endif",
  11325. THREE.ShaderChunk[ "map_pars_vertex" ],
  11326. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11327. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11328. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  11329. THREE.ShaderChunk[ "color_pars_vertex" ],
  11330. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11331. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11332. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11333. "void main() {",
  11334. THREE.ShaderChunk[ "map_vertex" ],
  11335. THREE.ShaderChunk[ "lightmap_vertex" ],
  11336. THREE.ShaderChunk[ "color_vertex" ],
  11337. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11338. THREE.ShaderChunk[ "skinbase_vertex" ],
  11339. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11340. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11341. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11342. THREE.ShaderChunk[ "skinning_vertex" ],
  11343. THREE.ShaderChunk[ "default_vertex" ],
  11344. THREE.ShaderChunk[ "worldpos_vertex" ],
  11345. THREE.ShaderChunk[ "envmap_vertex" ],
  11346. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  11347. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11348. "}"
  11349. ].join("\n"),
  11350. fragmentShader: [
  11351. "uniform float opacity;",
  11352. "varying vec3 vLightFront;",
  11353. "#ifdef DOUBLE_SIDED",
  11354. "varying vec3 vLightBack;",
  11355. "#endif",
  11356. THREE.ShaderChunk[ "color_pars_fragment" ],
  11357. THREE.ShaderChunk[ "map_pars_fragment" ],
  11358. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11359. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11360. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11361. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11362. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11363. "void main() {",
  11364. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  11365. THREE.ShaderChunk[ "map_fragment" ],
  11366. THREE.ShaderChunk[ "alphatest_fragment" ],
  11367. THREE.ShaderChunk[ "specularmap_fragment" ],
  11368. "#ifdef DOUBLE_SIDED",
  11369. //"float isFront = float( gl_FrontFacing );",
  11370. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  11371. "if ( gl_FrontFacing )",
  11372. "gl_FragColor.xyz *= vLightFront;",
  11373. "else",
  11374. "gl_FragColor.xyz *= vLightBack;",
  11375. "#else",
  11376. "gl_FragColor.xyz *= vLightFront;",
  11377. "#endif",
  11378. THREE.ShaderChunk[ "lightmap_fragment" ],
  11379. THREE.ShaderChunk[ "color_fragment" ],
  11380. THREE.ShaderChunk[ "envmap_fragment" ],
  11381. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11382. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11383. THREE.ShaderChunk[ "fog_fragment" ],
  11384. "}"
  11385. ].join("\n")
  11386. },
  11387. 'phong': {
  11388. uniforms: THREE.UniformsUtils.merge( [
  11389. THREE.UniformsLib[ "common" ],
  11390. THREE.UniformsLib[ "bump" ],
  11391. THREE.UniformsLib[ "normalmap" ],
  11392. THREE.UniformsLib[ "fog" ],
  11393. THREE.UniformsLib[ "lights" ],
  11394. THREE.UniformsLib[ "shadowmap" ],
  11395. {
  11396. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11397. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11398. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  11399. "shininess": { type: "f", value: 30 },
  11400. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11401. }
  11402. ] ),
  11403. vertexShader: [
  11404. "#define PHONG",
  11405. "varying vec3 vViewPosition;",
  11406. "varying vec3 vNormal;",
  11407. THREE.ShaderChunk[ "map_pars_vertex" ],
  11408. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11409. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11410. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  11411. THREE.ShaderChunk[ "color_pars_vertex" ],
  11412. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11413. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11414. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11415. "void main() {",
  11416. THREE.ShaderChunk[ "map_vertex" ],
  11417. THREE.ShaderChunk[ "lightmap_vertex" ],
  11418. THREE.ShaderChunk[ "color_vertex" ],
  11419. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11420. THREE.ShaderChunk[ "skinbase_vertex" ],
  11421. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11422. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11423. "vNormal = normalize( transformedNormal );",
  11424. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11425. THREE.ShaderChunk[ "skinning_vertex" ],
  11426. THREE.ShaderChunk[ "default_vertex" ],
  11427. "vViewPosition = -mvPosition.xyz;",
  11428. THREE.ShaderChunk[ "worldpos_vertex" ],
  11429. THREE.ShaderChunk[ "envmap_vertex" ],
  11430. THREE.ShaderChunk[ "lights_phong_vertex" ],
  11431. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11432. "}"
  11433. ].join("\n"),
  11434. fragmentShader: [
  11435. "uniform vec3 diffuse;",
  11436. "uniform float opacity;",
  11437. "uniform vec3 ambient;",
  11438. "uniform vec3 emissive;",
  11439. "uniform vec3 specular;",
  11440. "uniform float shininess;",
  11441. THREE.ShaderChunk[ "color_pars_fragment" ],
  11442. THREE.ShaderChunk[ "map_pars_fragment" ],
  11443. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11444. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11445. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11446. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11447. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11448. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11449. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11450. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11451. "void main() {",
  11452. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  11453. THREE.ShaderChunk[ "map_fragment" ],
  11454. THREE.ShaderChunk[ "alphatest_fragment" ],
  11455. THREE.ShaderChunk[ "specularmap_fragment" ],
  11456. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11457. THREE.ShaderChunk[ "lightmap_fragment" ],
  11458. THREE.ShaderChunk[ "color_fragment" ],
  11459. THREE.ShaderChunk[ "envmap_fragment" ],
  11460. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11461. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11462. THREE.ShaderChunk[ "fog_fragment" ],
  11463. "}"
  11464. ].join("\n")
  11465. },
  11466. 'particle_basic': {
  11467. uniforms: THREE.UniformsUtils.merge( [
  11468. THREE.UniformsLib[ "particle" ],
  11469. THREE.UniformsLib[ "shadowmap" ]
  11470. ] ),
  11471. vertexShader: [
  11472. "uniform float size;",
  11473. "uniform float scale;",
  11474. THREE.ShaderChunk[ "color_pars_vertex" ],
  11475. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11476. "void main() {",
  11477. THREE.ShaderChunk[ "color_vertex" ],
  11478. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11479. "#ifdef USE_SIZEATTENUATION",
  11480. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11481. "#else",
  11482. "gl_PointSize = size;",
  11483. "#endif",
  11484. "gl_Position = projectionMatrix * mvPosition;",
  11485. THREE.ShaderChunk[ "worldpos_vertex" ],
  11486. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11487. "}"
  11488. ].join("\n"),
  11489. fragmentShader: [
  11490. "uniform vec3 psColor;",
  11491. "uniform float opacity;",
  11492. THREE.ShaderChunk[ "color_pars_fragment" ],
  11493. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11494. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11495. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11496. "void main() {",
  11497. "gl_FragColor = vec4( psColor, opacity );",
  11498. THREE.ShaderChunk[ "map_particle_fragment" ],
  11499. THREE.ShaderChunk[ "alphatest_fragment" ],
  11500. THREE.ShaderChunk[ "color_fragment" ],
  11501. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11502. THREE.ShaderChunk[ "fog_fragment" ],
  11503. "}"
  11504. ].join("\n")
  11505. },
  11506. 'dashed': {
  11507. uniforms: THREE.UniformsUtils.merge( [
  11508. THREE.UniformsLib[ "common" ],
  11509. THREE.UniformsLib[ "fog" ],
  11510. {
  11511. "scale": { type: "f", value: 1 },
  11512. "dashSize": { type: "f", value: 1 },
  11513. "totalSize": { type: "f", value: 2 }
  11514. }
  11515. ] ),
  11516. vertexShader: [
  11517. "uniform float scale;",
  11518. "attribute float lineDistance;",
  11519. "varying float vLineDistance;",
  11520. THREE.ShaderChunk[ "color_pars_vertex" ],
  11521. "void main() {",
  11522. THREE.ShaderChunk[ "color_vertex" ],
  11523. "vLineDistance = scale * lineDistance;",
  11524. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11525. "gl_Position = projectionMatrix * mvPosition;",
  11526. "}"
  11527. ].join("\n"),
  11528. fragmentShader: [
  11529. "uniform vec3 diffuse;",
  11530. "uniform float opacity;",
  11531. "uniform float dashSize;",
  11532. "uniform float totalSize;",
  11533. "varying float vLineDistance;",
  11534. THREE.ShaderChunk[ "color_pars_fragment" ],
  11535. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11536. "void main() {",
  11537. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11538. "discard;",
  11539. "}",
  11540. "gl_FragColor = vec4( diffuse, opacity );",
  11541. THREE.ShaderChunk[ "color_fragment" ],
  11542. THREE.ShaderChunk[ "fog_fragment" ],
  11543. "}"
  11544. ].join("\n")
  11545. },
  11546. 'depth': {
  11547. uniforms: {
  11548. "mNear": { type: "f", value: 1.0 },
  11549. "mFar" : { type: "f", value: 2000.0 },
  11550. "opacity" : { type: "f", value: 1.0 }
  11551. },
  11552. vertexShader: [
  11553. "void main() {",
  11554. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11555. "}"
  11556. ].join("\n"),
  11557. fragmentShader: [
  11558. "uniform float mNear;",
  11559. "uniform float mFar;",
  11560. "uniform float opacity;",
  11561. "void main() {",
  11562. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11563. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11564. "gl_FragColor = vec4( vec3( color ), opacity );",
  11565. "}"
  11566. ].join("\n")
  11567. },
  11568. 'normal': {
  11569. uniforms: {
  11570. "opacity" : { type: "f", value: 1.0 }
  11571. },
  11572. vertexShader: [
  11573. "varying vec3 vNormal;",
  11574. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11575. "void main() {",
  11576. "vNormal = normalize( normalMatrix * normal );",
  11577. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11578. THREE.ShaderChunk[ "default_vertex" ],
  11579. "}"
  11580. ].join("\n"),
  11581. fragmentShader: [
  11582. "uniform float opacity;",
  11583. "varying vec3 vNormal;",
  11584. "void main() {",
  11585. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11586. "}"
  11587. ].join("\n")
  11588. },
  11589. /* -------------------------------------------------------------------------
  11590. // Normal map shader
  11591. // - Blinn-Phong
  11592. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11593. // - point and directional lights (use with "lights: true" material option)
  11594. ------------------------------------------------------------------------- */
  11595. 'normalmap' : {
  11596. uniforms: THREE.UniformsUtils.merge( [
  11597. THREE.UniformsLib[ "fog" ],
  11598. THREE.UniformsLib[ "lights" ],
  11599. THREE.UniformsLib[ "shadowmap" ],
  11600. {
  11601. "enableAO" : { type: "i", value: 0 },
  11602. "enableDiffuse" : { type: "i", value: 0 },
  11603. "enableSpecular" : { type: "i", value: 0 },
  11604. "enableReflection": { type: "i", value: 0 },
  11605. "enableDisplacement": { type: "i", value: 0 },
  11606. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11607. "tDiffuse" : { type: "t", value: null },
  11608. "tCube" : { type: "t", value: null },
  11609. "tNormal" : { type: "t", value: null },
  11610. "tSpecular" : { type: "t", value: null },
  11611. "tAO" : { type: "t", value: null },
  11612. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11613. "uDisplacementBias": { type: "f", value: 0.0 },
  11614. "uDisplacementScale": { type: "f", value: 1.0 },
  11615. "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) },
  11616. "specular": { type: "c", value: new THREE.Color( 0x111111 ) },
  11617. "ambient": { type: "c", value: new THREE.Color( 0xffffff ) },
  11618. "shininess": { type: "f", value: 30 },
  11619. "opacity": { type: "f", value: 1 },
  11620. "useRefract": { type: "i", value: 0 },
  11621. "refractionRatio": { type: "f", value: 0.98 },
  11622. "reflectivity": { type: "f", value: 0.5 },
  11623. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11624. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11625. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11626. }
  11627. ] ),
  11628. fragmentShader: [
  11629. "uniform vec3 ambient;",
  11630. "uniform vec3 diffuse;",
  11631. "uniform vec3 specular;",
  11632. "uniform float shininess;",
  11633. "uniform float opacity;",
  11634. "uniform bool enableDiffuse;",
  11635. "uniform bool enableSpecular;",
  11636. "uniform bool enableAO;",
  11637. "uniform bool enableReflection;",
  11638. "uniform sampler2D tDiffuse;",
  11639. "uniform sampler2D tNormal;",
  11640. "uniform sampler2D tSpecular;",
  11641. "uniform sampler2D tAO;",
  11642. "uniform samplerCube tCube;",
  11643. "uniform vec2 uNormalScale;",
  11644. "uniform bool useRefract;",
  11645. "uniform float refractionRatio;",
  11646. "uniform float reflectivity;",
  11647. "varying vec3 vTangent;",
  11648. "varying vec3 vBinormal;",
  11649. "varying vec3 vNormal;",
  11650. "varying vec2 vUv;",
  11651. "uniform vec3 ambientLightColor;",
  11652. "#if MAX_DIR_LIGHTS > 0",
  11653. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11654. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11655. "#endif",
  11656. "#if MAX_HEMI_LIGHTS > 0",
  11657. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11658. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11659. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11660. "#endif",
  11661. "#if MAX_POINT_LIGHTS > 0",
  11662. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11663. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11664. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11665. "#endif",
  11666. "#if MAX_SPOT_LIGHTS > 0",
  11667. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11668. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11669. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11670. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11671. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11672. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11673. "#endif",
  11674. "#ifdef WRAP_AROUND",
  11675. "uniform vec3 wrapRGB;",
  11676. "#endif",
  11677. "varying vec3 vWorldPosition;",
  11678. "varying vec3 vViewPosition;",
  11679. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11680. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11681. "void main() {",
  11682. "gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11683. "vec3 specularTex = vec3( 1.0 );",
  11684. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11685. "normalTex.xy *= uNormalScale;",
  11686. "normalTex = normalize( normalTex );",
  11687. "if( enableDiffuse ) {",
  11688. "#ifdef GAMMA_INPUT",
  11689. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11690. "texelColor.xyz *= texelColor.xyz;",
  11691. "gl_FragColor = gl_FragColor * texelColor;",
  11692. "#else",
  11693. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11694. "#endif",
  11695. "}",
  11696. "if( enableAO ) {",
  11697. "#ifdef GAMMA_INPUT",
  11698. "vec4 aoColor = texture2D( tAO, vUv );",
  11699. "aoColor.xyz *= aoColor.xyz;",
  11700. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11701. "#else",
  11702. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11703. "#endif",
  11704. "}",
  11705. "if( enableSpecular )",
  11706. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11707. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11708. "vec3 finalNormal = tsb * normalTex;",
  11709. "#ifdef FLIP_SIDED",
  11710. "finalNormal = -finalNormal;",
  11711. "#endif",
  11712. "vec3 normal = normalize( finalNormal );",
  11713. "vec3 viewPosition = normalize( vViewPosition );",
  11714. // point lights
  11715. "#if MAX_POINT_LIGHTS > 0",
  11716. "vec3 pointDiffuse = vec3( 0.0 );",
  11717. "vec3 pointSpecular = vec3( 0.0 );",
  11718. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11719. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11720. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11721. "float pointDistance = 1.0;",
  11722. "if ( pointLightDistance[ i ] > 0.0 )",
  11723. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11724. "pointVector = normalize( pointVector );",
  11725. // diffuse
  11726. "#ifdef WRAP_AROUND",
  11727. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11728. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11729. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11730. "#else",
  11731. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11732. "#endif",
  11733. "pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;",
  11734. // specular
  11735. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11736. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11737. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  11738. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11739. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11740. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11741. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11742. "}",
  11743. "#endif",
  11744. // spot lights
  11745. "#if MAX_SPOT_LIGHTS > 0",
  11746. "vec3 spotDiffuse = vec3( 0.0 );",
  11747. "vec3 spotSpecular = vec3( 0.0 );",
  11748. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11749. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11750. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11751. "float spotDistance = 1.0;",
  11752. "if ( spotLightDistance[ i ] > 0.0 )",
  11753. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11754. "spotVector = normalize( spotVector );",
  11755. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11756. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11757. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11758. // diffuse
  11759. "#ifdef WRAP_AROUND",
  11760. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11761. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11762. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11763. "#else",
  11764. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11765. "#endif",
  11766. "spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;",
  11767. // specular
  11768. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11769. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11770. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  11771. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11772. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11773. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11774. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11775. "}",
  11776. "}",
  11777. "#endif",
  11778. // directional lights
  11779. "#if MAX_DIR_LIGHTS > 0",
  11780. "vec3 dirDiffuse = vec3( 0.0 );",
  11781. "vec3 dirSpecular = vec3( 0.0 );",
  11782. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11783. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11784. "vec3 dirVector = normalize( lDirection.xyz );",
  11785. // diffuse
  11786. "#ifdef WRAP_AROUND",
  11787. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11788. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11789. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11790. "#else",
  11791. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11792. "#endif",
  11793. "dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;",
  11794. // specular
  11795. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11796. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11797. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  11798. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11799. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11800. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11801. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11802. "}",
  11803. "#endif",
  11804. // hemisphere lights
  11805. "#if MAX_HEMI_LIGHTS > 0",
  11806. "vec3 hemiDiffuse = vec3( 0.0 );",
  11807. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11808. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11809. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11810. "vec3 lVector = normalize( lDirection.xyz );",
  11811. // diffuse
  11812. "float dotProduct = dot( normal, lVector );",
  11813. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11814. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11815. "hemiDiffuse += diffuse * hemiColor;",
  11816. // specular (sky light)
  11817. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11818. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11819. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  11820. // specular (ground light)
  11821. "vec3 lVectorGround = -lVector;",
  11822. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11823. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11824. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  11825. "float dotProductGround = dot( normal, lVectorGround );",
  11826. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11827. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11828. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11829. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11830. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11831. "}",
  11832. "#endif",
  11833. // all lights contribution summation
  11834. "vec3 totalDiffuse = vec3( 0.0 );",
  11835. "vec3 totalSpecular = vec3( 0.0 );",
  11836. "#if MAX_DIR_LIGHTS > 0",
  11837. "totalDiffuse += dirDiffuse;",
  11838. "totalSpecular += dirSpecular;",
  11839. "#endif",
  11840. "#if MAX_HEMI_LIGHTS > 0",
  11841. "totalDiffuse += hemiDiffuse;",
  11842. "totalSpecular += hemiSpecular;",
  11843. "#endif",
  11844. "#if MAX_POINT_LIGHTS > 0",
  11845. "totalDiffuse += pointDiffuse;",
  11846. "totalSpecular += pointSpecular;",
  11847. "#endif",
  11848. "#if MAX_SPOT_LIGHTS > 0",
  11849. "totalDiffuse += spotDiffuse;",
  11850. "totalSpecular += spotSpecular;",
  11851. "#endif",
  11852. "#ifdef METAL",
  11853. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  11854. "#else",
  11855. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  11856. "#endif",
  11857. "if ( enableReflection ) {",
  11858. "vec3 vReflect;",
  11859. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11860. "if ( useRefract ) {",
  11861. "vReflect = refract( cameraToVertex, normal, refractionRatio );",
  11862. "} else {",
  11863. "vReflect = reflect( cameraToVertex, normal );",
  11864. "}",
  11865. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11866. "#ifdef GAMMA_INPUT",
  11867. "cubeColor.xyz *= cubeColor.xyz;",
  11868. "#endif",
  11869. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );",
  11870. "}",
  11871. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11872. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11873. THREE.ShaderChunk[ "fog_fragment" ],
  11874. "}"
  11875. ].join("\n"),
  11876. vertexShader: [
  11877. "attribute vec4 tangent;",
  11878. "uniform vec2 uOffset;",
  11879. "uniform vec2 uRepeat;",
  11880. "uniform bool enableDisplacement;",
  11881. "#ifdef VERTEX_TEXTURES",
  11882. "uniform sampler2D tDisplacement;",
  11883. "uniform float uDisplacementScale;",
  11884. "uniform float uDisplacementBias;",
  11885. "#endif",
  11886. "varying vec3 vTangent;",
  11887. "varying vec3 vBinormal;",
  11888. "varying vec3 vNormal;",
  11889. "varying vec2 vUv;",
  11890. "varying vec3 vWorldPosition;",
  11891. "varying vec3 vViewPosition;",
  11892. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11893. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11894. "void main() {",
  11895. THREE.ShaderChunk[ "skinbase_vertex" ],
  11896. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11897. // normal, tangent and binormal vectors
  11898. "#ifdef USE_SKINNING",
  11899. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11900. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11901. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11902. "#else",
  11903. "vNormal = normalize( normalMatrix * normal );",
  11904. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11905. "#endif",
  11906. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11907. "vUv = uv * uRepeat + uOffset;",
  11908. // displacement mapping
  11909. "vec3 displacedPosition;",
  11910. "#ifdef VERTEX_TEXTURES",
  11911. "if ( enableDisplacement ) {",
  11912. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11913. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11914. "displacedPosition = position + normalize( normal ) * df;",
  11915. "} else {",
  11916. "#ifdef USE_SKINNING",
  11917. "vec4 skinVertex = vec4( position, 1.0 );",
  11918. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11919. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11920. "displacedPosition = skinned.xyz;",
  11921. "#else",
  11922. "displacedPosition = position;",
  11923. "#endif",
  11924. "}",
  11925. "#else",
  11926. "#ifdef USE_SKINNING",
  11927. "vec4 skinVertex = vec4( position, 1.0 );",
  11928. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11929. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11930. "displacedPosition = skinned.xyz;",
  11931. "#else",
  11932. "displacedPosition = position;",
  11933. "#endif",
  11934. "#endif",
  11935. //
  11936. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11937. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11938. "gl_Position = projectionMatrix * mvPosition;",
  11939. //
  11940. "vWorldPosition = worldPosition.xyz;",
  11941. "vViewPosition = -mvPosition.xyz;",
  11942. // shadows
  11943. "#ifdef USE_SHADOWMAP",
  11944. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11945. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11946. "}",
  11947. "#endif",
  11948. "}"
  11949. ].join("\n")
  11950. },
  11951. /* -------------------------------------------------------------------------
  11952. // Cube map shader
  11953. ------------------------------------------------------------------------- */
  11954. 'cube': {
  11955. uniforms: { "tCube": { type: "t", value: null },
  11956. "tFlip": { type: "f", value: -1 } },
  11957. vertexShader: [
  11958. "varying vec3 vWorldPosition;",
  11959. "void main() {",
  11960. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11961. "vWorldPosition = worldPosition.xyz;",
  11962. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11963. "}"
  11964. ].join("\n"),
  11965. fragmentShader: [
  11966. "uniform samplerCube tCube;",
  11967. "uniform float tFlip;",
  11968. "varying vec3 vWorldPosition;",
  11969. "void main() {",
  11970. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11971. "}"
  11972. ].join("\n")
  11973. },
  11974. // Depth encoding into RGBA texture
  11975. // based on SpiderGL shadow map example
  11976. // http://spidergl.org/example.php?id=6
  11977. // originally from
  11978. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11979. // see also here:
  11980. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11981. 'depthRGBA': {
  11982. uniforms: {},
  11983. vertexShader: [
  11984. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11985. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11986. "void main() {",
  11987. THREE.ShaderChunk[ "skinbase_vertex" ],
  11988. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11989. THREE.ShaderChunk[ "skinning_vertex" ],
  11990. THREE.ShaderChunk[ "default_vertex" ],
  11991. "}"
  11992. ].join("\n"),
  11993. fragmentShader: [
  11994. "vec4 pack_depth( const in float depth ) {",
  11995. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11996. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11997. "vec4 res = fract( depth * bit_shift );",
  11998. "res -= res.xxyz * bit_mask;",
  11999. "return res;",
  12000. "}",
  12001. "void main() {",
  12002. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  12003. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  12004. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  12005. //"gl_FragData[ 0 ] = pack_depth( z );",
  12006. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  12007. "}"
  12008. ].join("\n")
  12009. }
  12010. };
  12011. /**
  12012. * @author supereggbert / http://www.paulbrunt.co.uk/
  12013. * @author mrdoob / http://mrdoob.com/
  12014. * @author alteredq / http://alteredqualia.com/
  12015. * @author szimek / https://github.com/szimek/
  12016. */
  12017. THREE.WebGLRenderer = function ( parameters ) {
  12018. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  12019. parameters = parameters || {};
  12020. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  12021. _context = parameters.context !== undefined ? parameters.context : null,
  12022. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  12023. _buffers = {},
  12024. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  12025. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  12026. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  12027. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  12028. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  12029. _clearColor = new THREE.Color( 0x000000 ),
  12030. _clearAlpha = 0;
  12031. // public properties
  12032. this.domElement = _canvas;
  12033. this.context = null;
  12034. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  12035. ? parameters.devicePixelRatio
  12036. : self.devicePixelRatio !== undefined
  12037. ? self.devicePixelRatio
  12038. : 1;
  12039. // clearing
  12040. this.autoClear = true;
  12041. this.autoClearColor = true;
  12042. this.autoClearDepth = true;
  12043. this.autoClearStencil = true;
  12044. // scene graph
  12045. this.sortObjects = true;
  12046. this.autoUpdateObjects = true;
  12047. // physically based shading
  12048. this.gammaInput = false;
  12049. this.gammaOutput = false;
  12050. // shadow map
  12051. this.shadowMapEnabled = false;
  12052. this.shadowMapAutoUpdate = true;
  12053. this.shadowMapType = THREE.PCFShadowMap;
  12054. this.shadowMapCullFace = THREE.CullFaceFront;
  12055. this.shadowMapDebug = false;
  12056. this.shadowMapCascade = false;
  12057. // morphs
  12058. this.maxMorphTargets = 8;
  12059. this.maxMorphNormals = 4;
  12060. // flags
  12061. this.autoScaleCubemaps = true;
  12062. // custom render plugins
  12063. this.renderPluginsPre = [];
  12064. this.renderPluginsPost = [];
  12065. // info
  12066. this.info = {
  12067. memory: {
  12068. programs: 0,
  12069. geometries: 0,
  12070. textures: 0
  12071. },
  12072. render: {
  12073. calls: 0,
  12074. vertices: 0,
  12075. faces: 0,
  12076. points: 0
  12077. }
  12078. };
  12079. // internal properties
  12080. var _this = this,
  12081. _programs = [],
  12082. _programs_counter = 0,
  12083. // internal state cache
  12084. _currentProgram = null,
  12085. _currentFramebuffer = null,
  12086. _currentMaterialId = -1,
  12087. _currentGeometryGroupHash = null,
  12088. _currentCamera = null,
  12089. _usedTextureUnits = 0,
  12090. // GL state cache
  12091. _oldDoubleSided = -1,
  12092. _oldFlipSided = -1,
  12093. _oldBlending = -1,
  12094. _oldBlendEquation = -1,
  12095. _oldBlendSrc = -1,
  12096. _oldBlendDst = -1,
  12097. _oldDepthTest = -1,
  12098. _oldDepthWrite = -1,
  12099. _oldPolygonOffset = null,
  12100. _oldPolygonOffsetFactor = null,
  12101. _oldPolygonOffsetUnits = null,
  12102. _oldLineWidth = null,
  12103. _viewportX = 0,
  12104. _viewportY = 0,
  12105. _viewportWidth = _canvas.width,
  12106. _viewportHeight = _canvas.height,
  12107. _currentWidth = 0,
  12108. _currentHeight = 0,
  12109. _enabledAttributes = new Uint8Array( 16 ),
  12110. // frustum
  12111. _frustum = new THREE.Frustum(),
  12112. // camera matrices cache
  12113. _projScreenMatrix = new THREE.Matrix4(),
  12114. _projScreenMatrixPS = new THREE.Matrix4(),
  12115. _vector3 = new THREE.Vector3(),
  12116. // light arrays cache
  12117. _direction = new THREE.Vector3(),
  12118. _lightsNeedUpdate = true,
  12119. _lights = {
  12120. ambient: [ 0, 0, 0 ],
  12121. directional: { length: 0, colors: new Array(), positions: new Array() },
  12122. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  12123. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  12124. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  12125. };
  12126. // initialize
  12127. var _gl;
  12128. var _glExtensionTextureFloat;
  12129. var _glExtensionTextureFloatLinear;
  12130. var _glExtensionStandardDerivatives;
  12131. var _glExtensionTextureFilterAnisotropic;
  12132. var _glExtensionCompressedTextureS3TC;
  12133. initGL();
  12134. setDefaultGLState();
  12135. this.context = _gl;
  12136. // GPU capabilities
  12137. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  12138. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  12139. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  12140. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  12141. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  12142. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  12143. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  12144. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  12145. //
  12146. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  12147. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  12148. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  12149. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  12150. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  12151. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  12152. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  12153. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  12154. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  12155. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  12156. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  12157. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  12158. // clamp precision to maximum available
  12159. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  12160. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  12161. if ( _precision === "highp" && ! highpAvailable ) {
  12162. if ( mediumpAvailable ) {
  12163. _precision = "mediump";
  12164. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  12165. } else {
  12166. _precision = "lowp";
  12167. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  12168. }
  12169. }
  12170. if ( _precision === "mediump" && ! mediumpAvailable ) {
  12171. _precision = "lowp";
  12172. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  12173. }
  12174. // API
  12175. this.getContext = function () {
  12176. return _gl;
  12177. };
  12178. this.supportsVertexTextures = function () {
  12179. return _supportsVertexTextures;
  12180. };
  12181. this.supportsFloatTextures = function () {
  12182. return _glExtensionTextureFloat;
  12183. };
  12184. this.supportsStandardDerivatives = function () {
  12185. return _glExtensionStandardDerivatives;
  12186. };
  12187. this.supportsCompressedTextureS3TC = function () {
  12188. return _glExtensionCompressedTextureS3TC;
  12189. };
  12190. this.getMaxAnisotropy = function () {
  12191. return _maxAnisotropy;
  12192. };
  12193. this.getPrecision = function () {
  12194. return _precision;
  12195. };
  12196. this.setSize = function ( width, height, updateStyle ) {
  12197. _canvas.width = width * this.devicePixelRatio;
  12198. _canvas.height = height * this.devicePixelRatio;
  12199. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  12200. _canvas.style.width = width + 'px';
  12201. _canvas.style.height = height + 'px';
  12202. }
  12203. this.setViewport( 0, 0, width, height );
  12204. };
  12205. this.setViewport = function ( x, y, width, height ) {
  12206. _viewportX = x * this.devicePixelRatio;
  12207. _viewportY = y * this.devicePixelRatio;
  12208. _viewportWidth = width * this.devicePixelRatio;
  12209. _viewportHeight = height * this.devicePixelRatio;
  12210. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  12211. };
  12212. this.setScissor = function ( x, y, width, height ) {
  12213. _gl.scissor(
  12214. x * this.devicePixelRatio,
  12215. y * this.devicePixelRatio,
  12216. width * this.devicePixelRatio,
  12217. height * this.devicePixelRatio
  12218. );
  12219. };
  12220. this.enableScissorTest = function ( enable ) {
  12221. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  12222. };
  12223. // Clearing
  12224. this.setClearColor = function ( color, alpha ) {
  12225. _clearColor.set( color );
  12226. _clearAlpha = alpha !== undefined ? alpha : 1;
  12227. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12228. };
  12229. this.setClearColorHex = function ( hex, alpha ) {
  12230. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  12231. this.setClearColor( hex, alpha );
  12232. };
  12233. this.getClearColor = function () {
  12234. return _clearColor;
  12235. };
  12236. this.getClearAlpha = function () {
  12237. return _clearAlpha;
  12238. };
  12239. this.clear = function ( color, depth, stencil ) {
  12240. var bits = 0;
  12241. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12242. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12243. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12244. _gl.clear( bits );
  12245. };
  12246. this.clearColor = function () {
  12247. _gl.clear( _gl.COLOR_BUFFER_BIT );
  12248. };
  12249. this.clearDepth = function () {
  12250. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  12251. };
  12252. this.clearStencil = function () {
  12253. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  12254. };
  12255. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12256. this.setRenderTarget( renderTarget );
  12257. this.clear( color, depth, stencil );
  12258. };
  12259. // Plugins
  12260. this.addPostPlugin = function ( plugin ) {
  12261. plugin.init( this );
  12262. this.renderPluginsPost.push( plugin );
  12263. };
  12264. this.addPrePlugin = function ( plugin ) {
  12265. plugin.init( this );
  12266. this.renderPluginsPre.push( plugin );
  12267. };
  12268. // Rendering
  12269. this.updateShadowMap = function ( scene, camera ) {
  12270. _currentProgram = null;
  12271. _oldBlending = -1;
  12272. _oldDepthTest = -1;
  12273. _oldDepthWrite = -1;
  12274. _currentGeometryGroupHash = -1;
  12275. _currentMaterialId = -1;
  12276. _lightsNeedUpdate = true;
  12277. _oldDoubleSided = -1;
  12278. _oldFlipSided = -1;
  12279. this.shadowMapPlugin.update( scene, camera );
  12280. };
  12281. // Internal functions
  12282. // Buffer allocation
  12283. function createParticleBuffers ( geometry ) {
  12284. geometry.__webglVertexBuffer = _gl.createBuffer();
  12285. geometry.__webglColorBuffer = _gl.createBuffer();
  12286. _this.info.memory.geometries ++;
  12287. };
  12288. function createLineBuffers ( geometry ) {
  12289. geometry.__webglVertexBuffer = _gl.createBuffer();
  12290. geometry.__webglColorBuffer = _gl.createBuffer();
  12291. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  12292. _this.info.memory.geometries ++;
  12293. };
  12294. function createMeshBuffers ( geometryGroup ) {
  12295. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  12296. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  12297. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  12298. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  12299. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  12300. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  12301. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  12302. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  12303. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  12304. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  12305. var m, ml;
  12306. if ( geometryGroup.numMorphTargets ) {
  12307. geometryGroup.__webglMorphTargetsBuffers = [];
  12308. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12309. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  12310. }
  12311. }
  12312. if ( geometryGroup.numMorphNormals ) {
  12313. geometryGroup.__webglMorphNormalsBuffers = [];
  12314. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12315. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  12316. }
  12317. }
  12318. _this.info.memory.geometries ++;
  12319. };
  12320. // Events
  12321. var onGeometryDispose = function ( event ) {
  12322. var geometry = event.target;
  12323. geometry.removeEventListener( 'dispose', onGeometryDispose );
  12324. deallocateGeometry( geometry );
  12325. };
  12326. var onTextureDispose = function ( event ) {
  12327. var texture = event.target;
  12328. texture.removeEventListener( 'dispose', onTextureDispose );
  12329. deallocateTexture( texture );
  12330. _this.info.memory.textures --;
  12331. };
  12332. var onRenderTargetDispose = function ( event ) {
  12333. var renderTarget = event.target;
  12334. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  12335. deallocateRenderTarget( renderTarget );
  12336. _this.info.memory.textures --;
  12337. };
  12338. var onMaterialDispose = function ( event ) {
  12339. var material = event.target;
  12340. material.removeEventListener( 'dispose', onMaterialDispose );
  12341. deallocateMaterial( material );
  12342. };
  12343. // Buffer deallocation
  12344. var deleteBuffers = function ( geometry ) {
  12345. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  12346. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  12347. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  12348. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  12349. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  12350. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  12351. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  12352. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  12353. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  12354. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  12355. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  12356. // custom attributes
  12357. if ( geometry.__webglCustomAttributesList !== undefined ) {
  12358. for ( var id in geometry.__webglCustomAttributesList ) {
  12359. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  12360. }
  12361. }
  12362. _this.info.memory.geometries --;
  12363. };
  12364. var deallocateGeometry = function ( geometry ) {
  12365. geometry.__webglInit = undefined;
  12366. if ( geometry instanceof THREE.BufferGeometry ) {
  12367. var attributes = geometry.attributes;
  12368. for ( var key in attributes ) {
  12369. if ( attributes[ key ].buffer !== undefined ) {
  12370. _gl.deleteBuffer( attributes[ key ].buffer );
  12371. }
  12372. }
  12373. _this.info.memory.geometries --;
  12374. } else {
  12375. if ( geometry.geometryGroups !== undefined ) {
  12376. for ( var g in geometry.geometryGroups ) {
  12377. var geometryGroup = geometry.geometryGroups[ g ];
  12378. if ( geometryGroup.numMorphTargets !== undefined ) {
  12379. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12380. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  12381. }
  12382. }
  12383. if ( geometryGroup.numMorphNormals !== undefined ) {
  12384. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12385. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  12386. }
  12387. }
  12388. deleteBuffers( geometryGroup );
  12389. }
  12390. } else {
  12391. deleteBuffers( geometry );
  12392. }
  12393. }
  12394. };
  12395. var deallocateTexture = function ( texture ) {
  12396. if ( texture.image && texture.image.__webglTextureCube ) {
  12397. // cube texture
  12398. _gl.deleteTexture( texture.image.__webglTextureCube );
  12399. } else {
  12400. // 2D texture
  12401. if ( ! texture.__webglInit ) return;
  12402. texture.__webglInit = false;
  12403. _gl.deleteTexture( texture.__webglTexture );
  12404. }
  12405. };
  12406. var deallocateRenderTarget = function ( renderTarget ) {
  12407. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  12408. _gl.deleteTexture( renderTarget.__webglTexture );
  12409. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12410. for ( var i = 0; i < 6; i ++ ) {
  12411. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  12412. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  12413. }
  12414. } else {
  12415. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  12416. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  12417. }
  12418. };
  12419. var deallocateMaterial = function ( material ) {
  12420. var program = material.program;
  12421. if ( program === undefined ) return;
  12422. material.program = undefined;
  12423. // only deallocate GL program if this was the last use of shared program
  12424. // assumed there is only single copy of any program in the _programs list
  12425. // (that's how it's constructed)
  12426. var i, il, programInfo;
  12427. var deleteProgram = false;
  12428. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12429. programInfo = _programs[ i ];
  12430. if ( programInfo.program === program ) {
  12431. programInfo.usedTimes --;
  12432. if ( programInfo.usedTimes === 0 ) {
  12433. deleteProgram = true;
  12434. }
  12435. break;
  12436. }
  12437. }
  12438. if ( deleteProgram === true ) {
  12439. // avoid using array.splice, this is costlier than creating new array from scratch
  12440. var newPrograms = [];
  12441. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12442. programInfo = _programs[ i ];
  12443. if ( programInfo.program !== program ) {
  12444. newPrograms.push( programInfo );
  12445. }
  12446. }
  12447. _programs = newPrograms;
  12448. _gl.deleteProgram( program );
  12449. _this.info.memory.programs --;
  12450. }
  12451. };
  12452. // Buffer initialization
  12453. function initCustomAttributes ( geometry, object ) {
  12454. var nvertices = geometry.vertices.length;
  12455. var material = object.material;
  12456. if ( material.attributes ) {
  12457. if ( geometry.__webglCustomAttributesList === undefined ) {
  12458. geometry.__webglCustomAttributesList = [];
  12459. }
  12460. for ( var a in material.attributes ) {
  12461. var attribute = material.attributes[ a ];
  12462. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12463. attribute.__webglInitialized = true;
  12464. var size = 1; // "f" and "i"
  12465. if ( attribute.type === "v2" ) size = 2;
  12466. else if ( attribute.type === "v3" ) size = 3;
  12467. else if ( attribute.type === "v4" ) size = 4;
  12468. else if ( attribute.type === "c" ) size = 3;
  12469. attribute.size = size;
  12470. attribute.array = new Float32Array( nvertices * size );
  12471. attribute.buffer = _gl.createBuffer();
  12472. attribute.buffer.belongsToAttribute = a;
  12473. attribute.needsUpdate = true;
  12474. }
  12475. geometry.__webglCustomAttributesList.push( attribute );
  12476. }
  12477. }
  12478. };
  12479. function initParticleBuffers ( geometry, object ) {
  12480. var nvertices = geometry.vertices.length;
  12481. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12482. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12483. geometry.__sortArray = [];
  12484. geometry.__webglParticleCount = nvertices;
  12485. initCustomAttributes ( geometry, object );
  12486. };
  12487. function initLineBuffers ( geometry, object ) {
  12488. var nvertices = geometry.vertices.length;
  12489. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12490. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12491. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12492. geometry.__webglLineCount = nvertices;
  12493. initCustomAttributes ( geometry, object );
  12494. };
  12495. function initMeshBuffers ( geometryGroup, object ) {
  12496. var geometry = object.geometry,
  12497. faces3 = geometryGroup.faces3,
  12498. nvertices = faces3.length * 3,
  12499. ntris = faces3.length * 1,
  12500. nlines = faces3.length * 3,
  12501. material = getBufferMaterial( object, geometryGroup ),
  12502. uvType = bufferGuessUVType( material ),
  12503. normalType = bufferGuessNormalType( material ),
  12504. vertexColorType = bufferGuessVertexColorType( material );
  12505. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12506. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12507. if ( normalType ) {
  12508. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12509. }
  12510. if ( geometry.hasTangents ) {
  12511. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12512. }
  12513. if ( vertexColorType ) {
  12514. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12515. }
  12516. if ( uvType ) {
  12517. if ( geometry.faceVertexUvs.length > 0 ) {
  12518. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12519. }
  12520. if ( geometry.faceVertexUvs.length > 1 ) {
  12521. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12522. }
  12523. }
  12524. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12525. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12526. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12527. }
  12528. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  12529. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  12530. var m, ml;
  12531. if ( geometryGroup.numMorphTargets ) {
  12532. geometryGroup.__morphTargetsArrays = [];
  12533. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12534. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12535. }
  12536. }
  12537. if ( geometryGroup.numMorphNormals ) {
  12538. geometryGroup.__morphNormalsArrays = [];
  12539. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12540. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12541. }
  12542. }
  12543. geometryGroup.__webglFaceCount = ntris * 3;
  12544. geometryGroup.__webglLineCount = nlines * 2;
  12545. // custom attributes
  12546. if ( material.attributes ) {
  12547. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12548. geometryGroup.__webglCustomAttributesList = [];
  12549. }
  12550. for ( var a in material.attributes ) {
  12551. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12552. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12553. var originalAttribute = material.attributes[ a ];
  12554. var attribute = {};
  12555. for ( var property in originalAttribute ) {
  12556. attribute[ property ] = originalAttribute[ property ];
  12557. }
  12558. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12559. attribute.__webglInitialized = true;
  12560. var size = 1; // "f" and "i"
  12561. if( attribute.type === "v2" ) size = 2;
  12562. else if( attribute.type === "v3" ) size = 3;
  12563. else if( attribute.type === "v4" ) size = 4;
  12564. else if( attribute.type === "c" ) size = 3;
  12565. attribute.size = size;
  12566. attribute.array = new Float32Array( nvertices * size );
  12567. attribute.buffer = _gl.createBuffer();
  12568. attribute.buffer.belongsToAttribute = a;
  12569. originalAttribute.needsUpdate = true;
  12570. attribute.__original = originalAttribute;
  12571. }
  12572. geometryGroup.__webglCustomAttributesList.push( attribute );
  12573. }
  12574. }
  12575. geometryGroup.__inittedArrays = true;
  12576. };
  12577. function getBufferMaterial( object, geometryGroup ) {
  12578. return object.material instanceof THREE.MeshFaceMaterial
  12579. ? object.material.materials[ geometryGroup.materialIndex ]
  12580. : object.material;
  12581. };
  12582. function materialNeedsSmoothNormals ( material ) {
  12583. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12584. };
  12585. function bufferGuessNormalType ( material ) {
  12586. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12587. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12588. return false;
  12589. }
  12590. if ( materialNeedsSmoothNormals( material ) ) {
  12591. return THREE.SmoothShading;
  12592. } else {
  12593. return THREE.FlatShading;
  12594. }
  12595. };
  12596. function bufferGuessVertexColorType( material ) {
  12597. if ( material.vertexColors ) {
  12598. return material.vertexColors;
  12599. }
  12600. return false;
  12601. };
  12602. function bufferGuessUVType( material ) {
  12603. // material must use some texture to require uvs
  12604. if ( material.map ||
  12605. material.lightMap ||
  12606. material.bumpMap ||
  12607. material.normalMap ||
  12608. material.specularMap ||
  12609. material instanceof THREE.ShaderMaterial ) {
  12610. return true;
  12611. }
  12612. return false;
  12613. };
  12614. //
  12615. function initDirectBuffers( geometry ) {
  12616. var a, attribute, type;
  12617. for ( a in geometry.attributes ) {
  12618. if ( a === "index" ) {
  12619. type = _gl.ELEMENT_ARRAY_BUFFER;
  12620. } else {
  12621. type = _gl.ARRAY_BUFFER;
  12622. }
  12623. attribute = geometry.attributes[ a ];
  12624. attribute.buffer = _gl.createBuffer();
  12625. _gl.bindBuffer( type, attribute.buffer );
  12626. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  12627. }
  12628. };
  12629. // Buffer setting
  12630. function setParticleBuffers ( geometry, hint, object ) {
  12631. var v, c, vertex, offset, index, color,
  12632. vertices = geometry.vertices,
  12633. vl = vertices.length,
  12634. colors = geometry.colors,
  12635. cl = colors.length,
  12636. vertexArray = geometry.__vertexArray,
  12637. colorArray = geometry.__colorArray,
  12638. sortArray = geometry.__sortArray,
  12639. dirtyVertices = geometry.verticesNeedUpdate,
  12640. dirtyElements = geometry.elementsNeedUpdate,
  12641. dirtyColors = geometry.colorsNeedUpdate,
  12642. customAttributes = geometry.__webglCustomAttributesList,
  12643. i, il,
  12644. a, ca, cal, value,
  12645. customAttribute;
  12646. if ( object.sortParticles ) {
  12647. _projScreenMatrixPS.copy( _projScreenMatrix );
  12648. _projScreenMatrixPS.multiply( object.matrixWorld );
  12649. for ( v = 0; v < vl; v ++ ) {
  12650. vertex = vertices[ v ];
  12651. _vector3.copy( vertex );
  12652. _vector3.applyProjection( _projScreenMatrixPS );
  12653. sortArray[ v ] = [ _vector3.z, v ];
  12654. }
  12655. sortArray.sort( numericalSort );
  12656. for ( v = 0; v < vl; v ++ ) {
  12657. vertex = vertices[ sortArray[v][1] ];
  12658. offset = v * 3;
  12659. vertexArray[ offset ] = vertex.x;
  12660. vertexArray[ offset + 1 ] = vertex.y;
  12661. vertexArray[ offset + 2 ] = vertex.z;
  12662. }
  12663. for ( c = 0; c < cl; c ++ ) {
  12664. offset = c * 3;
  12665. color = colors[ sortArray[c][1] ];
  12666. colorArray[ offset ] = color.r;
  12667. colorArray[ offset + 1 ] = color.g;
  12668. colorArray[ offset + 2 ] = color.b;
  12669. }
  12670. if ( customAttributes ) {
  12671. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12672. customAttribute = customAttributes[ i ];
  12673. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12674. offset = 0;
  12675. cal = customAttribute.value.length;
  12676. if ( customAttribute.size === 1 ) {
  12677. for ( ca = 0; ca < cal; ca ++ ) {
  12678. index = sortArray[ ca ][ 1 ];
  12679. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12680. }
  12681. } else if ( customAttribute.size === 2 ) {
  12682. for ( ca = 0; ca < cal; ca ++ ) {
  12683. index = sortArray[ ca ][ 1 ];
  12684. value = customAttribute.value[ index ];
  12685. customAttribute.array[ offset ] = value.x;
  12686. customAttribute.array[ offset + 1 ] = value.y;
  12687. offset += 2;
  12688. }
  12689. } else if ( customAttribute.size === 3 ) {
  12690. if ( customAttribute.type === "c" ) {
  12691. for ( ca = 0; ca < cal; ca ++ ) {
  12692. index = sortArray[ ca ][ 1 ];
  12693. value = customAttribute.value[ index ];
  12694. customAttribute.array[ offset ] = value.r;
  12695. customAttribute.array[ offset + 1 ] = value.g;
  12696. customAttribute.array[ offset + 2 ] = value.b;
  12697. offset += 3;
  12698. }
  12699. } else {
  12700. for ( ca = 0; ca < cal; ca ++ ) {
  12701. index = sortArray[ ca ][ 1 ];
  12702. value = customAttribute.value[ index ];
  12703. customAttribute.array[ offset ] = value.x;
  12704. customAttribute.array[ offset + 1 ] = value.y;
  12705. customAttribute.array[ offset + 2 ] = value.z;
  12706. offset += 3;
  12707. }
  12708. }
  12709. } else if ( customAttribute.size === 4 ) {
  12710. for ( ca = 0; ca < cal; ca ++ ) {
  12711. index = sortArray[ ca ][ 1 ];
  12712. value = customAttribute.value[ index ];
  12713. customAttribute.array[ offset ] = value.x;
  12714. customAttribute.array[ offset + 1 ] = value.y;
  12715. customAttribute.array[ offset + 2 ] = value.z;
  12716. customAttribute.array[ offset + 3 ] = value.w;
  12717. offset += 4;
  12718. }
  12719. }
  12720. }
  12721. }
  12722. } else {
  12723. if ( dirtyVertices ) {
  12724. for ( v = 0; v < vl; v ++ ) {
  12725. vertex = vertices[ v ];
  12726. offset = v * 3;
  12727. vertexArray[ offset ] = vertex.x;
  12728. vertexArray[ offset + 1 ] = vertex.y;
  12729. vertexArray[ offset + 2 ] = vertex.z;
  12730. }
  12731. }
  12732. if ( dirtyColors ) {
  12733. for ( c = 0; c < cl; c ++ ) {
  12734. color = colors[ c ];
  12735. offset = c * 3;
  12736. colorArray[ offset ] = color.r;
  12737. colorArray[ offset + 1 ] = color.g;
  12738. colorArray[ offset + 2 ] = color.b;
  12739. }
  12740. }
  12741. if ( customAttributes ) {
  12742. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12743. customAttribute = customAttributes[ i ];
  12744. if ( customAttribute.needsUpdate &&
  12745. ( customAttribute.boundTo === undefined ||
  12746. customAttribute.boundTo === "vertices") ) {
  12747. cal = customAttribute.value.length;
  12748. offset = 0;
  12749. if ( customAttribute.size === 1 ) {
  12750. for ( ca = 0; ca < cal; ca ++ ) {
  12751. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12752. }
  12753. } else if ( customAttribute.size === 2 ) {
  12754. for ( ca = 0; ca < cal; ca ++ ) {
  12755. value = customAttribute.value[ ca ];
  12756. customAttribute.array[ offset ] = value.x;
  12757. customAttribute.array[ offset + 1 ] = value.y;
  12758. offset += 2;
  12759. }
  12760. } else if ( customAttribute.size === 3 ) {
  12761. if ( customAttribute.type === "c" ) {
  12762. for ( ca = 0; ca < cal; ca ++ ) {
  12763. value = customAttribute.value[ ca ];
  12764. customAttribute.array[ offset ] = value.r;
  12765. customAttribute.array[ offset + 1 ] = value.g;
  12766. customAttribute.array[ offset + 2 ] = value.b;
  12767. offset += 3;
  12768. }
  12769. } else {
  12770. for ( ca = 0; ca < cal; ca ++ ) {
  12771. value = customAttribute.value[ ca ];
  12772. customAttribute.array[ offset ] = value.x;
  12773. customAttribute.array[ offset + 1 ] = value.y;
  12774. customAttribute.array[ offset + 2 ] = value.z;
  12775. offset += 3;
  12776. }
  12777. }
  12778. } else if ( customAttribute.size === 4 ) {
  12779. for ( ca = 0; ca < cal; ca ++ ) {
  12780. value = customAttribute.value[ ca ];
  12781. customAttribute.array[ offset ] = value.x;
  12782. customAttribute.array[ offset + 1 ] = value.y;
  12783. customAttribute.array[ offset + 2 ] = value.z;
  12784. customAttribute.array[ offset + 3 ] = value.w;
  12785. offset += 4;
  12786. }
  12787. }
  12788. }
  12789. }
  12790. }
  12791. }
  12792. if ( dirtyVertices || object.sortParticles ) {
  12793. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12794. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12795. }
  12796. if ( dirtyColors || object.sortParticles ) {
  12797. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12798. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12799. }
  12800. if ( customAttributes ) {
  12801. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12802. customAttribute = customAttributes[ i ];
  12803. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12804. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12805. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12806. }
  12807. }
  12808. }
  12809. };
  12810. function setLineBuffers ( geometry, hint ) {
  12811. var v, c, d, vertex, offset, color,
  12812. vertices = geometry.vertices,
  12813. colors = geometry.colors,
  12814. lineDistances = geometry.lineDistances,
  12815. vl = vertices.length,
  12816. cl = colors.length,
  12817. dl = lineDistances.length,
  12818. vertexArray = geometry.__vertexArray,
  12819. colorArray = geometry.__colorArray,
  12820. lineDistanceArray = geometry.__lineDistanceArray,
  12821. dirtyVertices = geometry.verticesNeedUpdate,
  12822. dirtyColors = geometry.colorsNeedUpdate,
  12823. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12824. customAttributes = geometry.__webglCustomAttributesList,
  12825. i, il,
  12826. a, ca, cal, value,
  12827. customAttribute;
  12828. if ( dirtyVertices ) {
  12829. for ( v = 0; v < vl; v ++ ) {
  12830. vertex = vertices[ v ];
  12831. offset = v * 3;
  12832. vertexArray[ offset ] = vertex.x;
  12833. vertexArray[ offset + 1 ] = vertex.y;
  12834. vertexArray[ offset + 2 ] = vertex.z;
  12835. }
  12836. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12837. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12838. }
  12839. if ( dirtyColors ) {
  12840. for ( c = 0; c < cl; c ++ ) {
  12841. color = colors[ c ];
  12842. offset = c * 3;
  12843. colorArray[ offset ] = color.r;
  12844. colorArray[ offset + 1 ] = color.g;
  12845. colorArray[ offset + 2 ] = color.b;
  12846. }
  12847. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12848. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12849. }
  12850. if ( dirtyLineDistances ) {
  12851. for ( d = 0; d < dl; d ++ ) {
  12852. lineDistanceArray[ d ] = lineDistances[ d ];
  12853. }
  12854. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12855. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12856. }
  12857. if ( customAttributes ) {
  12858. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12859. customAttribute = customAttributes[ i ];
  12860. if ( customAttribute.needsUpdate &&
  12861. ( customAttribute.boundTo === undefined ||
  12862. customAttribute.boundTo === "vertices" ) ) {
  12863. offset = 0;
  12864. cal = customAttribute.value.length;
  12865. if ( customAttribute.size === 1 ) {
  12866. for ( ca = 0; ca < cal; ca ++ ) {
  12867. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12868. }
  12869. } else if ( customAttribute.size === 2 ) {
  12870. for ( ca = 0; ca < cal; ca ++ ) {
  12871. value = customAttribute.value[ ca ];
  12872. customAttribute.array[ offset ] = value.x;
  12873. customAttribute.array[ offset + 1 ] = value.y;
  12874. offset += 2;
  12875. }
  12876. } else if ( customAttribute.size === 3 ) {
  12877. if ( customAttribute.type === "c" ) {
  12878. for ( ca = 0; ca < cal; ca ++ ) {
  12879. value = customAttribute.value[ ca ];
  12880. customAttribute.array[ offset ] = value.r;
  12881. customAttribute.array[ offset + 1 ] = value.g;
  12882. customAttribute.array[ offset + 2 ] = value.b;
  12883. offset += 3;
  12884. }
  12885. } else {
  12886. for ( ca = 0; ca < cal; ca ++ ) {
  12887. value = customAttribute.value[ ca ];
  12888. customAttribute.array[ offset ] = value.x;
  12889. customAttribute.array[ offset + 1 ] = value.y;
  12890. customAttribute.array[ offset + 2 ] = value.z;
  12891. offset += 3;
  12892. }
  12893. }
  12894. } else if ( customAttribute.size === 4 ) {
  12895. for ( ca = 0; ca < cal; ca ++ ) {
  12896. value = customAttribute.value[ ca ];
  12897. customAttribute.array[ offset ] = value.x;
  12898. customAttribute.array[ offset + 1 ] = value.y;
  12899. customAttribute.array[ offset + 2 ] = value.z;
  12900. customAttribute.array[ offset + 3 ] = value.w;
  12901. offset += 4;
  12902. }
  12903. }
  12904. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12905. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12906. }
  12907. }
  12908. }
  12909. };
  12910. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12911. if ( ! geometryGroup.__inittedArrays ) {
  12912. return;
  12913. }
  12914. var normalType = bufferGuessNormalType( material ),
  12915. vertexColorType = bufferGuessVertexColorType( material ),
  12916. uvType = bufferGuessUVType( material ),
  12917. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12918. var f, fl, fi, face,
  12919. vertexNormals, faceNormal, normal,
  12920. vertexColors, faceColor,
  12921. vertexTangents,
  12922. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12923. c1, c2, c3, c4,
  12924. sw1, sw2, sw3, sw4,
  12925. si1, si2, si3, si4,
  12926. sa1, sa2, sa3, sa4,
  12927. sb1, sb2, sb3, sb4,
  12928. m, ml, i, il,
  12929. vn, uvi, uv2i,
  12930. vk, vkl, vka,
  12931. nka, chf, faceVertexNormals,
  12932. a,
  12933. vertexIndex = 0,
  12934. offset = 0,
  12935. offset_uv = 0,
  12936. offset_uv2 = 0,
  12937. offset_face = 0,
  12938. offset_normal = 0,
  12939. offset_tangent = 0,
  12940. offset_line = 0,
  12941. offset_color = 0,
  12942. offset_skin = 0,
  12943. offset_morphTarget = 0,
  12944. offset_custom = 0,
  12945. offset_customSrc = 0,
  12946. value,
  12947. vertexArray = geometryGroup.__vertexArray,
  12948. uvArray = geometryGroup.__uvArray,
  12949. uv2Array = geometryGroup.__uv2Array,
  12950. normalArray = geometryGroup.__normalArray,
  12951. tangentArray = geometryGroup.__tangentArray,
  12952. colorArray = geometryGroup.__colorArray,
  12953. skinIndexArray = geometryGroup.__skinIndexArray,
  12954. skinWeightArray = geometryGroup.__skinWeightArray,
  12955. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12956. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12957. customAttributes = geometryGroup.__webglCustomAttributesList,
  12958. customAttribute,
  12959. faceArray = geometryGroup.__faceArray,
  12960. lineArray = geometryGroup.__lineArray,
  12961. geometry = object.geometry, // this is shared for all chunks
  12962. dirtyVertices = geometry.verticesNeedUpdate,
  12963. dirtyElements = geometry.elementsNeedUpdate,
  12964. dirtyUvs = geometry.uvsNeedUpdate,
  12965. dirtyNormals = geometry.normalsNeedUpdate,
  12966. dirtyTangents = geometry.tangentsNeedUpdate,
  12967. dirtyColors = geometry.colorsNeedUpdate,
  12968. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12969. vertices = geometry.vertices,
  12970. chunk_faces3 = geometryGroup.faces3,
  12971. obj_faces = geometry.faces,
  12972. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12973. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12974. obj_colors = geometry.colors,
  12975. obj_skinIndices = geometry.skinIndices,
  12976. obj_skinWeights = geometry.skinWeights,
  12977. morphTargets = geometry.morphTargets,
  12978. morphNormals = geometry.morphNormals;
  12979. if ( dirtyVertices ) {
  12980. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12981. face = obj_faces[ chunk_faces3[ f ] ];
  12982. v1 = vertices[ face.a ];
  12983. v2 = vertices[ face.b ];
  12984. v3 = vertices[ face.c ];
  12985. vertexArray[ offset ] = v1.x;
  12986. vertexArray[ offset + 1 ] = v1.y;
  12987. vertexArray[ offset + 2 ] = v1.z;
  12988. vertexArray[ offset + 3 ] = v2.x;
  12989. vertexArray[ offset + 4 ] = v2.y;
  12990. vertexArray[ offset + 5 ] = v2.z;
  12991. vertexArray[ offset + 6 ] = v3.x;
  12992. vertexArray[ offset + 7 ] = v3.y;
  12993. vertexArray[ offset + 8 ] = v3.z;
  12994. offset += 9;
  12995. }
  12996. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12997. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12998. }
  12999. if ( dirtyMorphTargets ) {
  13000. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  13001. offset_morphTarget = 0;
  13002. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13003. chf = chunk_faces3[ f ];
  13004. face = obj_faces[ chf ];
  13005. // morph positions
  13006. v1 = morphTargets[ vk ].vertices[ face.a ];
  13007. v2 = morphTargets[ vk ].vertices[ face.b ];
  13008. v3 = morphTargets[ vk ].vertices[ face.c ];
  13009. vka = morphTargetsArrays[ vk ];
  13010. vka[ offset_morphTarget ] = v1.x;
  13011. vka[ offset_morphTarget + 1 ] = v1.y;
  13012. vka[ offset_morphTarget + 2 ] = v1.z;
  13013. vka[ offset_morphTarget + 3 ] = v2.x;
  13014. vka[ offset_morphTarget + 4 ] = v2.y;
  13015. vka[ offset_morphTarget + 5 ] = v2.z;
  13016. vka[ offset_morphTarget + 6 ] = v3.x;
  13017. vka[ offset_morphTarget + 7 ] = v3.y;
  13018. vka[ offset_morphTarget + 8 ] = v3.z;
  13019. // morph normals
  13020. if ( material.morphNormals ) {
  13021. if ( needsSmoothNormals ) {
  13022. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  13023. n1 = faceVertexNormals.a;
  13024. n2 = faceVertexNormals.b;
  13025. n3 = faceVertexNormals.c;
  13026. } else {
  13027. n1 = morphNormals[ vk ].faceNormals[ chf ];
  13028. n2 = n1;
  13029. n3 = n1;
  13030. }
  13031. nka = morphNormalsArrays[ vk ];
  13032. nka[ offset_morphTarget ] = n1.x;
  13033. nka[ offset_morphTarget + 1 ] = n1.y;
  13034. nka[ offset_morphTarget + 2 ] = n1.z;
  13035. nka[ offset_morphTarget + 3 ] = n2.x;
  13036. nka[ offset_morphTarget + 4 ] = n2.y;
  13037. nka[ offset_morphTarget + 5 ] = n2.z;
  13038. nka[ offset_morphTarget + 6 ] = n3.x;
  13039. nka[ offset_morphTarget + 7 ] = n3.y;
  13040. nka[ offset_morphTarget + 8 ] = n3.z;
  13041. }
  13042. //
  13043. offset_morphTarget += 9;
  13044. }
  13045. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  13046. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  13047. if ( material.morphNormals ) {
  13048. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  13049. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  13050. }
  13051. }
  13052. }
  13053. if ( obj_skinWeights.length ) {
  13054. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13055. face = obj_faces[ chunk_faces3[ f ] ];
  13056. // weights
  13057. sw1 = obj_skinWeights[ face.a ];
  13058. sw2 = obj_skinWeights[ face.b ];
  13059. sw3 = obj_skinWeights[ face.c ];
  13060. skinWeightArray[ offset_skin ] = sw1.x;
  13061. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  13062. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  13063. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  13064. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  13065. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  13066. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  13067. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  13068. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  13069. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  13070. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  13071. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  13072. // indices
  13073. si1 = obj_skinIndices[ face.a ];
  13074. si2 = obj_skinIndices[ face.b ];
  13075. si3 = obj_skinIndices[ face.c ];
  13076. skinIndexArray[ offset_skin ] = si1.x;
  13077. skinIndexArray[ offset_skin + 1 ] = si1.y;
  13078. skinIndexArray[ offset_skin + 2 ] = si1.z;
  13079. skinIndexArray[ offset_skin + 3 ] = si1.w;
  13080. skinIndexArray[ offset_skin + 4 ] = si2.x;
  13081. skinIndexArray[ offset_skin + 5 ] = si2.y;
  13082. skinIndexArray[ offset_skin + 6 ] = si2.z;
  13083. skinIndexArray[ offset_skin + 7 ] = si2.w;
  13084. skinIndexArray[ offset_skin + 8 ] = si3.x;
  13085. skinIndexArray[ offset_skin + 9 ] = si3.y;
  13086. skinIndexArray[ offset_skin + 10 ] = si3.z;
  13087. skinIndexArray[ offset_skin + 11 ] = si3.w;
  13088. offset_skin += 12;
  13089. }
  13090. if ( offset_skin > 0 ) {
  13091. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13092. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  13093. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13094. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  13095. }
  13096. }
  13097. if ( dirtyColors && vertexColorType ) {
  13098. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13099. face = obj_faces[ chunk_faces3[ f ] ];
  13100. vertexColors = face.vertexColors;
  13101. faceColor = face.color;
  13102. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  13103. c1 = vertexColors[ 0 ];
  13104. c2 = vertexColors[ 1 ];
  13105. c3 = vertexColors[ 2 ];
  13106. } else {
  13107. c1 = faceColor;
  13108. c2 = faceColor;
  13109. c3 = faceColor;
  13110. }
  13111. colorArray[ offset_color ] = c1.r;
  13112. colorArray[ offset_color + 1 ] = c1.g;
  13113. colorArray[ offset_color + 2 ] = c1.b;
  13114. colorArray[ offset_color + 3 ] = c2.r;
  13115. colorArray[ offset_color + 4 ] = c2.g;
  13116. colorArray[ offset_color + 5 ] = c2.b;
  13117. colorArray[ offset_color + 6 ] = c3.r;
  13118. colorArray[ offset_color + 7 ] = c3.g;
  13119. colorArray[ offset_color + 8 ] = c3.b;
  13120. offset_color += 9;
  13121. }
  13122. if ( offset_color > 0 ) {
  13123. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13124. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13125. }
  13126. }
  13127. if ( dirtyTangents && geometry.hasTangents ) {
  13128. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13129. face = obj_faces[ chunk_faces3[ f ] ];
  13130. vertexTangents = face.vertexTangents;
  13131. t1 = vertexTangents[ 0 ];
  13132. t2 = vertexTangents[ 1 ];
  13133. t3 = vertexTangents[ 2 ];
  13134. tangentArray[ offset_tangent ] = t1.x;
  13135. tangentArray[ offset_tangent + 1 ] = t1.y;
  13136. tangentArray[ offset_tangent + 2 ] = t1.z;
  13137. tangentArray[ offset_tangent + 3 ] = t1.w;
  13138. tangentArray[ offset_tangent + 4 ] = t2.x;
  13139. tangentArray[ offset_tangent + 5 ] = t2.y;
  13140. tangentArray[ offset_tangent + 6 ] = t2.z;
  13141. tangentArray[ offset_tangent + 7 ] = t2.w;
  13142. tangentArray[ offset_tangent + 8 ] = t3.x;
  13143. tangentArray[ offset_tangent + 9 ] = t3.y;
  13144. tangentArray[ offset_tangent + 10 ] = t3.z;
  13145. tangentArray[ offset_tangent + 11 ] = t3.w;
  13146. offset_tangent += 12;
  13147. }
  13148. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13149. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  13150. }
  13151. if ( dirtyNormals && normalType ) {
  13152. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13153. face = obj_faces[ chunk_faces3[ f ] ];
  13154. vertexNormals = face.vertexNormals;
  13155. faceNormal = face.normal;
  13156. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  13157. for ( i = 0; i < 3; i ++ ) {
  13158. vn = vertexNormals[ i ];
  13159. normalArray[ offset_normal ] = vn.x;
  13160. normalArray[ offset_normal + 1 ] = vn.y;
  13161. normalArray[ offset_normal + 2 ] = vn.z;
  13162. offset_normal += 3;
  13163. }
  13164. } else {
  13165. for ( i = 0; i < 3; i ++ ) {
  13166. normalArray[ offset_normal ] = faceNormal.x;
  13167. normalArray[ offset_normal + 1 ] = faceNormal.y;
  13168. normalArray[ offset_normal + 2 ] = faceNormal.z;
  13169. offset_normal += 3;
  13170. }
  13171. }
  13172. }
  13173. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13174. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  13175. }
  13176. if ( dirtyUvs && obj_uvs && uvType ) {
  13177. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13178. fi = chunk_faces3[ f ];
  13179. uv = obj_uvs[ fi ];
  13180. if ( uv === undefined ) continue;
  13181. for ( i = 0; i < 3; i ++ ) {
  13182. uvi = uv[ i ];
  13183. uvArray[ offset_uv ] = uvi.x;
  13184. uvArray[ offset_uv + 1 ] = uvi.y;
  13185. offset_uv += 2;
  13186. }
  13187. }
  13188. if ( offset_uv > 0 ) {
  13189. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13190. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  13191. }
  13192. }
  13193. if ( dirtyUvs && obj_uvs2 && uvType ) {
  13194. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13195. fi = chunk_faces3[ f ];
  13196. uv2 = obj_uvs2[ fi ];
  13197. if ( uv2 === undefined ) continue;
  13198. for ( i = 0; i < 3; i ++ ) {
  13199. uv2i = uv2[ i ];
  13200. uv2Array[ offset_uv2 ] = uv2i.x;
  13201. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  13202. offset_uv2 += 2;
  13203. }
  13204. }
  13205. if ( offset_uv2 > 0 ) {
  13206. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13207. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  13208. }
  13209. }
  13210. if ( dirtyElements ) {
  13211. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13212. faceArray[ offset_face ] = vertexIndex;
  13213. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  13214. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  13215. offset_face += 3;
  13216. lineArray[ offset_line ] = vertexIndex;
  13217. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  13218. lineArray[ offset_line + 2 ] = vertexIndex;
  13219. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  13220. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  13221. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  13222. offset_line += 6;
  13223. vertexIndex += 3;
  13224. }
  13225. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13226. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  13227. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13228. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  13229. }
  13230. if ( customAttributes ) {
  13231. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13232. customAttribute = customAttributes[ i ];
  13233. if ( ! customAttribute.__original.needsUpdate ) continue;
  13234. offset_custom = 0;
  13235. offset_customSrc = 0;
  13236. if ( customAttribute.size === 1 ) {
  13237. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13238. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13239. face = obj_faces[ chunk_faces3[ f ] ];
  13240. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13241. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13242. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13243. offset_custom += 3;
  13244. }
  13245. } else if ( customAttribute.boundTo === "faces" ) {
  13246. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13247. value = customAttribute.value[ chunk_faces3[ f ] ];
  13248. customAttribute.array[ offset_custom ] = value;
  13249. customAttribute.array[ offset_custom + 1 ] = value;
  13250. customAttribute.array[ offset_custom + 2 ] = value;
  13251. offset_custom += 3;
  13252. }
  13253. }
  13254. } else if ( customAttribute.size === 2 ) {
  13255. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13256. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13257. face = obj_faces[ chunk_faces3[ f ] ];
  13258. v1 = customAttribute.value[ face.a ];
  13259. v2 = customAttribute.value[ face.b ];
  13260. v3 = customAttribute.value[ face.c ];
  13261. customAttribute.array[ offset_custom ] = v1.x;
  13262. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13263. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13264. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13265. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13266. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13267. offset_custom += 6;
  13268. }
  13269. } else if ( customAttribute.boundTo === "faces" ) {
  13270. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13271. value = customAttribute.value[ chunk_faces3[ f ] ];
  13272. v1 = value;
  13273. v2 = value;
  13274. v3 = value;
  13275. customAttribute.array[ offset_custom ] = v1.x;
  13276. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13277. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13278. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13279. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13280. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13281. offset_custom += 6;
  13282. }
  13283. }
  13284. } else if ( customAttribute.size === 3 ) {
  13285. var pp;
  13286. if ( customAttribute.type === "c" ) {
  13287. pp = [ "r", "g", "b" ];
  13288. } else {
  13289. pp = [ "x", "y", "z" ];
  13290. }
  13291. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13292. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13293. face = obj_faces[ chunk_faces3[ f ] ];
  13294. v1 = customAttribute.value[ face.a ];
  13295. v2 = customAttribute.value[ face.b ];
  13296. v3 = customAttribute.value[ face.c ];
  13297. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13298. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13299. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13300. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13301. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13302. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13303. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13304. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13305. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13306. offset_custom += 9;
  13307. }
  13308. } else if ( customAttribute.boundTo === "faces" ) {
  13309. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13310. value = customAttribute.value[ chunk_faces3[ f ] ];
  13311. v1 = value;
  13312. v2 = value;
  13313. v3 = value;
  13314. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13315. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13316. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13317. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13318. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13319. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13320. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13321. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13322. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13323. offset_custom += 9;
  13324. }
  13325. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13326. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13327. value = customAttribute.value[ chunk_faces3[ f ] ];
  13328. v1 = value[ 0 ];
  13329. v2 = value[ 1 ];
  13330. v3 = value[ 2 ];
  13331. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13332. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13333. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13334. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13335. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13336. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13337. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13338. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13339. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13340. offset_custom += 9;
  13341. }
  13342. }
  13343. } else if ( customAttribute.size === 4 ) {
  13344. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13345. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13346. face = obj_faces[ chunk_faces3[ f ] ];
  13347. v1 = customAttribute.value[ face.a ];
  13348. v2 = customAttribute.value[ face.b ];
  13349. v3 = customAttribute.value[ face.c ];
  13350. customAttribute.array[ offset_custom ] = v1.x;
  13351. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13352. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13353. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13354. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13355. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13356. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13357. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13358. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13359. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13360. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13361. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13362. offset_custom += 12;
  13363. }
  13364. } else if ( customAttribute.boundTo === "faces" ) {
  13365. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13366. value = customAttribute.value[ chunk_faces3[ f ] ];
  13367. v1 = value;
  13368. v2 = value;
  13369. v3 = value;
  13370. customAttribute.array[ offset_custom ] = v1.x;
  13371. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13372. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13373. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13374. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13375. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13376. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13377. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13378. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13379. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13380. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13381. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13382. offset_custom += 12;
  13383. }
  13384. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13385. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13386. value = customAttribute.value[ chunk_faces3[ f ] ];
  13387. v1 = value[ 0 ];
  13388. v2 = value[ 1 ];
  13389. v3 = value[ 2 ];
  13390. customAttribute.array[ offset_custom ] = v1.x;
  13391. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13392. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13393. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13394. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13395. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13396. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13397. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13398. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13399. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13400. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13401. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13402. offset_custom += 12;
  13403. }
  13404. }
  13405. }
  13406. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13407. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13408. }
  13409. }
  13410. if ( dispose ) {
  13411. delete geometryGroup.__inittedArrays;
  13412. delete geometryGroup.__colorArray;
  13413. delete geometryGroup.__normalArray;
  13414. delete geometryGroup.__tangentArray;
  13415. delete geometryGroup.__uvArray;
  13416. delete geometryGroup.__uv2Array;
  13417. delete geometryGroup.__faceArray;
  13418. delete geometryGroup.__vertexArray;
  13419. delete geometryGroup.__lineArray;
  13420. delete geometryGroup.__skinIndexArray;
  13421. delete geometryGroup.__skinWeightArray;
  13422. }
  13423. };
  13424. // used by renderBufferDirect for THREE.Line
  13425. function setupLinesVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
  13426. var attributeItem, attributeName, attributePointer, attributeSize;
  13427. for ( attributeName in programAttributes ) {
  13428. attributePointer = programAttributes[ attributeName ];
  13429. attributeItem = geometryAttributes[ attributeName ];
  13430. if ( attributePointer >= 0 ) {
  13431. if ( attributeItem ) {
  13432. attributeSize = attributeItem.itemSize;
  13433. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13434. enableAttribute( attributePointer );
  13435. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13436. } else if ( material.defaultAttributeValues ) {
  13437. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13438. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13439. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13440. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13441. }
  13442. }
  13443. }
  13444. }
  13445. }
  13446. function setDirectBuffers( geometry, hint ) {
  13447. var attributes = geometry.attributes;
  13448. var attributeName, attributeItem;
  13449. for ( attributeName in attributes ) {
  13450. attributeItem = attributes[ attributeName ];
  13451. if ( attributeItem.needsUpdate ) {
  13452. if ( attributeName === 'index' ) {
  13453. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13454. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13455. } else {
  13456. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13457. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13458. }
  13459. attributeItem.needsUpdate = false;
  13460. }
  13461. }
  13462. }
  13463. // Buffer rendering
  13464. this.renderBufferImmediate = function ( object, program, material ) {
  13465. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13466. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13467. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13468. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13469. if ( object.hasPositions ) {
  13470. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13471. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13472. _gl.enableVertexAttribArray( program.attributes.position );
  13473. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13474. }
  13475. if ( object.hasNormals ) {
  13476. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13477. if ( material.shading === THREE.FlatShading ) {
  13478. var nx, ny, nz,
  13479. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13480. normalArray,
  13481. i, il = object.count * 3;
  13482. for( i = 0; i < il; i += 9 ) {
  13483. normalArray = object.normalArray;
  13484. nax = normalArray[ i ];
  13485. nay = normalArray[ i + 1 ];
  13486. naz = normalArray[ i + 2 ];
  13487. nbx = normalArray[ i + 3 ];
  13488. nby = normalArray[ i + 4 ];
  13489. nbz = normalArray[ i + 5 ];
  13490. ncx = normalArray[ i + 6 ];
  13491. ncy = normalArray[ i + 7 ];
  13492. ncz = normalArray[ i + 8 ];
  13493. nx = ( nax + nbx + ncx ) / 3;
  13494. ny = ( nay + nby + ncy ) / 3;
  13495. nz = ( naz + nbz + ncz ) / 3;
  13496. normalArray[ i ] = nx;
  13497. normalArray[ i + 1 ] = ny;
  13498. normalArray[ i + 2 ] = nz;
  13499. normalArray[ i + 3 ] = nx;
  13500. normalArray[ i + 4 ] = ny;
  13501. normalArray[ i + 5 ] = nz;
  13502. normalArray[ i + 6 ] = nx;
  13503. normalArray[ i + 7 ] = ny;
  13504. normalArray[ i + 8 ] = nz;
  13505. }
  13506. }
  13507. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13508. _gl.enableVertexAttribArray( program.attributes.normal );
  13509. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13510. }
  13511. if ( object.hasUvs && material.map ) {
  13512. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13513. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13514. _gl.enableVertexAttribArray( program.attributes.uv );
  13515. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13516. }
  13517. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13518. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13519. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13520. _gl.enableVertexAttribArray( program.attributes.color );
  13521. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13522. }
  13523. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13524. object.count = 0;
  13525. };
  13526. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13527. if ( material.visible === false ) return;
  13528. var linewidth, a, attribute;
  13529. var attributeItem, attributeName, attributePointer, attributeSize;
  13530. var program = setProgram( camera, lights, fog, material, object );
  13531. var programAttributes = program.attributes;
  13532. var geometryAttributes = geometry.attributes;
  13533. var updateBuffers = false,
  13534. wireframeBit = material.wireframe ? 1 : 0,
  13535. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13536. if ( geometryHash !== _currentGeometryGroupHash ) {
  13537. _currentGeometryGroupHash = geometryHash;
  13538. updateBuffers = true;
  13539. }
  13540. if ( updateBuffers ) {
  13541. disableAttributes();
  13542. }
  13543. // render mesh
  13544. if ( object instanceof THREE.Mesh ) {
  13545. var index = geometryAttributes[ "index" ];
  13546. // indexed triangles
  13547. if ( index ) {
  13548. var offsets = geometry.offsets;
  13549. // if there is more than 1 chunk
  13550. // must set attribute pointers to use new offsets for each chunk
  13551. // even if geometry and materials didn't change
  13552. if ( offsets.length > 1 ) updateBuffers = true;
  13553. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13554. var startIndex = offsets[ i ].index;
  13555. if ( updateBuffers ) {
  13556. for ( attributeName in programAttributes ) {
  13557. attributePointer = programAttributes[ attributeName ];
  13558. attributeItem = geometryAttributes[ attributeName ];
  13559. if ( attributePointer >= 0 ) {
  13560. if ( attributeItem ) {
  13561. attributeSize = attributeItem.itemSize;
  13562. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13563. enableAttribute( attributePointer );
  13564. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13565. } else if ( material.defaultAttributeValues ) {
  13566. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13567. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13568. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13569. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13570. }
  13571. }
  13572. }
  13573. }
  13574. // indices
  13575. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13576. }
  13577. // render indexed triangles
  13578. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13579. _this.info.render.calls ++;
  13580. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13581. _this.info.render.faces += offsets[ i ].count / 3;
  13582. }
  13583. // non-indexed triangles
  13584. } else {
  13585. if ( updateBuffers ) {
  13586. for ( attributeName in programAttributes ) {
  13587. if ( attributeName === 'index') continue;
  13588. attributePointer = programAttributes[ attributeName ];
  13589. attributeItem = geometryAttributes[ attributeName ];
  13590. if ( attributePointer >= 0 ) {
  13591. if ( attributeItem ) {
  13592. attributeSize = attributeItem.itemSize;
  13593. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13594. enableAttribute( attributePointer );
  13595. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13596. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13597. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13598. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13599. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13600. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13601. }
  13602. }
  13603. }
  13604. }
  13605. }
  13606. var position = geometry.attributes[ "position" ];
  13607. // render non-indexed triangles
  13608. _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
  13609. _this.info.render.calls ++;
  13610. _this.info.render.vertices += position.array.length / 3;
  13611. _this.info.render.faces += position.array.length / 3 / 3;
  13612. }
  13613. // render particles
  13614. } else if ( object instanceof THREE.ParticleSystem ) {
  13615. if ( updateBuffers ) {
  13616. for ( attributeName in programAttributes ) {
  13617. attributePointer = programAttributes[ attributeName ];
  13618. attributeItem = geometryAttributes[ attributeName ];
  13619. if ( attributePointer >= 0 ) {
  13620. if ( attributeItem ) {
  13621. attributeSize = attributeItem.itemSize;
  13622. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13623. enableAttribute( attributePointer );
  13624. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13625. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13626. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13627. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13628. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13629. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13630. }
  13631. }
  13632. }
  13633. }
  13634. }
  13635. var position = geometryAttributes[ "position" ];
  13636. // render particles
  13637. _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
  13638. _this.info.render.calls ++;
  13639. _this.info.render.points += position.array.length / 3;
  13640. } else if ( object instanceof THREE.Line ) {
  13641. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13642. setLineWidth( material.linewidth );
  13643. var index = geometryAttributes[ "index" ];
  13644. // indexed lines
  13645. if ( index ) {
  13646. var offsets = geometry.offsets;
  13647. // if there is more than 1 chunk
  13648. // must set attribute pointers to use new offsets for each chunk
  13649. // even if geometry and materials didn't change
  13650. if ( offsets.length > 1 ) updateBuffers = true;
  13651. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13652. var startIndex = offsets[ i ].index;
  13653. if ( updateBuffers ) {
  13654. setupLinesVertexAttributes(material, programAttributes, geometryAttributes, startIndex);
  13655. // indices
  13656. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13657. }
  13658. // render indexed lines
  13659. _gl.drawElements( _gl.LINES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16Array
  13660. _this.info.render.calls ++;
  13661. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13662. }
  13663. }
  13664. // non-indexed lines
  13665. else {
  13666. if ( updateBuffers ) {
  13667. setupLinesVertexAttributes(material, programAttributes, geometryAttributes, 0);
  13668. }
  13669. var position = geometryAttributes[ "position" ];
  13670. _gl.drawArrays( primitives, 0, position.array.length / 3 );
  13671. _this.info.render.calls ++;
  13672. _this.info.render.points += position.array.length;
  13673. }
  13674. }
  13675. };
  13676. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13677. if ( material.visible === false ) return;
  13678. var linewidth, a, attribute, i, il;
  13679. var program = setProgram( camera, lights, fog, material, object );
  13680. var attributes = program.attributes;
  13681. var updateBuffers = false,
  13682. wireframeBit = material.wireframe ? 1 : 0,
  13683. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13684. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13685. _currentGeometryGroupHash = geometryGroupHash;
  13686. updateBuffers = true;
  13687. }
  13688. if ( updateBuffers ) {
  13689. disableAttributes();
  13690. }
  13691. // vertices
  13692. if ( !material.morphTargets && attributes.position >= 0 ) {
  13693. if ( updateBuffers ) {
  13694. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13695. enableAttribute( attributes.position );
  13696. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13697. }
  13698. } else {
  13699. if ( object.morphTargetBase ) {
  13700. setupMorphTargets( material, geometryGroup, object );
  13701. }
  13702. }
  13703. if ( updateBuffers ) {
  13704. // custom attributes
  13705. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13706. if ( geometryGroup.__webglCustomAttributesList ) {
  13707. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13708. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13709. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13710. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13711. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13712. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13713. }
  13714. }
  13715. }
  13716. // colors
  13717. if ( attributes.color >= 0 ) {
  13718. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13719. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13720. enableAttribute( attributes.color );
  13721. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13722. } else if ( material.defaultAttributeValues ) {
  13723. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13724. }
  13725. }
  13726. // normals
  13727. if ( attributes.normal >= 0 ) {
  13728. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13729. enableAttribute( attributes.normal );
  13730. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13731. }
  13732. // tangents
  13733. if ( attributes.tangent >= 0 ) {
  13734. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13735. enableAttribute( attributes.tangent );
  13736. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13737. }
  13738. // uvs
  13739. if ( attributes.uv >= 0 ) {
  13740. if ( object.geometry.faceVertexUvs[0] ) {
  13741. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13742. enableAttribute( attributes.uv );
  13743. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13744. } else if ( material.defaultAttributeValues ) {
  13745. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13746. }
  13747. }
  13748. if ( attributes.uv2 >= 0 ) {
  13749. if ( object.geometry.faceVertexUvs[1] ) {
  13750. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13751. enableAttribute( attributes.uv2 );
  13752. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13753. } else if ( material.defaultAttributeValues ) {
  13754. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13755. }
  13756. }
  13757. if ( material.skinning &&
  13758. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13759. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13760. enableAttribute( attributes.skinIndex );
  13761. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13762. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13763. enableAttribute( attributes.skinWeight );
  13764. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13765. }
  13766. // line distances
  13767. if ( attributes.lineDistance >= 0 ) {
  13768. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13769. enableAttribute( attributes.lineDistance );
  13770. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13771. }
  13772. }
  13773. // render mesh
  13774. if ( object instanceof THREE.Mesh ) {
  13775. // wireframe
  13776. if ( material.wireframe ) {
  13777. setLineWidth( material.wireframeLinewidth );
  13778. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13779. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13780. // triangles
  13781. } else {
  13782. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13783. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13784. }
  13785. _this.info.render.calls ++;
  13786. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13787. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13788. // render lines
  13789. } else if ( object instanceof THREE.Line ) {
  13790. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13791. setLineWidth( material.linewidth );
  13792. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13793. _this.info.render.calls ++;
  13794. // render particles
  13795. } else if ( object instanceof THREE.ParticleSystem ) {
  13796. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13797. _this.info.render.calls ++;
  13798. _this.info.render.points += geometryGroup.__webglParticleCount;
  13799. }
  13800. };
  13801. function enableAttribute( attribute ) {
  13802. if ( _enabledAttributes[ attribute ] === 0 ) {
  13803. _gl.enableVertexAttribArray( attribute );
  13804. _enabledAttributes[ attribute ] = 1;
  13805. }
  13806. };
  13807. function disableAttributes() {
  13808. for ( var attribute in _enabledAttributes ) {
  13809. if ( _enabledAttributes[ attribute ] === 1 ) {
  13810. _gl.disableVertexAttribArray( attribute );
  13811. _enabledAttributes[ attribute ] = 0;
  13812. }
  13813. }
  13814. };
  13815. function setupMorphTargets ( material, geometryGroup, object ) {
  13816. // set base
  13817. var attributes = material.program.attributes;
  13818. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13819. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13820. enableAttribute( attributes.position );
  13821. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13822. } else if ( attributes.position >= 0 ) {
  13823. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13824. enableAttribute( attributes.position );
  13825. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13826. }
  13827. if ( object.morphTargetForcedOrder.length ) {
  13828. // set forced order
  13829. var m = 0;
  13830. var order = object.morphTargetForcedOrder;
  13831. var influences = object.morphTargetInfluences;
  13832. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13833. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13834. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13835. enableAttribute( attributes[ "morphTarget" + m ] );
  13836. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13837. }
  13838. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13839. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13840. enableAttribute( attributes[ "morphNormal" + m ] );
  13841. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13842. }
  13843. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13844. m ++;
  13845. }
  13846. } else {
  13847. // find the most influencing
  13848. var influence, activeInfluenceIndices = [];
  13849. var influences = object.morphTargetInfluences;
  13850. var i, il = influences.length;
  13851. for ( i = 0; i < il; i ++ ) {
  13852. influence = influences[ i ];
  13853. if ( influence > 0 ) {
  13854. activeInfluenceIndices.push( [ influence, i ] );
  13855. }
  13856. }
  13857. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13858. activeInfluenceIndices.sort( numericalSort );
  13859. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13860. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13861. activeInfluenceIndices.sort( numericalSort );
  13862. } else if ( activeInfluenceIndices.length === 0 ) {
  13863. activeInfluenceIndices.push( [ 0, 0 ] );
  13864. };
  13865. var influenceIndex, m = 0;
  13866. while ( m < material.numSupportedMorphTargets ) {
  13867. if ( activeInfluenceIndices[ m ] ) {
  13868. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13869. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13870. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13871. enableAttribute( attributes[ "morphTarget" + m ] );
  13872. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13873. }
  13874. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13875. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13876. enableAttribute( attributes[ "morphNormal" + m ] );
  13877. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13878. }
  13879. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13880. } else {
  13881. /*
  13882. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13883. if ( material.morphNormals ) {
  13884. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13885. }
  13886. */
  13887. object.__webglMorphTargetInfluences[ m ] = 0;
  13888. }
  13889. m ++;
  13890. }
  13891. }
  13892. // load updated influences uniform
  13893. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13894. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13895. }
  13896. };
  13897. // Sorting
  13898. function painterSortStable ( a, b ) {
  13899. if ( a.z !== b.z ) {
  13900. return b.z - a.z;
  13901. } else {
  13902. return a.id - b.id;
  13903. }
  13904. };
  13905. function numericalSort ( a, b ) {
  13906. return b[ 0 ] - a[ 0 ];
  13907. };
  13908. // Rendering
  13909. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13910. if ( camera instanceof THREE.Camera === false ) {
  13911. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13912. return;
  13913. }
  13914. var i, il,
  13915. webglObject, object,
  13916. renderList,
  13917. lights = scene.__lights,
  13918. fog = scene.fog;
  13919. // reset caching for this frame
  13920. _currentMaterialId = -1;
  13921. _lightsNeedUpdate = true;
  13922. // update scene graph
  13923. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13924. // update camera matrices and frustum
  13925. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13926. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13927. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13928. _frustum.setFromMatrix( _projScreenMatrix );
  13929. // update WebGL objects
  13930. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13931. // custom render plugins (pre pass)
  13932. renderPlugins( this.renderPluginsPre, scene, camera );
  13933. //
  13934. _this.info.render.calls = 0;
  13935. _this.info.render.vertices = 0;
  13936. _this.info.render.faces = 0;
  13937. _this.info.render.points = 0;
  13938. this.setRenderTarget( renderTarget );
  13939. if ( this.autoClear || forceClear ) {
  13940. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13941. }
  13942. // set matrices for regular objects (frustum culled)
  13943. renderList = scene.__webglObjects;
  13944. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13945. webglObject = renderList[ i ];
  13946. object = webglObject.object;
  13947. webglObject.id = i;
  13948. webglObject.render = false;
  13949. if ( object.visible ) {
  13950. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13951. setupMatrices( object, camera );
  13952. unrollBufferMaterial( webglObject );
  13953. webglObject.render = true;
  13954. if ( this.sortObjects === true ) {
  13955. if ( object.renderDepth !== null ) {
  13956. webglObject.z = object.renderDepth;
  13957. } else {
  13958. _vector3.setFromMatrixPosition( object.matrixWorld );
  13959. _vector3.applyProjection( _projScreenMatrix );
  13960. webglObject.z = _vector3.z;
  13961. }
  13962. }
  13963. }
  13964. }
  13965. }
  13966. if ( this.sortObjects ) {
  13967. renderList.sort( painterSortStable );
  13968. }
  13969. // set matrices for immediate objects
  13970. renderList = scene.__webglObjectsImmediate;
  13971. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13972. webglObject = renderList[ i ];
  13973. object = webglObject.object;
  13974. if ( object.visible ) {
  13975. setupMatrices( object, camera );
  13976. unrollImmediateBufferMaterial( webglObject );
  13977. }
  13978. }
  13979. if ( scene.overrideMaterial ) {
  13980. var material = scene.overrideMaterial;
  13981. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13982. this.setDepthTest( material.depthTest );
  13983. this.setDepthWrite( material.depthWrite );
  13984. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13985. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13986. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13987. } else {
  13988. var material = null;
  13989. // opaque pass (front-to-back order)
  13990. this.setBlending( THREE.NoBlending );
  13991. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13992. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13993. // transparent pass (back-to-front order)
  13994. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13995. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13996. }
  13997. // custom render plugins (post pass)
  13998. renderPlugins( this.renderPluginsPost, scene, camera );
  13999. // Generate mipmap if we're using any kind of mipmap filtering
  14000. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  14001. updateRenderTargetMipmap( renderTarget );
  14002. }
  14003. // Ensure depth buffer writing is enabled so it can be cleared on next render
  14004. this.setDepthTest( true );
  14005. this.setDepthWrite( true );
  14006. // _gl.finish();
  14007. };
  14008. function renderPlugins( plugins, scene, camera ) {
  14009. if ( ! plugins.length ) return;
  14010. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  14011. // reset state for plugin (to start from clean slate)
  14012. _currentProgram = null;
  14013. _currentCamera = null;
  14014. _oldBlending = -1;
  14015. _oldDepthTest = -1;
  14016. _oldDepthWrite = -1;
  14017. _oldDoubleSided = -1;
  14018. _oldFlipSided = -1;
  14019. _currentGeometryGroupHash = -1;
  14020. _currentMaterialId = -1;
  14021. _lightsNeedUpdate = true;
  14022. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  14023. // reset state after plugin (anything could have changed)
  14024. _currentProgram = null;
  14025. _currentCamera = null;
  14026. _oldBlending = -1;
  14027. _oldDepthTest = -1;
  14028. _oldDepthWrite = -1;
  14029. _oldDoubleSided = -1;
  14030. _oldFlipSided = -1;
  14031. _currentGeometryGroupHash = -1;
  14032. _currentMaterialId = -1;
  14033. _lightsNeedUpdate = true;
  14034. }
  14035. };
  14036. function renderObjects( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14037. var webglObject, object, buffer, material, start, end, delta;
  14038. if ( reverse ) {
  14039. start = renderList.length - 1;
  14040. end = -1;
  14041. delta = -1;
  14042. } else {
  14043. start = 0;
  14044. end = renderList.length;
  14045. delta = 1;
  14046. }
  14047. for ( var i = start; i !== end; i += delta ) {
  14048. webglObject = renderList[ i ];
  14049. if ( webglObject.render ) {
  14050. object = webglObject.object;
  14051. buffer = webglObject.buffer;
  14052. if ( overrideMaterial ) {
  14053. material = overrideMaterial;
  14054. } else {
  14055. material = webglObject[ materialType ];
  14056. if ( ! material ) continue;
  14057. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14058. _this.setDepthTest( material.depthTest );
  14059. _this.setDepthWrite( material.depthWrite );
  14060. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14061. }
  14062. _this.setMaterialFaces( material );
  14063. if ( buffer instanceof THREE.BufferGeometry ) {
  14064. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  14065. } else {
  14066. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  14067. }
  14068. }
  14069. }
  14070. };
  14071. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14072. var webglObject, object, material, program;
  14073. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  14074. webglObject = renderList[ i ];
  14075. object = webglObject.object;
  14076. if ( object.visible ) {
  14077. if ( overrideMaterial ) {
  14078. material = overrideMaterial;
  14079. } else {
  14080. material = webglObject[ materialType ];
  14081. if ( ! material ) continue;
  14082. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14083. _this.setDepthTest( material.depthTest );
  14084. _this.setDepthWrite( material.depthWrite );
  14085. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14086. }
  14087. _this.renderImmediateObject( camera, lights, fog, material, object );
  14088. }
  14089. }
  14090. };
  14091. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  14092. var program = setProgram( camera, lights, fog, material, object );
  14093. _currentGeometryGroupHash = -1;
  14094. _this.setMaterialFaces( material );
  14095. if ( object.immediateRenderCallback ) {
  14096. object.immediateRenderCallback( program, _gl, _frustum );
  14097. } else {
  14098. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  14099. }
  14100. };
  14101. function unrollImmediateBufferMaterial ( globject ) {
  14102. var object = globject.object,
  14103. material = object.material;
  14104. if ( material.transparent ) {
  14105. globject.transparent = material;
  14106. globject.opaque = null;
  14107. } else {
  14108. globject.opaque = material;
  14109. globject.transparent = null;
  14110. }
  14111. };
  14112. function unrollBufferMaterial ( globject ) {
  14113. var object = globject.object;
  14114. var buffer = globject.buffer;
  14115. var geometry = object.geometry;
  14116. var material = object.material;
  14117. if ( material instanceof THREE.MeshFaceMaterial ) {
  14118. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  14119. material = material.materials[ materialIndex ];
  14120. if ( material.transparent ) {
  14121. globject.transparent = material;
  14122. globject.opaque = null;
  14123. } else {
  14124. globject.opaque = material;
  14125. globject.transparent = null;
  14126. }
  14127. } else {
  14128. if ( material ) {
  14129. if ( material.transparent ) {
  14130. globject.transparent = material;
  14131. globject.opaque = null;
  14132. } else {
  14133. globject.opaque = material;
  14134. globject.transparent = null;
  14135. }
  14136. }
  14137. }
  14138. };
  14139. // Objects refresh
  14140. this.initWebGLObjects = function ( scene ) {
  14141. if ( !scene.__webglObjects ) {
  14142. scene.__webglObjects = [];
  14143. scene.__webglObjectsImmediate = [];
  14144. scene.__webglSprites = [];
  14145. scene.__webglFlares = [];
  14146. }
  14147. while ( scene.__objectsAdded.length ) {
  14148. addObject( scene.__objectsAdded[ 0 ], scene );
  14149. scene.__objectsAdded.splice( 0, 1 );
  14150. }
  14151. while ( scene.__objectsRemoved.length ) {
  14152. removeObject( scene.__objectsRemoved[ 0 ], scene );
  14153. scene.__objectsRemoved.splice( 0, 1 );
  14154. }
  14155. // update must be called after objects adding / removal
  14156. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  14157. var object = scene.__webglObjects[ o ].object;
  14158. // TODO: Remove this hack (WebGLRenderer refactoring)
  14159. if ( object.__webglInit === undefined ) {
  14160. if ( object.__webglActive !== undefined ) {
  14161. removeObject( object, scene );
  14162. }
  14163. addObject( object, scene );
  14164. }
  14165. updateObject( object );
  14166. }
  14167. };
  14168. // Objects adding
  14169. function addObject( object, scene ) {
  14170. var g, geometry, material, geometryGroup;
  14171. if ( object.__webglInit === undefined ) {
  14172. object.__webglInit = true;
  14173. object._modelViewMatrix = new THREE.Matrix4();
  14174. object._normalMatrix = new THREE.Matrix3();
  14175. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  14176. object.geometry.__webglInit = true;
  14177. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  14178. }
  14179. geometry = object.geometry;
  14180. if ( geometry === undefined ) {
  14181. // fail silently for now
  14182. } else if ( geometry instanceof THREE.BufferGeometry ) {
  14183. initDirectBuffers( geometry );
  14184. } else if ( object instanceof THREE.Mesh ) {
  14185. material = object.material;
  14186. if ( geometry.geometryGroups === undefined ) {
  14187. geometry.makeGroups( material instanceof THREE.MeshFaceMaterial );
  14188. }
  14189. // create separate VBOs per geometry chunk
  14190. for ( g in geometry.geometryGroups ) {
  14191. geometryGroup = geometry.geometryGroups[ g ];
  14192. // initialise VBO on the first access
  14193. if ( ! geometryGroup.__webglVertexBuffer ) {
  14194. createMeshBuffers( geometryGroup );
  14195. initMeshBuffers( geometryGroup, object );
  14196. geometry.verticesNeedUpdate = true;
  14197. geometry.morphTargetsNeedUpdate = true;
  14198. geometry.elementsNeedUpdate = true;
  14199. geometry.uvsNeedUpdate = true;
  14200. geometry.normalsNeedUpdate = true;
  14201. geometry.tangentsNeedUpdate = true;
  14202. geometry.colorsNeedUpdate = true;
  14203. }
  14204. }
  14205. } else if ( object instanceof THREE.Line ) {
  14206. if ( ! geometry.__webglVertexBuffer ) {
  14207. createLineBuffers( geometry );
  14208. initLineBuffers( geometry, object );
  14209. geometry.verticesNeedUpdate = true;
  14210. geometry.colorsNeedUpdate = true;
  14211. geometry.lineDistancesNeedUpdate = true;
  14212. }
  14213. } else if ( object instanceof THREE.ParticleSystem ) {
  14214. if ( ! geometry.__webglVertexBuffer ) {
  14215. createParticleBuffers( geometry );
  14216. initParticleBuffers( geometry, object );
  14217. geometry.verticesNeedUpdate = true;
  14218. geometry.colorsNeedUpdate = true;
  14219. }
  14220. }
  14221. }
  14222. if ( object.__webglActive === undefined ) {
  14223. if ( object instanceof THREE.Mesh ) {
  14224. geometry = object.geometry;
  14225. if ( geometry instanceof THREE.BufferGeometry ) {
  14226. addBuffer( scene.__webglObjects, geometry, object );
  14227. } else if ( geometry instanceof THREE.Geometry ) {
  14228. for ( g in geometry.geometryGroups ) {
  14229. geometryGroup = geometry.geometryGroups[ g ];
  14230. addBuffer( scene.__webglObjects, geometryGroup, object );
  14231. }
  14232. }
  14233. } else if ( object instanceof THREE.Line ||
  14234. object instanceof THREE.ParticleSystem ) {
  14235. geometry = object.geometry;
  14236. addBuffer( scene.__webglObjects, geometry, object );
  14237. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14238. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14239. } else if ( object instanceof THREE.Sprite ) {
  14240. scene.__webglSprites.push( object );
  14241. } else if ( object instanceof THREE.LensFlare ) {
  14242. scene.__webglFlares.push( object );
  14243. }
  14244. object.__webglActive = true;
  14245. }
  14246. };
  14247. function addBuffer( objlist, buffer, object ) {
  14248. objlist.push(
  14249. {
  14250. id: null,
  14251. buffer: buffer,
  14252. object: object,
  14253. opaque: null,
  14254. transparent: null,
  14255. z: 0
  14256. }
  14257. );
  14258. };
  14259. function addBufferImmediate( objlist, object ) {
  14260. objlist.push(
  14261. {
  14262. id: null,
  14263. object: object,
  14264. opaque: null,
  14265. transparent: null,
  14266. z: 0
  14267. }
  14268. );
  14269. };
  14270. // Objects updates
  14271. function updateObject( object ) {
  14272. var geometry = object.geometry,
  14273. geometryGroup, customAttributesDirty, material;
  14274. if ( geometry instanceof THREE.BufferGeometry ) {
  14275. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW );
  14276. } else if ( object instanceof THREE.Mesh ) {
  14277. // check all geometry groups
  14278. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14279. geometryGroup = geometry.geometryGroupsList[ i ];
  14280. material = getBufferMaterial( object, geometryGroup );
  14281. if ( geometry.buffersNeedUpdate ) {
  14282. initMeshBuffers( geometryGroup, object );
  14283. }
  14284. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14285. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14286. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14287. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14288. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  14289. }
  14290. }
  14291. geometry.verticesNeedUpdate = false;
  14292. geometry.morphTargetsNeedUpdate = false;
  14293. geometry.elementsNeedUpdate = false;
  14294. geometry.uvsNeedUpdate = false;
  14295. geometry.normalsNeedUpdate = false;
  14296. geometry.colorsNeedUpdate = false;
  14297. geometry.tangentsNeedUpdate = false;
  14298. geometry.buffersNeedUpdate = false;
  14299. material.attributes && clearCustomAttributes( material );
  14300. } else if ( object instanceof THREE.Line ) {
  14301. material = getBufferMaterial( object, geometry );
  14302. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14303. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14304. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14305. }
  14306. geometry.verticesNeedUpdate = false;
  14307. geometry.colorsNeedUpdate = false;
  14308. geometry.lineDistancesNeedUpdate = false;
  14309. material.attributes && clearCustomAttributes( material );
  14310. } else if ( object instanceof THREE.ParticleSystem ) {
  14311. material = getBufferMaterial( object, geometry );
  14312. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14313. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14314. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14315. }
  14316. geometry.verticesNeedUpdate = false;
  14317. geometry.colorsNeedUpdate = false;
  14318. material.attributes && clearCustomAttributes( material );
  14319. }
  14320. };
  14321. // Objects updates - custom attributes check
  14322. function areCustomAttributesDirty( material ) {
  14323. for ( var a in material.attributes ) {
  14324. if ( material.attributes[ a ].needsUpdate ) return true;
  14325. }
  14326. return false;
  14327. };
  14328. function clearCustomAttributes( material ) {
  14329. for ( var a in material.attributes ) {
  14330. material.attributes[ a ].needsUpdate = false;
  14331. }
  14332. };
  14333. // Objects removal
  14334. function removeObject( object, scene ) {
  14335. if ( object instanceof THREE.Mesh ||
  14336. object instanceof THREE.ParticleSystem ||
  14337. object instanceof THREE.Line ) {
  14338. removeInstances( scene.__webglObjects, object );
  14339. } else if ( object instanceof THREE.Sprite ) {
  14340. removeInstancesDirect( scene.__webglSprites, object );
  14341. } else if ( object instanceof THREE.LensFlare ) {
  14342. removeInstancesDirect( scene.__webglFlares, object );
  14343. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14344. removeInstances( scene.__webglObjectsImmediate, object );
  14345. }
  14346. delete object.__webglActive;
  14347. };
  14348. function removeInstances( objlist, object ) {
  14349. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14350. if ( objlist[ o ].object === object ) {
  14351. objlist.splice( o, 1 );
  14352. }
  14353. }
  14354. };
  14355. function removeInstancesDirect( objlist, object ) {
  14356. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14357. if ( objlist[ o ] === object ) {
  14358. objlist.splice( o, 1 );
  14359. }
  14360. }
  14361. };
  14362. // Materials
  14363. this.initMaterial = function ( material, lights, fog, object ) {
  14364. material.addEventListener( 'dispose', onMaterialDispose );
  14365. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14366. if ( material instanceof THREE.MeshDepthMaterial ) {
  14367. shaderID = 'depth';
  14368. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14369. shaderID = 'normal';
  14370. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14371. shaderID = 'basic';
  14372. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14373. shaderID = 'lambert';
  14374. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14375. shaderID = 'phong';
  14376. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14377. shaderID = 'basic';
  14378. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14379. shaderID = 'dashed';
  14380. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14381. shaderID = 'particle_basic';
  14382. }
  14383. if ( shaderID ) {
  14384. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14385. }
  14386. // heuristics to create shader parameters according to lights in the scene
  14387. // (not to blow over maxLights budget)
  14388. maxLightCount = allocateLights( lights );
  14389. maxShadows = allocateShadows( lights );
  14390. maxBones = allocateBones( object );
  14391. parameters = {
  14392. map: !!material.map,
  14393. envMap: !!material.envMap,
  14394. lightMap: !!material.lightMap,
  14395. bumpMap: !!material.bumpMap,
  14396. normalMap: !!material.normalMap,
  14397. specularMap: !!material.specularMap,
  14398. vertexColors: material.vertexColors,
  14399. fog: fog,
  14400. useFog: material.fog,
  14401. fogExp: fog instanceof THREE.FogExp2,
  14402. sizeAttenuation: material.sizeAttenuation,
  14403. skinning: material.skinning,
  14404. maxBones: maxBones,
  14405. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  14406. morphTargets: material.morphTargets,
  14407. morphNormals: material.morphNormals,
  14408. maxMorphTargets: this.maxMorphTargets,
  14409. maxMorphNormals: this.maxMorphNormals,
  14410. maxDirLights: maxLightCount.directional,
  14411. maxPointLights: maxLightCount.point,
  14412. maxSpotLights: maxLightCount.spot,
  14413. maxHemiLights: maxLightCount.hemi,
  14414. maxShadows: maxShadows,
  14415. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
  14416. shadowMapType: this.shadowMapType,
  14417. shadowMapDebug: this.shadowMapDebug,
  14418. shadowMapCascade: this.shadowMapCascade,
  14419. alphaTest: material.alphaTest,
  14420. metal: material.metal,
  14421. wrapAround: material.wrapAround,
  14422. doubleSided: material.side === THREE.DoubleSide,
  14423. flipSided: material.side === THREE.BackSide
  14424. };
  14425. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName );
  14426. var attributes = material.program.attributes;
  14427. if ( material.morphTargets ) {
  14428. material.numSupportedMorphTargets = 0;
  14429. var id, base = "morphTarget";
  14430. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14431. id = base + i;
  14432. if ( attributes[ id ] >= 0 ) {
  14433. material.numSupportedMorphTargets ++;
  14434. }
  14435. }
  14436. }
  14437. if ( material.morphNormals ) {
  14438. material.numSupportedMorphNormals = 0;
  14439. var id, base = "morphNormal";
  14440. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14441. id = base + i;
  14442. if ( attributes[ id ] >= 0 ) {
  14443. material.numSupportedMorphNormals ++;
  14444. }
  14445. }
  14446. }
  14447. material.uniformsList = [];
  14448. for ( u in material.uniforms ) {
  14449. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14450. }
  14451. };
  14452. function setMaterialShaders( material, shaders ) {
  14453. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14454. material.vertexShader = shaders.vertexShader;
  14455. material.fragmentShader = shaders.fragmentShader;
  14456. };
  14457. function setProgram( camera, lights, fog, material, object ) {
  14458. _usedTextureUnits = 0;
  14459. if ( material.needsUpdate ) {
  14460. if ( material.program ) deallocateMaterial( material );
  14461. _this.initMaterial( material, lights, fog, object );
  14462. material.needsUpdate = false;
  14463. }
  14464. if ( material.morphTargets ) {
  14465. if ( ! object.__webglMorphTargetInfluences ) {
  14466. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14467. }
  14468. }
  14469. var refreshMaterial = false;
  14470. var program = material.program,
  14471. p_uniforms = program.uniforms,
  14472. m_uniforms = material.uniforms;
  14473. if ( program !== _currentProgram ) {
  14474. _gl.useProgram( program );
  14475. _currentProgram = program;
  14476. refreshMaterial = true;
  14477. }
  14478. if ( material.id !== _currentMaterialId ) {
  14479. _currentMaterialId = material.id;
  14480. refreshMaterial = true;
  14481. }
  14482. if ( refreshMaterial || camera !== _currentCamera ) {
  14483. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14484. if ( camera !== _currentCamera ) _currentCamera = camera;
  14485. }
  14486. // skinning uniforms must be set even if material didn't change
  14487. // auto-setting of texture unit for bone texture must go before other textures
  14488. // not sure why, but otherwise weird things happen
  14489. if ( material.skinning ) {
  14490. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14491. if ( p_uniforms.boneTexture !== null ) {
  14492. var textureUnit = getTextureUnit();
  14493. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14494. _this.setTexture( object.boneTexture, textureUnit );
  14495. }
  14496. if ( p_uniforms.boneTextureWidth !== null ) {
  14497. _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
  14498. }
  14499. if ( p_uniforms.boneTextureHeight !== null ) {
  14500. _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
  14501. }
  14502. } else {
  14503. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14504. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14505. }
  14506. }
  14507. }
  14508. if ( refreshMaterial ) {
  14509. // refresh uniforms common to several materials
  14510. if ( fog && material.fog ) {
  14511. refreshUniformsFog( m_uniforms, fog );
  14512. }
  14513. if ( material instanceof THREE.MeshPhongMaterial ||
  14514. material instanceof THREE.MeshLambertMaterial ||
  14515. material.lights ) {
  14516. if ( _lightsNeedUpdate ) {
  14517. setupLights( program, lights );
  14518. _lightsNeedUpdate = false;
  14519. }
  14520. refreshUniformsLights( m_uniforms, _lights );
  14521. }
  14522. if ( material instanceof THREE.MeshBasicMaterial ||
  14523. material instanceof THREE.MeshLambertMaterial ||
  14524. material instanceof THREE.MeshPhongMaterial ) {
  14525. refreshUniformsCommon( m_uniforms, material );
  14526. }
  14527. // refresh single material specific uniforms
  14528. if ( material instanceof THREE.LineBasicMaterial ) {
  14529. refreshUniformsLine( m_uniforms, material );
  14530. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14531. refreshUniformsLine( m_uniforms, material );
  14532. refreshUniformsDash( m_uniforms, material );
  14533. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14534. refreshUniformsParticle( m_uniforms, material );
  14535. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14536. refreshUniformsPhong( m_uniforms, material );
  14537. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14538. refreshUniformsLambert( m_uniforms, material );
  14539. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14540. m_uniforms.mNear.value = camera.near;
  14541. m_uniforms.mFar.value = camera.far;
  14542. m_uniforms.opacity.value = material.opacity;
  14543. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14544. m_uniforms.opacity.value = material.opacity;
  14545. }
  14546. if ( object.receiveShadow && ! material._shadowPass ) {
  14547. refreshUniformsShadow( m_uniforms, lights );
  14548. }
  14549. // load common uniforms
  14550. loadUniformsGeneric( program, material.uniformsList );
  14551. // load material specific uniforms
  14552. // (shader material also gets them for the sake of genericity)
  14553. if ( material instanceof THREE.ShaderMaterial ||
  14554. material instanceof THREE.MeshPhongMaterial ||
  14555. material.envMap ) {
  14556. if ( p_uniforms.cameraPosition !== null ) {
  14557. _vector3.setFromMatrixPosition( camera.matrixWorld );
  14558. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14559. }
  14560. }
  14561. if ( material instanceof THREE.MeshPhongMaterial ||
  14562. material instanceof THREE.MeshLambertMaterial ||
  14563. material instanceof THREE.ShaderMaterial ||
  14564. material.skinning ) {
  14565. if ( p_uniforms.viewMatrix !== null ) {
  14566. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14567. }
  14568. }
  14569. }
  14570. loadUniformsMatrices( p_uniforms, object );
  14571. if ( p_uniforms.modelMatrix !== null ) {
  14572. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14573. }
  14574. return program;
  14575. };
  14576. // Uniforms (refresh uniforms objects)
  14577. function refreshUniformsCommon ( uniforms, material ) {
  14578. uniforms.opacity.value = material.opacity;
  14579. if ( _this.gammaInput ) {
  14580. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14581. } else {
  14582. uniforms.diffuse.value = material.color;
  14583. }
  14584. uniforms.map.value = material.map;
  14585. uniforms.lightMap.value = material.lightMap;
  14586. uniforms.specularMap.value = material.specularMap;
  14587. if ( material.bumpMap ) {
  14588. uniforms.bumpMap.value = material.bumpMap;
  14589. uniforms.bumpScale.value = material.bumpScale;
  14590. }
  14591. if ( material.normalMap ) {
  14592. uniforms.normalMap.value = material.normalMap;
  14593. uniforms.normalScale.value.copy( material.normalScale );
  14594. }
  14595. // uv repeat and offset setting priorities
  14596. // 1. color map
  14597. // 2. specular map
  14598. // 3. normal map
  14599. // 4. bump map
  14600. var uvScaleMap;
  14601. if ( material.map ) {
  14602. uvScaleMap = material.map;
  14603. } else if ( material.specularMap ) {
  14604. uvScaleMap = material.specularMap;
  14605. } else if ( material.normalMap ) {
  14606. uvScaleMap = material.normalMap;
  14607. } else if ( material.bumpMap ) {
  14608. uvScaleMap = material.bumpMap;
  14609. }
  14610. if ( uvScaleMap !== undefined ) {
  14611. var offset = uvScaleMap.offset;
  14612. var repeat = uvScaleMap.repeat;
  14613. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14614. }
  14615. uniforms.envMap.value = material.envMap;
  14616. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14617. if ( _this.gammaInput ) {
  14618. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14619. uniforms.reflectivity.value = material.reflectivity;
  14620. } else {
  14621. uniforms.reflectivity.value = material.reflectivity;
  14622. }
  14623. uniforms.refractionRatio.value = material.refractionRatio;
  14624. uniforms.combine.value = material.combine;
  14625. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14626. };
  14627. function refreshUniformsLine ( uniforms, material ) {
  14628. uniforms.diffuse.value = material.color;
  14629. uniforms.opacity.value = material.opacity;
  14630. };
  14631. function refreshUniformsDash ( uniforms, material ) {
  14632. uniforms.dashSize.value = material.dashSize;
  14633. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14634. uniforms.scale.value = material.scale;
  14635. };
  14636. function refreshUniformsParticle ( uniforms, material ) {
  14637. uniforms.psColor.value = material.color;
  14638. uniforms.opacity.value = material.opacity;
  14639. uniforms.size.value = material.size;
  14640. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14641. uniforms.map.value = material.map;
  14642. };
  14643. function refreshUniformsFog ( uniforms, fog ) {
  14644. uniforms.fogColor.value = fog.color;
  14645. if ( fog instanceof THREE.Fog ) {
  14646. uniforms.fogNear.value = fog.near;
  14647. uniforms.fogFar.value = fog.far;
  14648. } else if ( fog instanceof THREE.FogExp2 ) {
  14649. uniforms.fogDensity.value = fog.density;
  14650. }
  14651. };
  14652. function refreshUniformsPhong ( uniforms, material ) {
  14653. uniforms.shininess.value = material.shininess;
  14654. if ( _this.gammaInput ) {
  14655. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14656. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14657. uniforms.specular.value.copyGammaToLinear( material.specular );
  14658. } else {
  14659. uniforms.ambient.value = material.ambient;
  14660. uniforms.emissive.value = material.emissive;
  14661. uniforms.specular.value = material.specular;
  14662. }
  14663. if ( material.wrapAround ) {
  14664. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14665. }
  14666. };
  14667. function refreshUniformsLambert ( uniforms, material ) {
  14668. if ( _this.gammaInput ) {
  14669. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14670. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14671. } else {
  14672. uniforms.ambient.value = material.ambient;
  14673. uniforms.emissive.value = material.emissive;
  14674. }
  14675. if ( material.wrapAround ) {
  14676. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14677. }
  14678. };
  14679. function refreshUniformsLights ( uniforms, lights ) {
  14680. uniforms.ambientLightColor.value = lights.ambient;
  14681. uniforms.directionalLightColor.value = lights.directional.colors;
  14682. uniforms.directionalLightDirection.value = lights.directional.positions;
  14683. uniforms.pointLightColor.value = lights.point.colors;
  14684. uniforms.pointLightPosition.value = lights.point.positions;
  14685. uniforms.pointLightDistance.value = lights.point.distances;
  14686. uniforms.spotLightColor.value = lights.spot.colors;
  14687. uniforms.spotLightPosition.value = lights.spot.positions;
  14688. uniforms.spotLightDistance.value = lights.spot.distances;
  14689. uniforms.spotLightDirection.value = lights.spot.directions;
  14690. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14691. uniforms.spotLightExponent.value = lights.spot.exponents;
  14692. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14693. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14694. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14695. };
  14696. function refreshUniformsShadow ( uniforms, lights ) {
  14697. if ( uniforms.shadowMatrix ) {
  14698. var j = 0;
  14699. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14700. var light = lights[ i ];
  14701. if ( ! light.castShadow ) continue;
  14702. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14703. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14704. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14705. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14706. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14707. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14708. j ++;
  14709. }
  14710. }
  14711. }
  14712. };
  14713. // Uniforms (load to GPU)
  14714. function loadUniformsMatrices ( uniforms, object ) {
  14715. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14716. if ( uniforms.normalMatrix ) {
  14717. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14718. }
  14719. };
  14720. function getTextureUnit() {
  14721. var textureUnit = _usedTextureUnits;
  14722. if ( textureUnit >= _maxTextures ) {
  14723. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14724. }
  14725. _usedTextureUnits += 1;
  14726. return textureUnit;
  14727. };
  14728. function loadUniformsGeneric ( program, uniforms ) {
  14729. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14730. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14731. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14732. if ( !location ) continue;
  14733. uniform = uniforms[ j ][ 0 ];
  14734. type = uniform.type;
  14735. value = uniform.value;
  14736. if ( type === "i" ) { // single integer
  14737. _gl.uniform1i( location, value );
  14738. } else if ( type === "f" ) { // single float
  14739. _gl.uniform1f( location, value );
  14740. } else if ( type === "v2" ) { // single THREE.Vector2
  14741. _gl.uniform2f( location, value.x, value.y );
  14742. } else if ( type === "v3" ) { // single THREE.Vector3
  14743. _gl.uniform3f( location, value.x, value.y, value.z );
  14744. } else if ( type === "v4" ) { // single THREE.Vector4
  14745. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14746. } else if ( type === "c" ) { // single THREE.Color
  14747. _gl.uniform3f( location, value.r, value.g, value.b );
  14748. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14749. _gl.uniform1iv( location, value );
  14750. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14751. _gl.uniform3iv( location, value );
  14752. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14753. _gl.uniform1fv( location, value );
  14754. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14755. _gl.uniform3fv( location, value );
  14756. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14757. if ( uniform._array === undefined ) {
  14758. uniform._array = new Float32Array( 2 * value.length );
  14759. }
  14760. for ( i = 0, il = value.length; i < il; i ++ ) {
  14761. offset = i * 2;
  14762. uniform._array[ offset ] = value[ i ].x;
  14763. uniform._array[ offset + 1 ] = value[ i ].y;
  14764. }
  14765. _gl.uniform2fv( location, uniform._array );
  14766. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14767. if ( uniform._array === undefined ) {
  14768. uniform._array = new Float32Array( 3 * value.length );
  14769. }
  14770. for ( i = 0, il = value.length; i < il; i ++ ) {
  14771. offset = i * 3;
  14772. uniform._array[ offset ] = value[ i ].x;
  14773. uniform._array[ offset + 1 ] = value[ i ].y;
  14774. uniform._array[ offset + 2 ] = value[ i ].z;
  14775. }
  14776. _gl.uniform3fv( location, uniform._array );
  14777. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14778. if ( uniform._array === undefined ) {
  14779. uniform._array = new Float32Array( 4 * value.length );
  14780. }
  14781. for ( i = 0, il = value.length; i < il; i ++ ) {
  14782. offset = i * 4;
  14783. uniform._array[ offset ] = value[ i ].x;
  14784. uniform._array[ offset + 1 ] = value[ i ].y;
  14785. uniform._array[ offset + 2 ] = value[ i ].z;
  14786. uniform._array[ offset + 3 ] = value[ i ].w;
  14787. }
  14788. _gl.uniform4fv( location, uniform._array );
  14789. } else if ( type === "m4") { // single THREE.Matrix4
  14790. if ( uniform._array === undefined ) {
  14791. uniform._array = new Float32Array( 16 );
  14792. }
  14793. value.flattenToArray( uniform._array );
  14794. _gl.uniformMatrix4fv( location, false, uniform._array );
  14795. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14796. if ( uniform._array === undefined ) {
  14797. uniform._array = new Float32Array( 16 * value.length );
  14798. }
  14799. for ( i = 0, il = value.length; i < il; i ++ ) {
  14800. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14801. }
  14802. _gl.uniformMatrix4fv( location, false, uniform._array );
  14803. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14804. texture = value;
  14805. textureUnit = getTextureUnit();
  14806. _gl.uniform1i( location, textureUnit );
  14807. if ( !texture ) continue;
  14808. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14809. setCubeTexture( texture, textureUnit );
  14810. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14811. setCubeTextureDynamic( texture, textureUnit );
  14812. } else {
  14813. _this.setTexture( texture, textureUnit );
  14814. }
  14815. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14816. if ( uniform._array === undefined ) {
  14817. uniform._array = [];
  14818. }
  14819. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14820. uniform._array[ i ] = getTextureUnit();
  14821. }
  14822. _gl.uniform1iv( location, uniform._array );
  14823. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14824. texture = uniform.value[ i ];
  14825. textureUnit = uniform._array[ i ];
  14826. if ( !texture ) continue;
  14827. _this.setTexture( texture, textureUnit );
  14828. }
  14829. } else {
  14830. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14831. }
  14832. }
  14833. };
  14834. function setupMatrices ( object, camera ) {
  14835. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14836. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14837. };
  14838. //
  14839. function setColorGamma( array, offset, color, intensitySq ) {
  14840. array[ offset ] = color.r * color.r * intensitySq;
  14841. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14842. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14843. };
  14844. function setColorLinear( array, offset, color, intensity ) {
  14845. array[ offset ] = color.r * intensity;
  14846. array[ offset + 1 ] = color.g * intensity;
  14847. array[ offset + 2 ] = color.b * intensity;
  14848. };
  14849. function setupLights ( program, lights ) {
  14850. var l, ll, light, n,
  14851. r = 0, g = 0, b = 0,
  14852. color, skyColor, groundColor,
  14853. intensity, intensitySq,
  14854. position,
  14855. distance,
  14856. zlights = _lights,
  14857. dirColors = zlights.directional.colors,
  14858. dirPositions = zlights.directional.positions,
  14859. pointColors = zlights.point.colors,
  14860. pointPositions = zlights.point.positions,
  14861. pointDistances = zlights.point.distances,
  14862. spotColors = zlights.spot.colors,
  14863. spotPositions = zlights.spot.positions,
  14864. spotDistances = zlights.spot.distances,
  14865. spotDirections = zlights.spot.directions,
  14866. spotAnglesCos = zlights.spot.anglesCos,
  14867. spotExponents = zlights.spot.exponents,
  14868. hemiSkyColors = zlights.hemi.skyColors,
  14869. hemiGroundColors = zlights.hemi.groundColors,
  14870. hemiPositions = zlights.hemi.positions,
  14871. dirLength = 0,
  14872. pointLength = 0,
  14873. spotLength = 0,
  14874. hemiLength = 0,
  14875. dirCount = 0,
  14876. pointCount = 0,
  14877. spotCount = 0,
  14878. hemiCount = 0,
  14879. dirOffset = 0,
  14880. pointOffset = 0,
  14881. spotOffset = 0,
  14882. hemiOffset = 0;
  14883. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14884. light = lights[ l ];
  14885. if ( light.onlyShadow ) continue;
  14886. color = light.color;
  14887. intensity = light.intensity;
  14888. distance = light.distance;
  14889. if ( light instanceof THREE.AmbientLight ) {
  14890. if ( ! light.visible ) continue;
  14891. if ( _this.gammaInput ) {
  14892. r += color.r * color.r;
  14893. g += color.g * color.g;
  14894. b += color.b * color.b;
  14895. } else {
  14896. r += color.r;
  14897. g += color.g;
  14898. b += color.b;
  14899. }
  14900. } else if ( light instanceof THREE.DirectionalLight ) {
  14901. dirCount += 1;
  14902. if ( ! light.visible ) continue;
  14903. _direction.setFromMatrixPosition( light.matrixWorld );
  14904. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14905. _direction.sub( _vector3 );
  14906. _direction.normalize();
  14907. // skip lights with undefined direction
  14908. // these create troubles in OpenGL (making pixel black)
  14909. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14910. dirOffset = dirLength * 3;
  14911. dirPositions[ dirOffset ] = _direction.x;
  14912. dirPositions[ dirOffset + 1 ] = _direction.y;
  14913. dirPositions[ dirOffset + 2 ] = _direction.z;
  14914. if ( _this.gammaInput ) {
  14915. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14916. } else {
  14917. setColorLinear( dirColors, dirOffset, color, intensity );
  14918. }
  14919. dirLength += 1;
  14920. } else if ( light instanceof THREE.PointLight ) {
  14921. pointCount += 1;
  14922. if ( ! light.visible ) continue;
  14923. pointOffset = pointLength * 3;
  14924. if ( _this.gammaInput ) {
  14925. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14926. } else {
  14927. setColorLinear( pointColors, pointOffset, color, intensity );
  14928. }
  14929. _vector3.setFromMatrixPosition( light.matrixWorld );
  14930. pointPositions[ pointOffset ] = _vector3.x;
  14931. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14932. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14933. pointDistances[ pointLength ] = distance;
  14934. pointLength += 1;
  14935. } else if ( light instanceof THREE.SpotLight ) {
  14936. spotCount += 1;
  14937. if ( ! light.visible ) continue;
  14938. spotOffset = spotLength * 3;
  14939. if ( _this.gammaInput ) {
  14940. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14941. } else {
  14942. setColorLinear( spotColors, spotOffset, color, intensity );
  14943. }
  14944. _vector3.setFromMatrixPosition( light.matrixWorld );
  14945. spotPositions[ spotOffset ] = _vector3.x;
  14946. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14947. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14948. spotDistances[ spotLength ] = distance;
  14949. _direction.copy( _vector3 );
  14950. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14951. _direction.sub( _vector3 );
  14952. _direction.normalize();
  14953. spotDirections[ spotOffset ] = _direction.x;
  14954. spotDirections[ spotOffset + 1 ] = _direction.y;
  14955. spotDirections[ spotOffset + 2 ] = _direction.z;
  14956. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14957. spotExponents[ spotLength ] = light.exponent;
  14958. spotLength += 1;
  14959. } else if ( light instanceof THREE.HemisphereLight ) {
  14960. hemiCount += 1;
  14961. if ( ! light.visible ) continue;
  14962. _direction.setFromMatrixPosition( light.matrixWorld );
  14963. _direction.normalize();
  14964. // skip lights with undefined direction
  14965. // these create troubles in OpenGL (making pixel black)
  14966. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14967. hemiOffset = hemiLength * 3;
  14968. hemiPositions[ hemiOffset ] = _direction.x;
  14969. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14970. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14971. skyColor = light.color;
  14972. groundColor = light.groundColor;
  14973. if ( _this.gammaInput ) {
  14974. intensitySq = intensity * intensity;
  14975. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14976. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14977. } else {
  14978. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14979. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14980. }
  14981. hemiLength += 1;
  14982. }
  14983. }
  14984. // null eventual remains from removed lights
  14985. // (this is to avoid if in shader)
  14986. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14987. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14988. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14989. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14990. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14991. zlights.directional.length = dirLength;
  14992. zlights.point.length = pointLength;
  14993. zlights.spot.length = spotLength;
  14994. zlights.hemi.length = hemiLength;
  14995. zlights.ambient[ 0 ] = r;
  14996. zlights.ambient[ 1 ] = g;
  14997. zlights.ambient[ 2 ] = b;
  14998. };
  14999. // GL state setting
  15000. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  15001. if ( cullFace === THREE.CullFaceNone ) {
  15002. _gl.disable( _gl.CULL_FACE );
  15003. } else {
  15004. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  15005. _gl.frontFace( _gl.CW );
  15006. } else {
  15007. _gl.frontFace( _gl.CCW );
  15008. }
  15009. if ( cullFace === THREE.CullFaceBack ) {
  15010. _gl.cullFace( _gl.BACK );
  15011. } else if ( cullFace === THREE.CullFaceFront ) {
  15012. _gl.cullFace( _gl.FRONT );
  15013. } else {
  15014. _gl.cullFace( _gl.FRONT_AND_BACK );
  15015. }
  15016. _gl.enable( _gl.CULL_FACE );
  15017. }
  15018. };
  15019. this.setMaterialFaces = function ( material ) {
  15020. var doubleSided = material.side === THREE.DoubleSide;
  15021. var flipSided = material.side === THREE.BackSide;
  15022. if ( _oldDoubleSided !== doubleSided ) {
  15023. if ( doubleSided ) {
  15024. _gl.disable( _gl.CULL_FACE );
  15025. } else {
  15026. _gl.enable( _gl.CULL_FACE );
  15027. }
  15028. _oldDoubleSided = doubleSided;
  15029. }
  15030. if ( _oldFlipSided !== flipSided ) {
  15031. if ( flipSided ) {
  15032. _gl.frontFace( _gl.CW );
  15033. } else {
  15034. _gl.frontFace( _gl.CCW );
  15035. }
  15036. _oldFlipSided = flipSided;
  15037. }
  15038. };
  15039. this.setDepthTest = function ( depthTest ) {
  15040. if ( _oldDepthTest !== depthTest ) {
  15041. if ( depthTest ) {
  15042. _gl.enable( _gl.DEPTH_TEST );
  15043. } else {
  15044. _gl.disable( _gl.DEPTH_TEST );
  15045. }
  15046. _oldDepthTest = depthTest;
  15047. }
  15048. };
  15049. this.setDepthWrite = function ( depthWrite ) {
  15050. if ( _oldDepthWrite !== depthWrite ) {
  15051. _gl.depthMask( depthWrite );
  15052. _oldDepthWrite = depthWrite;
  15053. }
  15054. };
  15055. function setLineWidth ( width ) {
  15056. if ( width !== _oldLineWidth ) {
  15057. _gl.lineWidth( width );
  15058. _oldLineWidth = width;
  15059. }
  15060. };
  15061. function setPolygonOffset ( polygonoffset, factor, units ) {
  15062. if ( _oldPolygonOffset !== polygonoffset ) {
  15063. if ( polygonoffset ) {
  15064. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  15065. } else {
  15066. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  15067. }
  15068. _oldPolygonOffset = polygonoffset;
  15069. }
  15070. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  15071. _gl.polygonOffset( factor, units );
  15072. _oldPolygonOffsetFactor = factor;
  15073. _oldPolygonOffsetUnits = units;
  15074. }
  15075. };
  15076. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  15077. if ( blending !== _oldBlending ) {
  15078. if ( blending === THREE.NoBlending ) {
  15079. _gl.disable( _gl.BLEND );
  15080. } else if ( blending === THREE.AdditiveBlending ) {
  15081. _gl.enable( _gl.BLEND );
  15082. _gl.blendEquation( _gl.FUNC_ADD );
  15083. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  15084. } else if ( blending === THREE.SubtractiveBlending ) {
  15085. // TODO: Find blendFuncSeparate() combination
  15086. _gl.enable( _gl.BLEND );
  15087. _gl.blendEquation( _gl.FUNC_ADD );
  15088. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  15089. } else if ( blending === THREE.MultiplyBlending ) {
  15090. // TODO: Find blendFuncSeparate() combination
  15091. _gl.enable( _gl.BLEND );
  15092. _gl.blendEquation( _gl.FUNC_ADD );
  15093. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  15094. } else if ( blending === THREE.CustomBlending ) {
  15095. _gl.enable( _gl.BLEND );
  15096. } else {
  15097. _gl.enable( _gl.BLEND );
  15098. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  15099. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  15100. }
  15101. _oldBlending = blending;
  15102. }
  15103. if ( blending === THREE.CustomBlending ) {
  15104. if ( blendEquation !== _oldBlendEquation ) {
  15105. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  15106. _oldBlendEquation = blendEquation;
  15107. }
  15108. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  15109. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  15110. _oldBlendSrc = blendSrc;
  15111. _oldBlendDst = blendDst;
  15112. }
  15113. } else {
  15114. _oldBlendEquation = null;
  15115. _oldBlendSrc = null;
  15116. _oldBlendDst = null;
  15117. }
  15118. };
  15119. // Defines
  15120. function generateDefines ( defines ) {
  15121. var value, chunk, chunks = [];
  15122. for ( var d in defines ) {
  15123. value = defines[ d ];
  15124. if ( value === false ) continue;
  15125. chunk = "#define " + d + " " + value;
  15126. chunks.push( chunk );
  15127. }
  15128. return chunks.join( "\n" );
  15129. };
  15130. // Shaders
  15131. function buildProgram( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) {
  15132. var p, pl, d, program, code;
  15133. var chunks = [];
  15134. // Generate code
  15135. if ( shaderID ) {
  15136. chunks.push( shaderID );
  15137. } else {
  15138. chunks.push( fragmentShader );
  15139. chunks.push( vertexShader );
  15140. }
  15141. for ( d in defines ) {
  15142. chunks.push( d );
  15143. chunks.push( defines[ d ] );
  15144. }
  15145. for ( p in parameters ) {
  15146. chunks.push( p );
  15147. chunks.push( parameters[ p ] );
  15148. }
  15149. code = chunks.join();
  15150. // Check if code has been already compiled
  15151. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  15152. var programInfo = _programs[ p ];
  15153. if ( programInfo.code === code ) {
  15154. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  15155. programInfo.usedTimes ++;
  15156. return programInfo.program;
  15157. }
  15158. }
  15159. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  15160. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  15161. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  15162. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  15163. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  15164. }
  15165. // console.log( "building new program " );
  15166. //
  15167. var customDefines = generateDefines( defines );
  15168. //
  15169. program = _gl.createProgram();
  15170. var prefix_vertex = [
  15171. "precision " + _precision + " float;",
  15172. "precision " + _precision + " int;",
  15173. customDefines,
  15174. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  15175. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15176. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15177. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15178. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15179. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15180. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15181. "#define MAX_SHADOWS " + parameters.maxShadows,
  15182. "#define MAX_BONES " + parameters.maxBones,
  15183. parameters.map ? "#define USE_MAP" : "",
  15184. parameters.envMap ? "#define USE_ENVMAP" : "",
  15185. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15186. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15187. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15188. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15189. parameters.vertexColors ? "#define USE_COLOR" : "",
  15190. parameters.skinning ? "#define USE_SKINNING" : "",
  15191. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  15192. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  15193. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  15194. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15195. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15196. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15197. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15198. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15199. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15200. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15201. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  15202. "uniform mat4 modelMatrix;",
  15203. "uniform mat4 modelViewMatrix;",
  15204. "uniform mat4 projectionMatrix;",
  15205. "uniform mat4 viewMatrix;",
  15206. "uniform mat3 normalMatrix;",
  15207. "uniform vec3 cameraPosition;",
  15208. "attribute vec3 position;",
  15209. "attribute vec3 normal;",
  15210. "attribute vec2 uv;",
  15211. "attribute vec2 uv2;",
  15212. "#ifdef USE_COLOR",
  15213. "attribute vec3 color;",
  15214. "#endif",
  15215. "#ifdef USE_MORPHTARGETS",
  15216. "attribute vec3 morphTarget0;",
  15217. "attribute vec3 morphTarget1;",
  15218. "attribute vec3 morphTarget2;",
  15219. "attribute vec3 morphTarget3;",
  15220. "#ifdef USE_MORPHNORMALS",
  15221. "attribute vec3 morphNormal0;",
  15222. "attribute vec3 morphNormal1;",
  15223. "attribute vec3 morphNormal2;",
  15224. "attribute vec3 morphNormal3;",
  15225. "#else",
  15226. "attribute vec3 morphTarget4;",
  15227. "attribute vec3 morphTarget5;",
  15228. "attribute vec3 morphTarget6;",
  15229. "attribute vec3 morphTarget7;",
  15230. "#endif",
  15231. "#endif",
  15232. "#ifdef USE_SKINNING",
  15233. "attribute vec4 skinIndex;",
  15234. "attribute vec4 skinWeight;",
  15235. "#endif",
  15236. ""
  15237. ].join("\n");
  15238. var prefix_fragment = [
  15239. "precision " + _precision + " float;",
  15240. "precision " + _precision + " int;",
  15241. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15242. customDefines,
  15243. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15244. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15245. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15246. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15247. "#define MAX_SHADOWS " + parameters.maxShadows,
  15248. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15249. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15250. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15251. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15252. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15253. parameters.map ? "#define USE_MAP" : "",
  15254. parameters.envMap ? "#define USE_ENVMAP" : "",
  15255. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15256. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15257. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15258. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15259. parameters.vertexColors ? "#define USE_COLOR" : "",
  15260. parameters.metal ? "#define METAL" : "",
  15261. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15262. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15263. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15264. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15265. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15266. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15267. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15268. "uniform mat4 viewMatrix;",
  15269. "uniform vec3 cameraPosition;",
  15270. ""
  15271. ].join("\n");
  15272. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  15273. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  15274. _gl.attachShader( program, glVertexShader );
  15275. _gl.attachShader( program, glFragmentShader );
  15276. // Force a particular attribute to index 0.
  15277. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  15278. // And, color, for example is often automatically bound to index 0 so disabling it
  15279. if ( index0AttributeName !== undefined ) {
  15280. _gl.bindAttribLocation( program, 0, index0AttributeName );
  15281. }
  15282. _gl.linkProgram( program );
  15283. if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) {
  15284. console.error( 'Could not initialise shader' );
  15285. console.error( 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) );
  15286. console.error( 'gl.getError()', _gl.getError() );
  15287. }
  15288. if ( _gl.getProgramInfoLog( program ) !== '' ) {
  15289. console.error( 'gl.getProgramInfoLog()', _gl.getProgramInfoLog( program ) );
  15290. }
  15291. // clean up
  15292. _gl.deleteShader( glFragmentShader );
  15293. _gl.deleteShader( glVertexShader );
  15294. // console.log( prefix_fragment + fragmentShader );
  15295. // console.log( prefix_vertex + vertexShader );
  15296. program.uniforms = {};
  15297. program.attributes = {};
  15298. var identifiers, u, a, i;
  15299. // cache uniform locations
  15300. identifiers = [
  15301. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15302. 'morphTargetInfluences'
  15303. ];
  15304. if ( parameters.useVertexTexture ) {
  15305. identifiers.push( 'boneTexture' );
  15306. identifiers.push( 'boneTextureWidth' );
  15307. identifiers.push( 'boneTextureHeight' );
  15308. } else {
  15309. identifiers.push( 'boneGlobalMatrices' );
  15310. }
  15311. for ( u in uniforms ) {
  15312. identifiers.push( u );
  15313. }
  15314. cacheUniformLocations( program, identifiers );
  15315. // cache attributes locations
  15316. identifiers = [
  15317. "position", "normal", "uv", "uv2", "tangent", "color",
  15318. "skinIndex", "skinWeight", "lineDistance"
  15319. ];
  15320. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  15321. identifiers.push( "morphTarget" + i );
  15322. }
  15323. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  15324. identifiers.push( "morphNormal" + i );
  15325. }
  15326. for ( a in attributes ) {
  15327. identifiers.push( a );
  15328. }
  15329. cacheAttributeLocations( program, identifiers );
  15330. program.id = _programs_counter ++;
  15331. _programs.push( { program: program, code: code, usedTimes: 1 } );
  15332. _this.info.memory.programs = _programs.length;
  15333. return program;
  15334. };
  15335. // Shader parameters cache
  15336. function cacheUniformLocations ( program, identifiers ) {
  15337. var i, l, id;
  15338. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15339. id = identifiers[ i ];
  15340. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  15341. }
  15342. };
  15343. function cacheAttributeLocations ( program, identifiers ) {
  15344. var i, l, id;
  15345. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15346. id = identifiers[ i ];
  15347. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  15348. }
  15349. };
  15350. function addLineNumbers ( string ) {
  15351. var chunks = string.split( "\n" );
  15352. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  15353. // Chrome reports shader errors on lines
  15354. // starting counting from 1
  15355. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  15356. }
  15357. return chunks.join( "\n" );
  15358. };
  15359. function getShader ( type, string ) {
  15360. var shader;
  15361. if ( type === "fragment" ) {
  15362. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  15363. } else if ( type === "vertex" ) {
  15364. shader = _gl.createShader( _gl.VERTEX_SHADER );
  15365. }
  15366. _gl.shaderSource( shader, string );
  15367. _gl.compileShader( shader );
  15368. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  15369. console.error( _gl.getShaderInfoLog( shader ) );
  15370. console.error( addLineNumbers( string ) );
  15371. return null;
  15372. }
  15373. return shader;
  15374. };
  15375. // Textures
  15376. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15377. if ( isImagePowerOfTwo ) {
  15378. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15379. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15380. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15381. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15382. } else {
  15383. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15384. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15385. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15386. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15387. }
  15388. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15389. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15390. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15391. texture.__oldAnisotropy = texture.anisotropy;
  15392. }
  15393. }
  15394. };
  15395. this.setTexture = function ( texture, slot ) {
  15396. if ( texture.needsUpdate ) {
  15397. if ( ! texture.__webglInit ) {
  15398. texture.__webglInit = true;
  15399. texture.addEventListener( 'dispose', onTextureDispose );
  15400. texture.__webglTexture = _gl.createTexture();
  15401. _this.info.memory.textures ++;
  15402. }
  15403. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15404. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15405. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15406. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15407. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15408. var image = texture.image,
  15409. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15410. glFormat = paramThreeToGL( texture.format ),
  15411. glType = paramThreeToGL( texture.type );
  15412. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15413. var mipmap, mipmaps = texture.mipmaps;
  15414. if ( texture instanceof THREE.DataTexture ) {
  15415. // use manually created mipmaps if available
  15416. // if there are no manual mipmaps
  15417. // set 0 level mipmap and then use GL to generate other mipmap levels
  15418. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15419. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15420. mipmap = mipmaps[ i ];
  15421. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15422. }
  15423. texture.generateMipmaps = false;
  15424. } else {
  15425. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15426. }
  15427. } else if ( texture instanceof THREE.CompressedTexture ) {
  15428. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15429. mipmap = mipmaps[ i ];
  15430. if ( texture.format!==THREE.RGBAFormat ) {
  15431. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15432. } else {
  15433. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15434. }
  15435. }
  15436. } else { // regular Texture (image, video, canvas)
  15437. // use manually created mipmaps if available
  15438. // if there are no manual mipmaps
  15439. // set 0 level mipmap and then use GL to generate other mipmap levels
  15440. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15441. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15442. mipmap = mipmaps[ i ];
  15443. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15444. }
  15445. texture.generateMipmaps = false;
  15446. } else {
  15447. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15448. }
  15449. }
  15450. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15451. texture.needsUpdate = false;
  15452. if ( texture.onUpdate ) texture.onUpdate();
  15453. } else {
  15454. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15455. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15456. }
  15457. };
  15458. function clampToMaxSize ( image, maxSize ) {
  15459. if ( image.width <= maxSize && image.height <= maxSize ) {
  15460. return image;
  15461. }
  15462. // Warning: Scaling through the canvas will only work with images that use
  15463. // premultiplied alpha.
  15464. var maxDimension = Math.max( image.width, image.height );
  15465. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15466. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15467. var canvas = document.createElement( 'canvas' );
  15468. canvas.width = newWidth;
  15469. canvas.height = newHeight;
  15470. var ctx = canvas.getContext( "2d" );
  15471. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15472. return canvas;
  15473. }
  15474. function setCubeTexture ( texture, slot ) {
  15475. if ( texture.image.length === 6 ) {
  15476. if ( texture.needsUpdate ) {
  15477. if ( ! texture.image.__webglTextureCube ) {
  15478. texture.addEventListener( 'dispose', onTextureDispose );
  15479. texture.image.__webglTextureCube = _gl.createTexture();
  15480. _this.info.memory.textures ++;
  15481. }
  15482. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15483. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15484. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15485. var isCompressed = texture instanceof THREE.CompressedTexture;
  15486. var cubeImage = [];
  15487. for ( var i = 0; i < 6; i ++ ) {
  15488. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15489. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15490. } else {
  15491. cubeImage[ i ] = texture.image[ i ];
  15492. }
  15493. }
  15494. var image = cubeImage[ 0 ],
  15495. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15496. glFormat = paramThreeToGL( texture.format ),
  15497. glType = paramThreeToGL( texture.type );
  15498. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15499. for ( var i = 0; i < 6; i ++ ) {
  15500. if( !isCompressed ) {
  15501. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15502. } else {
  15503. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15504. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15505. mipmap = mipmaps[ j ];
  15506. if ( texture.format!==THREE.RGBAFormat ) {
  15507. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15508. } else {
  15509. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15510. }
  15511. }
  15512. }
  15513. }
  15514. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15515. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15516. }
  15517. texture.needsUpdate = false;
  15518. if ( texture.onUpdate ) texture.onUpdate();
  15519. } else {
  15520. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15521. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15522. }
  15523. }
  15524. };
  15525. function setCubeTextureDynamic ( texture, slot ) {
  15526. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15527. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15528. };
  15529. // Render targets
  15530. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15531. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15532. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15533. };
  15534. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15535. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15536. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15537. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15538. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15539. /* For some reason this is not working. Defaulting to RGBA4.
  15540. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15541. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15542. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15543. */
  15544. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15545. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15546. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15547. } else {
  15548. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15549. }
  15550. };
  15551. this.setRenderTarget = function ( renderTarget ) {
  15552. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15553. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15554. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15555. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15556. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15557. renderTarget.__webglTexture = _gl.createTexture();
  15558. _this.info.memory.textures ++;
  15559. // Setup texture, create render and frame buffers
  15560. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  15561. glFormat = paramThreeToGL( renderTarget.format ),
  15562. glType = paramThreeToGL( renderTarget.type );
  15563. if ( isCube ) {
  15564. renderTarget.__webglFramebuffer = [];
  15565. renderTarget.__webglRenderbuffer = [];
  15566. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15567. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15568. for ( var i = 0; i < 6; i ++ ) {
  15569. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15570. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15571. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15572. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15573. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15574. }
  15575. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15576. } else {
  15577. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15578. if ( renderTarget.shareDepthFrom ) {
  15579. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15580. } else {
  15581. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15582. }
  15583. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15584. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15585. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15586. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15587. if ( renderTarget.shareDepthFrom ) {
  15588. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15589. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15590. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15591. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15592. }
  15593. } else {
  15594. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15595. }
  15596. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15597. }
  15598. // Release everything
  15599. if ( isCube ) {
  15600. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15601. } else {
  15602. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15603. }
  15604. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15605. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15606. }
  15607. var framebuffer, width, height, vx, vy;
  15608. if ( renderTarget ) {
  15609. if ( isCube ) {
  15610. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15611. } else {
  15612. framebuffer = renderTarget.__webglFramebuffer;
  15613. }
  15614. width = renderTarget.width;
  15615. height = renderTarget.height;
  15616. vx = 0;
  15617. vy = 0;
  15618. } else {
  15619. framebuffer = null;
  15620. width = _viewportWidth;
  15621. height = _viewportHeight;
  15622. vx = _viewportX;
  15623. vy = _viewportY;
  15624. }
  15625. if ( framebuffer !== _currentFramebuffer ) {
  15626. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15627. _gl.viewport( vx, vy, width, height );
  15628. _currentFramebuffer = framebuffer;
  15629. }
  15630. _currentWidth = width;
  15631. _currentHeight = height;
  15632. };
  15633. function updateRenderTargetMipmap ( renderTarget ) {
  15634. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15635. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15636. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15637. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15638. } else {
  15639. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15640. _gl.generateMipmap( _gl.TEXTURE_2D );
  15641. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15642. }
  15643. };
  15644. // Fallback filters for non-power-of-2 textures
  15645. function filterFallback ( f ) {
  15646. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15647. return _gl.NEAREST;
  15648. }
  15649. return _gl.LINEAR;
  15650. };
  15651. // Map three.js constants to WebGL constants
  15652. function paramThreeToGL ( p ) {
  15653. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15654. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15655. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15656. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15657. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15658. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15659. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15660. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15661. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15662. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15663. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15664. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15665. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15666. if ( p === THREE.ByteType ) return _gl.BYTE;
  15667. if ( p === THREE.ShortType ) return _gl.SHORT;
  15668. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15669. if ( p === THREE.IntType ) return _gl.INT;
  15670. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15671. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15672. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15673. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15674. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15675. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15676. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15677. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15678. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15679. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15680. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15681. if ( p === THREE.OneFactor ) return _gl.ONE;
  15682. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15683. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15684. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15685. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15686. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15687. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15688. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15689. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15690. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15691. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15692. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15693. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15694. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15695. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15696. }
  15697. return 0;
  15698. };
  15699. // Allocations
  15700. function allocateBones ( object ) {
  15701. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15702. return 1024;
  15703. } else {
  15704. // default for when object is not specified
  15705. // ( for example when prebuilding shader
  15706. // to be used with multiple objects )
  15707. //
  15708. // - leave some extra space for other uniforms
  15709. // - limit here is ANGLE's 254 max uniform vectors
  15710. // (up to 54 should be safe)
  15711. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15712. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15713. var maxBones = nVertexMatrices;
  15714. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15715. maxBones = Math.min( object.bones.length, maxBones );
  15716. if ( maxBones < object.bones.length ) {
  15717. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15718. }
  15719. }
  15720. return maxBones;
  15721. }
  15722. };
  15723. function allocateLights( lights ) {
  15724. var dirLights = 0;
  15725. var pointLights = 0;
  15726. var spotLights = 0;
  15727. var hemiLights = 0;
  15728. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15729. var light = lights[ l ];
  15730. if ( light.onlyShadow || light.visible === false ) continue;
  15731. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15732. if ( light instanceof THREE.PointLight ) pointLights ++;
  15733. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15734. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15735. }
  15736. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15737. };
  15738. function allocateShadows( lights ) {
  15739. var maxShadows = 0;
  15740. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15741. var light = lights[ l ];
  15742. if ( ! light.castShadow ) continue;
  15743. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15744. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15745. }
  15746. return maxShadows;
  15747. };
  15748. // Initialization
  15749. function initGL() {
  15750. try {
  15751. var attributes = {
  15752. alpha: _alpha,
  15753. premultipliedAlpha: _premultipliedAlpha,
  15754. antialias: _antialias,
  15755. stencil: _stencil,
  15756. preserveDrawingBuffer: _preserveDrawingBuffer
  15757. };
  15758. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15759. if ( _gl === null ) {
  15760. throw 'Error creating WebGL context.';
  15761. }
  15762. } catch ( error ) {
  15763. console.error( error );
  15764. }
  15765. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15766. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15767. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15768. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15769. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15770. if ( ! _glExtensionTextureFloat ) {
  15771. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15772. }
  15773. if ( ! _glExtensionStandardDerivatives ) {
  15774. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15775. }
  15776. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15777. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15778. }
  15779. if ( ! _glExtensionCompressedTextureS3TC ) {
  15780. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15781. }
  15782. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15783. _gl.getShaderPrecisionFormat = function() {
  15784. return {
  15785. "rangeMin" : 1,
  15786. "rangeMax" : 1,
  15787. "precision" : 1
  15788. };
  15789. }
  15790. }
  15791. };
  15792. function setDefaultGLState () {
  15793. _gl.clearColor( 0, 0, 0, 1 );
  15794. _gl.clearDepth( 1 );
  15795. _gl.clearStencil( 0 );
  15796. _gl.enable( _gl.DEPTH_TEST );
  15797. _gl.depthFunc( _gl.LEQUAL );
  15798. _gl.frontFace( _gl.CCW );
  15799. _gl.cullFace( _gl.BACK );
  15800. _gl.enable( _gl.CULL_FACE );
  15801. _gl.enable( _gl.BLEND );
  15802. _gl.blendEquation( _gl.FUNC_ADD );
  15803. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15804. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  15805. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15806. };
  15807. // default plugins (order is important)
  15808. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15809. this.addPrePlugin( this.shadowMapPlugin );
  15810. this.addPostPlugin( new THREE.SpritePlugin() );
  15811. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15812. };
  15813. /**
  15814. * @author szimek / https://github.com/szimek/
  15815. * @author alteredq / http://alteredqualia.com/
  15816. */
  15817. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15818. this.width = width;
  15819. this.height = height;
  15820. options = options || {};
  15821. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15822. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15823. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15824. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15825. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15826. this.offset = new THREE.Vector2( 0, 0 );
  15827. this.repeat = new THREE.Vector2( 1, 1 );
  15828. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15829. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15830. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15831. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15832. this.generateMipmaps = true;
  15833. this.shareDepthFrom = null;
  15834. };
  15835. THREE.WebGLRenderTarget.prototype = {
  15836. constructor: THREE.WebGLRenderTarget,
  15837. clone: function () {
  15838. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15839. tmp.wrapS = this.wrapS;
  15840. tmp.wrapT = this.wrapT;
  15841. tmp.magFilter = this.magFilter;
  15842. tmp.minFilter = this.minFilter;
  15843. tmp.anisotropy = this.anisotropy;
  15844. tmp.offset.copy( this.offset );
  15845. tmp.repeat.copy( this.repeat );
  15846. tmp.format = this.format;
  15847. tmp.type = this.type;
  15848. tmp.depthBuffer = this.depthBuffer;
  15849. tmp.stencilBuffer = this.stencilBuffer;
  15850. tmp.generateMipmaps = this.generateMipmaps;
  15851. tmp.shareDepthFrom = this.shareDepthFrom;
  15852. return tmp;
  15853. },
  15854. dispose: function () {
  15855. this.dispatchEvent( { type: 'dispose' } );
  15856. }
  15857. };
  15858. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15859. /**
  15860. * @author alteredq / http://alteredqualia.com
  15861. */
  15862. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15863. THREE.WebGLRenderTarget.call( this, width, height, options );
  15864. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15865. };
  15866. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15867. /**
  15868. * @author mrdoob / http://mrdoob.com/
  15869. */
  15870. THREE.RenderableVertex = function () {
  15871. this.position = new THREE.Vector3();
  15872. this.positionWorld = new THREE.Vector3();
  15873. this.positionScreen = new THREE.Vector4();
  15874. this.visible = true;
  15875. };
  15876. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15877. this.positionWorld.copy( vertex.positionWorld );
  15878. this.positionScreen.copy( vertex.positionScreen );
  15879. };
  15880. /**
  15881. * @author mrdoob / http://mrdoob.com/
  15882. */
  15883. THREE.RenderableFace = function () {
  15884. this.id = 0;
  15885. this.v1 = new THREE.RenderableVertex();
  15886. this.v2 = new THREE.RenderableVertex();
  15887. this.v3 = new THREE.RenderableVertex();
  15888. this.centroidModel = new THREE.Vector3();
  15889. this.normalModel = new THREE.Vector3();
  15890. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15891. this.vertexNormalsLength = 0;
  15892. this.color = null;
  15893. this.material = null;
  15894. this.uvs = [[]];
  15895. this.z = 0;
  15896. };
  15897. /**
  15898. * @author mrdoob / http://mrdoob.com/
  15899. */
  15900. THREE.RenderableObject = function () {
  15901. this.id = 0;
  15902. this.object = null;
  15903. this.z = 0;
  15904. };
  15905. /**
  15906. * @author mrdoob / http://mrdoob.com/
  15907. */
  15908. THREE.RenderableSprite = function () {
  15909. this.id = 0;
  15910. this.object = null;
  15911. this.x = 0;
  15912. this.y = 0;
  15913. this.z = 0;
  15914. this.rotation = 0;
  15915. this.scale = new THREE.Vector2();
  15916. this.material = null;
  15917. };
  15918. /**
  15919. * @author mrdoob / http://mrdoob.com/
  15920. */
  15921. THREE.RenderableLine = function () {
  15922. this.id = 0;
  15923. this.v1 = new THREE.RenderableVertex();
  15924. this.v2 = new THREE.RenderableVertex();
  15925. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15926. this.material = null;
  15927. this.z = 0;
  15928. };
  15929. /**
  15930. * @author mrdoob / http://mrdoob.com/
  15931. * @author alteredq / http://alteredqualia.com/
  15932. */
  15933. THREE.GeometryUtils = {
  15934. // Merge two geometries or geometry and geometry from object (using object's transform)
  15935. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15936. var matrix, normalMatrix,
  15937. vertexOffset = geometry1.vertices.length,
  15938. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15939. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15940. vertices1 = geometry1.vertices,
  15941. vertices2 = geometry2.vertices,
  15942. faces1 = geometry1.faces,
  15943. faces2 = geometry2.faces,
  15944. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15945. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15946. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15947. if ( object2 instanceof THREE.Mesh ) {
  15948. object2.matrixAutoUpdate && object2.updateMatrix();
  15949. matrix = object2.matrix;
  15950. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15951. }
  15952. // vertices
  15953. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15954. var vertex = vertices2[ i ];
  15955. var vertexCopy = vertex.clone();
  15956. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15957. vertices1.push( vertexCopy );
  15958. }
  15959. // faces
  15960. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15961. var face = faces2[ i ], faceCopy, normal, color,
  15962. faceVertexNormals = face.vertexNormals,
  15963. faceVertexColors = face.vertexColors;
  15964. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15965. faceCopy.normal.copy( face.normal );
  15966. if ( normalMatrix ) {
  15967. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15968. }
  15969. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15970. normal = faceVertexNormals[ j ].clone();
  15971. if ( normalMatrix ) {
  15972. normal.applyMatrix3( normalMatrix ).normalize();
  15973. }
  15974. faceCopy.vertexNormals.push( normal );
  15975. }
  15976. faceCopy.color.copy( face.color );
  15977. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15978. color = faceVertexColors[ j ];
  15979. faceCopy.vertexColors.push( color.clone() );
  15980. }
  15981. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15982. faceCopy.centroid.copy( face.centroid );
  15983. if ( matrix ) {
  15984. faceCopy.centroid.applyMatrix4( matrix );
  15985. }
  15986. faces1.push( faceCopy );
  15987. }
  15988. // uvs
  15989. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15990. var uv = uvs2[ i ], uvCopy = [];
  15991. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15992. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15993. }
  15994. uvs1.push( uvCopy );
  15995. }
  15996. },
  15997. // Get random point in triangle (via barycentric coordinates)
  15998. // (uniform distribution)
  15999. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  16000. randomPointInTriangle: function () {
  16001. var vector = new THREE.Vector3();
  16002. return function ( vectorA, vectorB, vectorC ) {
  16003. var point = new THREE.Vector3();
  16004. var a = THREE.Math.random16();
  16005. var b = THREE.Math.random16();
  16006. if ( ( a + b ) > 1 ) {
  16007. a = 1 - a;
  16008. b = 1 - b;
  16009. }
  16010. var c = 1 - a - b;
  16011. point.copy( vectorA );
  16012. point.multiplyScalar( a );
  16013. vector.copy( vectorB );
  16014. vector.multiplyScalar( b );
  16015. point.add( vector );
  16016. vector.copy( vectorC );
  16017. vector.multiplyScalar( c );
  16018. point.add( vector );
  16019. return point;
  16020. };
  16021. }(),
  16022. // Get random point in face (triangle / quad)
  16023. // (uniform distribution)
  16024. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  16025. var vA, vB, vC, vD;
  16026. vA = geometry.vertices[ face.a ];
  16027. vB = geometry.vertices[ face.b ];
  16028. vC = geometry.vertices[ face.c ];
  16029. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  16030. },
  16031. // Get uniformly distributed random points in mesh
  16032. // - create array with cumulative sums of face areas
  16033. // - pick random number from 0 to total area
  16034. // - find corresponding place in area array by binary search
  16035. // - get random point in face
  16036. randomPointsInGeometry: function ( geometry, n ) {
  16037. var face, i,
  16038. faces = geometry.faces,
  16039. vertices = geometry.vertices,
  16040. il = faces.length,
  16041. totalArea = 0,
  16042. cumulativeAreas = [],
  16043. vA, vB, vC, vD;
  16044. // precompute face areas
  16045. for ( i = 0; i < il; i ++ ) {
  16046. face = faces[ i ];
  16047. vA = vertices[ face.a ];
  16048. vB = vertices[ face.b ];
  16049. vC = vertices[ face.c ];
  16050. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  16051. totalArea += face._area;
  16052. cumulativeAreas[ i ] = totalArea;
  16053. }
  16054. // binary search cumulative areas array
  16055. function binarySearchIndices( value ) {
  16056. function binarySearch( start, end ) {
  16057. // return closest larger index
  16058. // if exact number is not found
  16059. if ( end < start )
  16060. return start;
  16061. var mid = start + Math.floor( ( end - start ) / 2 );
  16062. if ( cumulativeAreas[ mid ] > value ) {
  16063. return binarySearch( start, mid - 1 );
  16064. } else if ( cumulativeAreas[ mid ] < value ) {
  16065. return binarySearch( mid + 1, end );
  16066. } else {
  16067. return mid;
  16068. }
  16069. }
  16070. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  16071. return result;
  16072. }
  16073. // pick random face weighted by face area
  16074. var r, index,
  16075. result = [];
  16076. var stats = {};
  16077. for ( i = 0; i < n; i ++ ) {
  16078. r = THREE.Math.random16() * totalArea;
  16079. index = binarySearchIndices( r );
  16080. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  16081. if ( ! stats[ index ] ) {
  16082. stats[ index ] = 1;
  16083. } else {
  16084. stats[ index ] += 1;
  16085. }
  16086. }
  16087. return result;
  16088. },
  16089. // Get triangle area (half of parallelogram)
  16090. // http://mathworld.wolfram.com/TriangleArea.html
  16091. triangleArea: function () {
  16092. var vector1 = new THREE.Vector3();
  16093. var vector2 = new THREE.Vector3();
  16094. return function ( vectorA, vectorB, vectorC ) {
  16095. vector1.subVectors( vectorB, vectorA );
  16096. vector2.subVectors( vectorC, vectorA );
  16097. vector1.cross( vector2 );
  16098. return 0.5 * vector1.length();
  16099. };
  16100. }(),
  16101. // Center geometry so that 0,0,0 is in center of bounding box
  16102. center: function ( geometry ) {
  16103. geometry.computeBoundingBox();
  16104. var bb = geometry.boundingBox;
  16105. var offset = new THREE.Vector3();
  16106. offset.addVectors( bb.min, bb.max );
  16107. offset.multiplyScalar( -0.5 );
  16108. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  16109. geometry.computeBoundingBox();
  16110. return offset;
  16111. },
  16112. triangulateQuads: function ( geometry ) {
  16113. var i, il, j, jl;
  16114. var faces = [];
  16115. var faceVertexUvs = [];
  16116. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  16117. faceVertexUvs[ i ] = [];
  16118. }
  16119. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  16120. var face = geometry.faces[ i ];
  16121. faces.push( face );
  16122. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  16123. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  16124. }
  16125. }
  16126. geometry.faces = faces;
  16127. geometry.faceVertexUvs = faceVertexUvs;
  16128. geometry.computeCentroids();
  16129. geometry.computeFaceNormals();
  16130. geometry.computeVertexNormals();
  16131. if ( geometry.hasTangents ) geometry.computeTangents();
  16132. }
  16133. };
  16134. /**
  16135. * @author alteredq / http://alteredqualia.com/
  16136. * @author mrdoob / http://mrdoob.com/
  16137. */
  16138. THREE.ImageUtils = {
  16139. crossOrigin: undefined,
  16140. loadTexture: function ( url, mapping, onLoad, onError ) {
  16141. var loader = new THREE.ImageLoader();
  16142. loader.crossOrigin = this.crossOrigin;
  16143. var texture = new THREE.Texture( undefined, mapping );
  16144. var image = loader.load( url, function () {
  16145. texture.needsUpdate = true;
  16146. if ( onLoad ) onLoad( texture );
  16147. } );
  16148. texture.image = image;
  16149. texture.sourceFile = url;
  16150. return texture;
  16151. },
  16152. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  16153. var texture = new THREE.CompressedTexture();
  16154. texture.mapping = mapping;
  16155. var request = new XMLHttpRequest();
  16156. request.onload = function () {
  16157. var buffer = request.response;
  16158. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16159. texture.format = dds.format;
  16160. texture.mipmaps = dds.mipmaps;
  16161. texture.image.width = dds.width;
  16162. texture.image.height = dds.height;
  16163. // gl.generateMipmap fails for compressed textures
  16164. // mipmaps must be embedded in the DDS file
  16165. // or texture filters must not use mipmapping
  16166. texture.generateMipmaps = false;
  16167. texture.needsUpdate = true;
  16168. if ( onLoad ) onLoad( texture );
  16169. }
  16170. request.onerror = onError;
  16171. request.open( 'GET', url, true );
  16172. request.responseType = "arraybuffer";
  16173. request.send( null );
  16174. return texture;
  16175. },
  16176. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  16177. var images = [];
  16178. images.loadCount = 0;
  16179. var texture = new THREE.Texture();
  16180. texture.image = images;
  16181. if ( mapping !== undefined ) texture.mapping = mapping;
  16182. // no flipping needed for cube textures
  16183. texture.flipY = false;
  16184. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16185. var cubeImage = new Image();
  16186. images[ i ] = cubeImage;
  16187. cubeImage.onload = function () {
  16188. images.loadCount += 1;
  16189. if ( images.loadCount === 6 ) {
  16190. texture.needsUpdate = true;
  16191. if ( onLoad ) onLoad( texture );
  16192. }
  16193. };
  16194. cubeImage.onerror = onError;
  16195. cubeImage.crossOrigin = this.crossOrigin;
  16196. cubeImage.src = array[ i ];
  16197. }
  16198. return texture;
  16199. },
  16200. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  16201. var images = [];
  16202. images.loadCount = 0;
  16203. var texture = new THREE.CompressedTexture();
  16204. texture.image = images;
  16205. if ( mapping !== undefined ) texture.mapping = mapping;
  16206. // no flipping for cube textures
  16207. // (also flipping doesn't work for compressed textures )
  16208. texture.flipY = false;
  16209. // can't generate mipmaps for compressed textures
  16210. // mips must be embedded in DDS files
  16211. texture.generateMipmaps = false;
  16212. var generateCubeFaceCallback = function ( rq, img ) {
  16213. return function () {
  16214. var buffer = rq.response;
  16215. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16216. img.format = dds.format;
  16217. img.mipmaps = dds.mipmaps;
  16218. img.width = dds.width;
  16219. img.height = dds.height;
  16220. images.loadCount += 1;
  16221. if ( images.loadCount === 6 ) {
  16222. texture.format = dds.format;
  16223. texture.needsUpdate = true;
  16224. if ( onLoad ) onLoad( texture );
  16225. }
  16226. }
  16227. }
  16228. // compressed cubemap textures as 6 separate DDS files
  16229. if ( array instanceof Array ) {
  16230. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16231. var cubeImage = {};
  16232. images[ i ] = cubeImage;
  16233. var request = new XMLHttpRequest();
  16234. request.onload = generateCubeFaceCallback( request, cubeImage );
  16235. request.onerror = onError;
  16236. var url = array[ i ];
  16237. request.open( 'GET', url, true );
  16238. request.responseType = "arraybuffer";
  16239. request.send( null );
  16240. }
  16241. // compressed cubemap texture stored in a single DDS file
  16242. } else {
  16243. var url = array;
  16244. var request = new XMLHttpRequest();
  16245. request.onload = function( ) {
  16246. var buffer = request.response;
  16247. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16248. if ( dds.isCubemap ) {
  16249. var faces = dds.mipmaps.length / dds.mipmapCount;
  16250. for ( var f = 0; f < faces; f ++ ) {
  16251. images[ f ] = { mipmaps : [] };
  16252. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16253. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16254. images[ f ].format = dds.format;
  16255. images[ f ].width = dds.width;
  16256. images[ f ].height = dds.height;
  16257. }
  16258. }
  16259. texture.format = dds.format;
  16260. texture.needsUpdate = true;
  16261. if ( onLoad ) onLoad( texture );
  16262. }
  16263. }
  16264. request.onerror = onError;
  16265. request.open( 'GET', url, true );
  16266. request.responseType = "arraybuffer";
  16267. request.send( null );
  16268. }
  16269. return texture;
  16270. },
  16271. loadDDSTexture: function ( url, mapping, onLoad, onError ) {
  16272. var images = [];
  16273. images.loadCount = 0;
  16274. var texture = new THREE.CompressedTexture();
  16275. texture.image = images;
  16276. if ( mapping !== undefined ) texture.mapping = mapping;
  16277. // no flipping for cube textures
  16278. // (also flipping doesn't work for compressed textures )
  16279. texture.flipY = false;
  16280. // can't generate mipmaps for compressed textures
  16281. // mips must be embedded in DDS files
  16282. texture.generateMipmaps = false;
  16283. {
  16284. var request = new XMLHttpRequest();
  16285. request.onload = function( ) {
  16286. var buffer = request.response;
  16287. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16288. if ( dds.isCubemap ) {
  16289. var faces = dds.mipmaps.length / dds.mipmapCount;
  16290. for ( var f = 0; f < faces; f ++ ) {
  16291. images[ f ] = { mipmaps : [] };
  16292. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16293. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16294. images[ f ].format = dds.format;
  16295. images[ f ].width = dds.width;
  16296. images[ f ].height = dds.height;
  16297. }
  16298. }
  16299. } else {
  16300. texture.image.width = dds.width;
  16301. texture.image.height = dds.height;
  16302. texture.mipmaps = dds.mipmaps;
  16303. }
  16304. texture.format = dds.format;
  16305. texture.needsUpdate = true;
  16306. if ( onLoad ) onLoad( texture );
  16307. }
  16308. request.onerror = onError;
  16309. request.open( 'GET', url, true );
  16310. request.responseType = "arraybuffer";
  16311. request.send( null );
  16312. }
  16313. return texture;
  16314. },
  16315. parseDDS: function ( buffer, loadMipmaps ) {
  16316. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  16317. // Adapted from @toji's DDS utils
  16318. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  16319. // All values and structures referenced from:
  16320. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  16321. var DDS_MAGIC = 0x20534444;
  16322. var DDSD_CAPS = 0x1,
  16323. DDSD_HEIGHT = 0x2,
  16324. DDSD_WIDTH = 0x4,
  16325. DDSD_PITCH = 0x8,
  16326. DDSD_PIXELFORMAT = 0x1000,
  16327. DDSD_MIPMAPCOUNT = 0x20000,
  16328. DDSD_LINEARSIZE = 0x80000,
  16329. DDSD_DEPTH = 0x800000;
  16330. var DDSCAPS_COMPLEX = 0x8,
  16331. DDSCAPS_MIPMAP = 0x400000,
  16332. DDSCAPS_TEXTURE = 0x1000;
  16333. var DDSCAPS2_CUBEMAP = 0x200,
  16334. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  16335. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  16336. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  16337. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  16338. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  16339. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  16340. DDSCAPS2_VOLUME = 0x200000;
  16341. var DDPF_ALPHAPIXELS = 0x1,
  16342. DDPF_ALPHA = 0x2,
  16343. DDPF_FOURCC = 0x4,
  16344. DDPF_RGB = 0x40,
  16345. DDPF_YUV = 0x200,
  16346. DDPF_LUMINANCE = 0x20000;
  16347. function fourCCToInt32( value ) {
  16348. return value.charCodeAt(0) +
  16349. (value.charCodeAt(1) << 8) +
  16350. (value.charCodeAt(2) << 16) +
  16351. (value.charCodeAt(3) << 24);
  16352. }
  16353. function int32ToFourCC( value ) {
  16354. return String.fromCharCode(
  16355. value & 0xff,
  16356. (value >> 8) & 0xff,
  16357. (value >> 16) & 0xff,
  16358. (value >> 24) & 0xff
  16359. );
  16360. }
  16361. function loadARGBMip( buffer, dataOffset, width, height ) {
  16362. var dataLength = width*height*4;
  16363. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  16364. var byteArray = new Uint8Array( dataLength );
  16365. var dst = 0;
  16366. var src = 0;
  16367. for ( var y = 0; y < height; y++ ) {
  16368. for ( var x = 0; x < width; x++ ) {
  16369. var b = srcBuffer[src]; src++;
  16370. var g = srcBuffer[src]; src++;
  16371. var r = srcBuffer[src]; src++;
  16372. var a = srcBuffer[src]; src++;
  16373. byteArray[dst] = r; dst++; //r
  16374. byteArray[dst] = g; dst++; //g
  16375. byteArray[dst] = b; dst++; //b
  16376. byteArray[dst] = a; dst++; //a
  16377. }
  16378. }
  16379. return byteArray;
  16380. }
  16381. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  16382. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  16383. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  16384. var headerLengthInt = 31; // The header length in 32 bit ints
  16385. // Offsets into the header array
  16386. var off_magic = 0;
  16387. var off_size = 1;
  16388. var off_flags = 2;
  16389. var off_height = 3;
  16390. var off_width = 4;
  16391. var off_mipmapCount = 7;
  16392. var off_pfFlags = 20;
  16393. var off_pfFourCC = 21;
  16394. var off_RGBBitCount = 22;
  16395. var off_RBitMask = 23;
  16396. var off_GBitMask = 24;
  16397. var off_BBitMask = 25;
  16398. var off_ABitMask = 26;
  16399. var off_caps = 27;
  16400. var off_caps2 = 28;
  16401. var off_caps3 = 29;
  16402. var off_caps4 = 30;
  16403. // Parse header
  16404. var header = new Int32Array( buffer, 0, headerLengthInt );
  16405. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16406. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16407. return dds;
  16408. }
  16409. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16410. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16411. return dds;
  16412. }
  16413. var blockBytes;
  16414. var fourCC = header[ off_pfFourCC ];
  16415. var isRGBAUncompressed = false;
  16416. switch ( fourCC ) {
  16417. case FOURCC_DXT1:
  16418. blockBytes = 8;
  16419. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16420. break;
  16421. case FOURCC_DXT3:
  16422. blockBytes = 16;
  16423. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16424. break;
  16425. case FOURCC_DXT5:
  16426. blockBytes = 16;
  16427. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16428. break;
  16429. default:
  16430. if( header[off_RGBBitCount] ==32
  16431. && header[off_RBitMask]&0xff0000
  16432. && header[off_GBitMask]&0xff00
  16433. && header[off_BBitMask]&0xff
  16434. && header[off_ABitMask]&0xff000000 ) {
  16435. isRGBAUncompressed = true;
  16436. blockBytes = 64;
  16437. dds.format = THREE.RGBAFormat;
  16438. } else {
  16439. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16440. return dds;
  16441. }
  16442. }
  16443. dds.mipmapCount = 1;
  16444. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16445. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16446. }
  16447. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16448. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16449. dds.width = header[ off_width ];
  16450. dds.height = header[ off_height ];
  16451. var dataOffset = header[ off_size ] + 4;
  16452. // Extract mipmaps buffers
  16453. var width = dds.width;
  16454. var height = dds.height;
  16455. var faces = dds.isCubemap ? 6 : 1;
  16456. for ( var face = 0; face < faces; face ++ ) {
  16457. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16458. if( isRGBAUncompressed ) {
  16459. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  16460. var dataLength = byteArray.length;
  16461. } else {
  16462. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16463. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16464. }
  16465. var mipmap = { "data": byteArray, "width": width, "height": height };
  16466. dds.mipmaps.push( mipmap );
  16467. dataOffset += dataLength;
  16468. width = Math.max( width * 0.5, 1 );
  16469. height = Math.max( height * 0.5, 1 );
  16470. }
  16471. width = dds.width;
  16472. height = dds.height;
  16473. }
  16474. return dds;
  16475. },
  16476. getNormalMap: function ( image, depth ) {
  16477. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16478. var cross = function ( a, b ) {
  16479. 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 ] ];
  16480. }
  16481. var subtract = function ( a, b ) {
  16482. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16483. }
  16484. var normalize = function ( a ) {
  16485. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16486. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16487. }
  16488. depth = depth | 1;
  16489. var width = image.width;
  16490. var height = image.height;
  16491. var canvas = document.createElement( 'canvas' );
  16492. canvas.width = width;
  16493. canvas.height = height;
  16494. var context = canvas.getContext( '2d' );
  16495. context.drawImage( image, 0, 0 );
  16496. var data = context.getImageData( 0, 0, width, height ).data;
  16497. var imageData = context.createImageData( width, height );
  16498. var output = imageData.data;
  16499. for ( var x = 0; x < width; x ++ ) {
  16500. for ( var y = 0; y < height; y ++ ) {
  16501. var ly = y - 1 < 0 ? 0 : y - 1;
  16502. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16503. var lx = x - 1 < 0 ? 0 : x - 1;
  16504. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16505. var points = [];
  16506. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16507. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16508. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16509. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16510. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16511. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16512. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16513. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16514. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16515. var normals = [];
  16516. var num_points = points.length;
  16517. for ( var i = 0; i < num_points; i ++ ) {
  16518. var v1 = points[ i ];
  16519. var v2 = points[ ( i + 1 ) % num_points ];
  16520. v1 = subtract( v1, origin );
  16521. v2 = subtract( v2, origin );
  16522. normals.push( normalize( cross( v1, v2 ) ) );
  16523. }
  16524. var normal = [ 0, 0, 0 ];
  16525. for ( var i = 0; i < normals.length; i ++ ) {
  16526. normal[ 0 ] += normals[ i ][ 0 ];
  16527. normal[ 1 ] += normals[ i ][ 1 ];
  16528. normal[ 2 ] += normals[ i ][ 2 ];
  16529. }
  16530. normal[ 0 ] /= normals.length;
  16531. normal[ 1 ] /= normals.length;
  16532. normal[ 2 ] /= normals.length;
  16533. var idx = ( y * width + x ) * 4;
  16534. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16535. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16536. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16537. output[ idx + 3 ] = 255;
  16538. }
  16539. }
  16540. context.putImageData( imageData, 0, 0 );
  16541. return canvas;
  16542. },
  16543. generateDataTexture: function ( width, height, color ) {
  16544. var size = width * height;
  16545. var data = new Uint8Array( 3 * size );
  16546. var r = Math.floor( color.r * 255 );
  16547. var g = Math.floor( color.g * 255 );
  16548. var b = Math.floor( color.b * 255 );
  16549. for ( var i = 0; i < size; i ++ ) {
  16550. data[ i * 3 ] = r;
  16551. data[ i * 3 + 1 ] = g;
  16552. data[ i * 3 + 2 ] = b;
  16553. }
  16554. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16555. texture.needsUpdate = true;
  16556. return texture;
  16557. }
  16558. };
  16559. /**
  16560. * @author alteredq / http://alteredqualia.com/
  16561. */
  16562. THREE.SceneUtils = {
  16563. createMultiMaterialObject: function ( geometry, materials ) {
  16564. var group = new THREE.Object3D();
  16565. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16566. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16567. }
  16568. return group;
  16569. },
  16570. detach : function ( child, parent, scene ) {
  16571. child.applyMatrix( parent.matrixWorld );
  16572. parent.remove( child );
  16573. scene.add( child );
  16574. },
  16575. attach: function ( child, scene, parent ) {
  16576. var matrixWorldInverse = new THREE.Matrix4();
  16577. matrixWorldInverse.getInverse( parent.matrixWorld );
  16578. child.applyMatrix( matrixWorldInverse );
  16579. scene.remove( child );
  16580. parent.add( child );
  16581. }
  16582. };
  16583. /**
  16584. * @author zz85 / http://www.lab4games.net/zz85/blog
  16585. * @author alteredq / http://alteredqualia.com/
  16586. *
  16587. * For Text operations in three.js (See TextGeometry)
  16588. *
  16589. * It uses techniques used in:
  16590. *
  16591. * typeface.js and canvastext
  16592. * For converting fonts and rendering with javascript
  16593. * http://typeface.neocracy.org
  16594. *
  16595. * Triangulation ported from AS3
  16596. * Simple Polygon Triangulation
  16597. * http://actionsnippet.com/?p=1462
  16598. *
  16599. * A Method to triangulate shapes with holes
  16600. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16601. *
  16602. */
  16603. THREE.FontUtils = {
  16604. faces : {},
  16605. // Just for now. face[weight][style]
  16606. face : "helvetiker",
  16607. weight: "normal",
  16608. style : "normal",
  16609. size : 150,
  16610. divisions : 10,
  16611. getFace : function() {
  16612. return this.faces[ this.face ][ this.weight ][ this.style ];
  16613. },
  16614. loadFace : function( data ) {
  16615. var family = data.familyName.toLowerCase();
  16616. var ThreeFont = this;
  16617. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16618. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16619. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16620. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16621. return data;
  16622. },
  16623. drawText : function( text ) {
  16624. var characterPts = [], allPts = [];
  16625. // RenderText
  16626. var i, p,
  16627. face = this.getFace(),
  16628. scale = this.size / face.resolution,
  16629. offset = 0,
  16630. chars = String( text ).split( '' ),
  16631. length = chars.length;
  16632. var fontPaths = [];
  16633. for ( i = 0; i < length; i ++ ) {
  16634. var path = new THREE.Path();
  16635. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16636. offset += ret.offset;
  16637. fontPaths.push( ret.path );
  16638. }
  16639. // get the width
  16640. var width = offset / 2;
  16641. //
  16642. // for ( p = 0; p < allPts.length; p++ ) {
  16643. //
  16644. // allPts[ p ].x -= width;
  16645. //
  16646. // }
  16647. //var extract = this.extractPoints( allPts, characterPts );
  16648. //extract.contour = allPts;
  16649. //extract.paths = fontPaths;
  16650. //extract.offset = width;
  16651. return { paths : fontPaths, offset : width };
  16652. },
  16653. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16654. var pts = [];
  16655. var i, i2, divisions,
  16656. outline, action, length,
  16657. scaleX, scaleY,
  16658. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16659. laste,
  16660. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16661. if ( !glyph ) return;
  16662. if ( glyph.o ) {
  16663. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16664. length = outline.length;
  16665. scaleX = scale;
  16666. scaleY = scale;
  16667. for ( i = 0; i < length; ) {
  16668. action = outline[ i ++ ];
  16669. //console.log( action );
  16670. switch( action ) {
  16671. case 'm':
  16672. // Move To
  16673. x = outline[ i++ ] * scaleX + offset;
  16674. y = outline[ i++ ] * scaleY;
  16675. path.moveTo( x, y );
  16676. break;
  16677. case 'l':
  16678. // Line To
  16679. x = outline[ i++ ] * scaleX + offset;
  16680. y = outline[ i++ ] * scaleY;
  16681. path.lineTo(x,y);
  16682. break;
  16683. case 'q':
  16684. // QuadraticCurveTo
  16685. cpx = outline[ i++ ] * scaleX + offset;
  16686. cpy = outline[ i++ ] * scaleY;
  16687. cpx1 = outline[ i++ ] * scaleX + offset;
  16688. cpy1 = outline[ i++ ] * scaleY;
  16689. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16690. laste = pts[ pts.length - 1 ];
  16691. if ( laste ) {
  16692. cpx0 = laste.x;
  16693. cpy0 = laste.y;
  16694. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16695. var t = i2 / divisions;
  16696. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16697. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16698. }
  16699. }
  16700. break;
  16701. case 'b':
  16702. // Cubic Bezier Curve
  16703. cpx = outline[ i++ ] * scaleX + offset;
  16704. cpy = outline[ i++ ] * scaleY;
  16705. cpx1 = outline[ i++ ] * scaleX + offset;
  16706. cpy1 = outline[ i++ ] * -scaleY;
  16707. cpx2 = outline[ i++ ] * scaleX + offset;
  16708. cpy2 = outline[ i++ ] * -scaleY;
  16709. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16710. laste = pts[ pts.length - 1 ];
  16711. if ( laste ) {
  16712. cpx0 = laste.x;
  16713. cpy0 = laste.y;
  16714. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16715. var t = i2 / divisions;
  16716. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16717. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16718. }
  16719. }
  16720. break;
  16721. }
  16722. }
  16723. }
  16724. return { offset: glyph.ha*scale, path:path};
  16725. }
  16726. };
  16727. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16728. // Parameters
  16729. parameters = parameters || {};
  16730. var size = parameters.size !== undefined ? parameters.size : 100;
  16731. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16732. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16733. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16734. var style = parameters.style !== undefined ? parameters.style : "normal";
  16735. THREE.FontUtils.size = size;
  16736. THREE.FontUtils.divisions = curveSegments;
  16737. THREE.FontUtils.face = font;
  16738. THREE.FontUtils.weight = weight;
  16739. THREE.FontUtils.style = style;
  16740. // Get a Font data json object
  16741. var data = THREE.FontUtils.drawText( text );
  16742. var paths = data.paths;
  16743. var shapes = [];
  16744. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16745. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16746. }
  16747. return shapes;
  16748. };
  16749. /**
  16750. * This code is a quick port of code written in C++ which was submitted to
  16751. * flipcode.com by John W. Ratcliff // July 22, 2000
  16752. * See original code and more information here:
  16753. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16754. *
  16755. * ported to actionscript by Zevan Rosser
  16756. * www.actionsnippet.com
  16757. *
  16758. * ported to javascript by Joshua Koo
  16759. * http://www.lab4games.net/zz85/blog
  16760. *
  16761. */
  16762. ( function( namespace ) {
  16763. var EPSILON = 0.0000000001;
  16764. // takes in an contour array and returns
  16765. var process = function( contour, indices ) {
  16766. var n = contour.length;
  16767. if ( n < 3 ) return null;
  16768. var result = [],
  16769. verts = [],
  16770. vertIndices = [];
  16771. /* we want a counter-clockwise polygon in verts */
  16772. var u, v, w;
  16773. if ( area( contour ) > 0.0 ) {
  16774. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16775. } else {
  16776. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16777. }
  16778. var nv = n;
  16779. /* remove nv - 2 vertices, creating 1 triangle every time */
  16780. var count = 2 * nv; /* error detection */
  16781. for( v = nv - 1; nv > 2; ) {
  16782. /* if we loop, it is probably a non-simple polygon */
  16783. if ( ( count-- ) <= 0 ) {
  16784. //** Triangulate: ERROR - probable bad polygon!
  16785. //throw ( "Warning, unable to triangulate polygon!" );
  16786. //return null;
  16787. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16788. console.log( "Warning, unable to triangulate polygon!" );
  16789. if ( indices ) return vertIndices;
  16790. return result;
  16791. }
  16792. /* three consecutive vertices in current polygon, <u,v,w> */
  16793. u = v; if ( nv <= u ) u = 0; /* previous */
  16794. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16795. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16796. if ( snip( contour, u, v, w, nv, verts ) ) {
  16797. var a, b, c, s, t;
  16798. /* true names of the vertices */
  16799. a = verts[ u ];
  16800. b = verts[ v ];
  16801. c = verts[ w ];
  16802. /* output Triangle */
  16803. result.push( [ contour[ a ],
  16804. contour[ b ],
  16805. contour[ c ] ] );
  16806. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16807. /* remove v from the remaining polygon */
  16808. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16809. verts[ s ] = verts[ t ];
  16810. }
  16811. nv--;
  16812. /* reset error detection counter */
  16813. count = 2 * nv;
  16814. }
  16815. }
  16816. if ( indices ) return vertIndices;
  16817. return result;
  16818. };
  16819. // calculate area of the contour polygon
  16820. var area = function ( contour ) {
  16821. var n = contour.length;
  16822. var a = 0.0;
  16823. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16824. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16825. }
  16826. return a * 0.5;
  16827. };
  16828. var snip = function ( contour, u, v, w, n, verts ) {
  16829. var p;
  16830. var ax, ay, bx, by;
  16831. var cx, cy, px, py;
  16832. ax = contour[ verts[ u ] ].x;
  16833. ay = contour[ verts[ u ] ].y;
  16834. bx = contour[ verts[ v ] ].x;
  16835. by = contour[ verts[ v ] ].y;
  16836. cx = contour[ verts[ w ] ].x;
  16837. cy = contour[ verts[ w ] ].y;
  16838. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16839. var aX, aY, bX, bY, cX, cY;
  16840. var apx, apy, bpx, bpy, cpx, cpy;
  16841. var cCROSSap, bCROSScp, aCROSSbp;
  16842. aX = cx - bx; aY = cy - by;
  16843. bX = ax - cx; bY = ay - cy;
  16844. cX = bx - ax; cY = by - ay;
  16845. for ( p = 0; p < n; p++ ) {
  16846. px = contour[ verts[ p ] ].x
  16847. py = contour[ verts[ p ] ].y
  16848. if ( ( (px === ax) && (py === ay) ) ||
  16849. ( (px === bx) && (py === by) ) ||
  16850. ( (px === cx) && (py === cy) ) ) continue;
  16851. apx = px - ax; apy = py - ay;
  16852. bpx = px - bx; bpy = py - by;
  16853. cpx = px - cx; cpy = py - cy;
  16854. // see if p is inside triangle abc
  16855. aCROSSbp = aX*bpy - aY*bpx;
  16856. cCROSSap = cX*apy - cY*apx;
  16857. bCROSScp = bX*cpy - bY*cpx;
  16858. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  16859. }
  16860. return true;
  16861. };
  16862. namespace.Triangulate = process;
  16863. namespace.Triangulate.area = area;
  16864. return namespace;
  16865. })(THREE.FontUtils);
  16866. // To use the typeface.js face files, hook up the API
  16867. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16868. THREE.typeface_js = self._typeface_js;
  16869. /**
  16870. * @author zz85 / http://www.lab4games.net/zz85/blog
  16871. * Extensible curve object
  16872. *
  16873. * Some common of Curve methods
  16874. * .getPoint(t), getTangent(t)
  16875. * .getPointAt(u), getTagentAt(u)
  16876. * .getPoints(), .getSpacedPoints()
  16877. * .getLength()
  16878. * .updateArcLengths()
  16879. *
  16880. * This following classes subclasses THREE.Curve:
  16881. *
  16882. * -- 2d classes --
  16883. * THREE.LineCurve
  16884. * THREE.QuadraticBezierCurve
  16885. * THREE.CubicBezierCurve
  16886. * THREE.SplineCurve
  16887. * THREE.ArcCurve
  16888. * THREE.EllipseCurve
  16889. *
  16890. * -- 3d classes --
  16891. * THREE.LineCurve3
  16892. * THREE.QuadraticBezierCurve3
  16893. * THREE.CubicBezierCurve3
  16894. * THREE.SplineCurve3
  16895. * THREE.ClosedSplineCurve3
  16896. *
  16897. * A series of curves can be represented as a THREE.CurvePath
  16898. *
  16899. **/
  16900. /**************************************************************
  16901. * Abstract Curve base class
  16902. **************************************************************/
  16903. THREE.Curve = function () {
  16904. };
  16905. // Virtual base class method to overwrite and implement in subclasses
  16906. // - t [0 .. 1]
  16907. THREE.Curve.prototype.getPoint = function ( t ) {
  16908. console.log( "Warning, getPoint() not implemented!" );
  16909. return null;
  16910. };
  16911. // Get point at relative position in curve according to arc length
  16912. // - u [0 .. 1]
  16913. THREE.Curve.prototype.getPointAt = function ( u ) {
  16914. var t = this.getUtoTmapping( u );
  16915. return this.getPoint( t );
  16916. };
  16917. // Get sequence of points using getPoint( t )
  16918. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16919. if ( !divisions ) divisions = 5;
  16920. var d, pts = [];
  16921. for ( d = 0; d <= divisions; d ++ ) {
  16922. pts.push( this.getPoint( d / divisions ) );
  16923. }
  16924. return pts;
  16925. };
  16926. // Get sequence of points using getPointAt( u )
  16927. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16928. if ( !divisions ) divisions = 5;
  16929. var d, pts = [];
  16930. for ( d = 0; d <= divisions; d ++ ) {
  16931. pts.push( this.getPointAt( d / divisions ) );
  16932. }
  16933. return pts;
  16934. };
  16935. // Get total curve arc length
  16936. THREE.Curve.prototype.getLength = function () {
  16937. var lengths = this.getLengths();
  16938. return lengths[ lengths.length - 1 ];
  16939. };
  16940. // Get list of cumulative segment lengths
  16941. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16942. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16943. if ( this.cacheArcLengths
  16944. && ( this.cacheArcLengths.length == divisions + 1 )
  16945. && !this.needsUpdate) {
  16946. //console.log( "cached", this.cacheArcLengths );
  16947. return this.cacheArcLengths;
  16948. }
  16949. this.needsUpdate = false;
  16950. var cache = [];
  16951. var current, last = this.getPoint( 0 );
  16952. var p, sum = 0;
  16953. cache.push( 0 );
  16954. for ( p = 1; p <= divisions; p ++ ) {
  16955. current = this.getPoint ( p / divisions );
  16956. sum += current.distanceTo( last );
  16957. cache.push( sum );
  16958. last = current;
  16959. }
  16960. this.cacheArcLengths = cache;
  16961. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16962. };
  16963. THREE.Curve.prototype.updateArcLengths = function() {
  16964. this.needsUpdate = true;
  16965. this.getLengths();
  16966. };
  16967. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16968. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16969. var arcLengths = this.getLengths();
  16970. var i = 0, il = arcLengths.length;
  16971. var targetArcLength; // The targeted u distance value to get
  16972. if ( distance ) {
  16973. targetArcLength = distance;
  16974. } else {
  16975. targetArcLength = u * arcLengths[ il - 1 ];
  16976. }
  16977. //var time = Date.now();
  16978. // binary search for the index with largest value smaller than target u distance
  16979. var low = 0, high = il - 1, comparison;
  16980. while ( low <= high ) {
  16981. 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
  16982. comparison = arcLengths[ i ] - targetArcLength;
  16983. if ( comparison < 0 ) {
  16984. low = i + 1;
  16985. continue;
  16986. } else if ( comparison > 0 ) {
  16987. high = i - 1;
  16988. continue;
  16989. } else {
  16990. high = i;
  16991. break;
  16992. // DONE
  16993. }
  16994. }
  16995. i = high;
  16996. //console.log('b' , i, low, high, Date.now()- time);
  16997. if ( arcLengths[ i ] == targetArcLength ) {
  16998. var t = i / ( il - 1 );
  16999. return t;
  17000. }
  17001. // we could get finer grain at lengths, or use simple interpolatation between two points
  17002. var lengthBefore = arcLengths[ i ];
  17003. var lengthAfter = arcLengths[ i + 1 ];
  17004. var segmentLength = lengthAfter - lengthBefore;
  17005. // determine where we are between the 'before' and 'after' points
  17006. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  17007. // add that fractional amount to t
  17008. var t = ( i + segmentFraction ) / ( il -1 );
  17009. return t;
  17010. };
  17011. // Returns a unit vector tangent at t
  17012. // In case any sub curve does not implement its tangent derivation,
  17013. // 2 points a small delta apart will be used to find its gradient
  17014. // which seems to give a reasonable approximation
  17015. THREE.Curve.prototype.getTangent = function( t ) {
  17016. var delta = 0.0001;
  17017. var t1 = t - delta;
  17018. var t2 = t + delta;
  17019. // Capping in case of danger
  17020. if ( t1 < 0 ) t1 = 0;
  17021. if ( t2 > 1 ) t2 = 1;
  17022. var pt1 = this.getPoint( t1 );
  17023. var pt2 = this.getPoint( t2 );
  17024. var vec = pt2.clone().sub(pt1);
  17025. return vec.normalize();
  17026. };
  17027. THREE.Curve.prototype.getTangentAt = function ( u ) {
  17028. var t = this.getUtoTmapping( u );
  17029. return this.getTangent( t );
  17030. };
  17031. /**************************************************************
  17032. * Utils
  17033. **************************************************************/
  17034. THREE.Curve.Utils = {
  17035. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  17036. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  17037. },
  17038. // Puay Bing, thanks for helping with this derivative!
  17039. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  17040. return -3 * p0 * (1 - t) * (1 - t) +
  17041. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  17042. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  17043. 3 * t * t * p3;
  17044. },
  17045. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  17046. // To check if my formulas are correct
  17047. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  17048. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  17049. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  17050. var h11 = 3 * t * t - 2 * t; // t3 − t2
  17051. return h00 + h10 + h01 + h11;
  17052. },
  17053. // Catmull-Rom
  17054. interpolate: function( p0, p1, p2, p3, t ) {
  17055. var v0 = ( p2 - p0 ) * 0.5;
  17056. var v1 = ( p3 - p1 ) * 0.5;
  17057. var t2 = t * t;
  17058. var t3 = t * t2;
  17059. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17060. }
  17061. };
  17062. // TODO: Transformation for Curves?
  17063. /**************************************************************
  17064. * 3D Curves
  17065. **************************************************************/
  17066. // A Factory method for creating new curve subclasses
  17067. THREE.Curve.create = function ( constructor, getPointFunc ) {
  17068. constructor.prototype = Object.create( THREE.Curve.prototype );
  17069. constructor.prototype.getPoint = getPointFunc;
  17070. return constructor;
  17071. };
  17072. /**
  17073. * @author zz85 / http://www.lab4games.net/zz85/blog
  17074. *
  17075. **/
  17076. /**************************************************************
  17077. * Curved Path - a curve path is simply a array of connected
  17078. * curves, but retains the api of a curve
  17079. **************************************************************/
  17080. THREE.CurvePath = function () {
  17081. this.curves = [];
  17082. this.bends = [];
  17083. this.autoClose = false; // Automatically closes the path
  17084. };
  17085. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  17086. THREE.CurvePath.prototype.add = function ( curve ) {
  17087. this.curves.push( curve );
  17088. };
  17089. THREE.CurvePath.prototype.checkConnection = function() {
  17090. // TODO
  17091. // If the ending of curve is not connected to the starting
  17092. // or the next curve, then, this is not a real path
  17093. };
  17094. THREE.CurvePath.prototype.closePath = function() {
  17095. // TODO Test
  17096. // and verify for vector3 (needs to implement equals)
  17097. // Add a line curve if start and end of lines are not connected
  17098. var startPoint = this.curves[0].getPoint(0);
  17099. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  17100. if (!startPoint.equals(endPoint)) {
  17101. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  17102. }
  17103. };
  17104. // To get accurate point with reference to
  17105. // entire path distance at time t,
  17106. // following has to be done:
  17107. // 1. Length of each sub path have to be known
  17108. // 2. Locate and identify type of curve
  17109. // 3. Get t for the curve
  17110. // 4. Return curve.getPointAt(t')
  17111. THREE.CurvePath.prototype.getPoint = function( t ) {
  17112. var d = t * this.getLength();
  17113. var curveLengths = this.getCurveLengths();
  17114. var i = 0, diff, curve;
  17115. // To think about boundaries points.
  17116. while ( i < curveLengths.length ) {
  17117. if ( curveLengths[ i ] >= d ) {
  17118. diff = curveLengths[ i ] - d;
  17119. curve = this.curves[ i ];
  17120. var u = 1 - diff / curve.getLength();
  17121. return curve.getPointAt( u );
  17122. break;
  17123. }
  17124. i ++;
  17125. }
  17126. return null;
  17127. // loop where sum != 0, sum > d , sum+1 <d
  17128. };
  17129. /*
  17130. THREE.CurvePath.prototype.getTangent = function( t ) {
  17131. };*/
  17132. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17133. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17134. // getPoint() depends on getLength
  17135. THREE.CurvePath.prototype.getLength = function() {
  17136. var lens = this.getCurveLengths();
  17137. return lens[ lens.length - 1 ];
  17138. };
  17139. // Compute lengths and cache them
  17140. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17141. THREE.CurvePath.prototype.getCurveLengths = function() {
  17142. // We use cache values if curves and cache array are same length
  17143. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  17144. return this.cacheLengths;
  17145. };
  17146. // Get length of subsurve
  17147. // Push sums into cached array
  17148. var lengths = [], sums = 0;
  17149. var i, il = this.curves.length;
  17150. for ( i = 0; i < il; i ++ ) {
  17151. sums += this.curves[ i ].getLength();
  17152. lengths.push( sums );
  17153. }
  17154. this.cacheLengths = lengths;
  17155. return lengths;
  17156. };
  17157. // Returns min and max coordinates, as well as centroid
  17158. THREE.CurvePath.prototype.getBoundingBox = function () {
  17159. var points = this.getPoints();
  17160. var maxX, maxY, maxZ;
  17161. var minX, minY, minZ;
  17162. maxX = maxY = Number.NEGATIVE_INFINITY;
  17163. minX = minY = Number.POSITIVE_INFINITY;
  17164. var p, i, il, sum;
  17165. var v3 = points[0] instanceof THREE.Vector3;
  17166. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  17167. for ( i = 0, il = points.length; i < il; i ++ ) {
  17168. p = points[ i ];
  17169. if ( p.x > maxX ) maxX = p.x;
  17170. else if ( p.x < minX ) minX = p.x;
  17171. if ( p.y > maxY ) maxY = p.y;
  17172. else if ( p.y < minY ) minY = p.y;
  17173. if ( v3 ) {
  17174. if ( p.z > maxZ ) maxZ = p.z;
  17175. else if ( p.z < minZ ) minZ = p.z;
  17176. }
  17177. sum.add( p );
  17178. }
  17179. var ret = {
  17180. minX: minX,
  17181. minY: minY,
  17182. maxX: maxX,
  17183. maxY: maxY,
  17184. centroid: sum.divideScalar( il )
  17185. };
  17186. if ( v3 ) {
  17187. ret.maxZ = maxZ;
  17188. ret.minZ = minZ;
  17189. }
  17190. return ret;
  17191. };
  17192. /**************************************************************
  17193. * Create Geometries Helpers
  17194. **************************************************************/
  17195. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17196. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17197. var pts = this.getPoints( divisions, true );
  17198. return this.createGeometry( pts );
  17199. };
  17200. // Generate geometry from equidistance sampling along the path
  17201. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17202. var pts = this.getSpacedPoints( divisions, true );
  17203. return this.createGeometry( pts );
  17204. };
  17205. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17206. var geometry = new THREE.Geometry();
  17207. for ( var i = 0; i < points.length; i ++ ) {
  17208. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17209. }
  17210. return geometry;
  17211. };
  17212. /**************************************************************
  17213. * Bend / Wrap Helper Methods
  17214. **************************************************************/
  17215. // Wrap path / Bend modifiers?
  17216. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17217. this.bends.push( bendpath );
  17218. };
  17219. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17220. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17221. var i, il;
  17222. if ( !bends ) {
  17223. bends = this.bends;
  17224. }
  17225. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17226. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17227. }
  17228. return oldPts;
  17229. };
  17230. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17231. var oldPts = this.getSpacedPoints( segments );
  17232. var i, il;
  17233. if ( !bends ) {
  17234. bends = this.bends;
  17235. }
  17236. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17237. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17238. }
  17239. return oldPts;
  17240. };
  17241. // This returns getPoints() bend/wrapped around the contour of a path.
  17242. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17243. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17244. var bounds = this.getBoundingBox();
  17245. var i, il, p, oldX, oldY, xNorm;
  17246. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17247. p = oldPts[ i ];
  17248. oldX = p.x;
  17249. oldY = p.y;
  17250. xNorm = oldX / bounds.maxX;
  17251. // If using actual distance, for length > path, requires line extrusions
  17252. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17253. xNorm = path.getUtoTmapping( xNorm, oldX );
  17254. // check for out of bounds?
  17255. var pathPt = path.getPoint( xNorm );
  17256. var normal = path.getTangent( xNorm );
  17257. normal.set( -normal.y, normal.x ).multiplyScalar( oldY );
  17258. p.x = pathPt.x + normal.x;
  17259. p.y = pathPt.y + normal.y;
  17260. }
  17261. return oldPts;
  17262. };
  17263. /**
  17264. * @author alteredq / http://alteredqualia.com/
  17265. */
  17266. THREE.Gyroscope = function () {
  17267. THREE.Object3D.call( this );
  17268. };
  17269. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17270. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17271. this.matrixAutoUpdate && this.updateMatrix();
  17272. // update matrixWorld
  17273. if ( this.matrixWorldNeedsUpdate || force ) {
  17274. if ( this.parent ) {
  17275. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17276. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  17277. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  17278. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  17279. } else {
  17280. this.matrixWorld.copy( this.matrix );
  17281. }
  17282. this.matrixWorldNeedsUpdate = false;
  17283. force = true;
  17284. }
  17285. // update children
  17286. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17287. this.children[ i ].updateMatrixWorld( force );
  17288. }
  17289. };
  17290. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17291. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17292. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  17293. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  17294. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17295. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17296. /**
  17297. * @author zz85 / http://www.lab4games.net/zz85/blog
  17298. * Creates free form 2d path using series of points, lines or curves.
  17299. *
  17300. **/
  17301. THREE.Path = function ( points ) {
  17302. THREE.CurvePath.call(this);
  17303. this.actions = [];
  17304. if ( points ) {
  17305. this.fromPoints( points );
  17306. }
  17307. };
  17308. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17309. THREE.PathActions = {
  17310. MOVE_TO: 'moveTo',
  17311. LINE_TO: 'lineTo',
  17312. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17313. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17314. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17315. ARC: 'arc', // Circle
  17316. ELLIPSE: 'ellipse'
  17317. };
  17318. // TODO Clean up PATH API
  17319. // Create path using straight lines to connect all points
  17320. // - vectors: array of Vector2
  17321. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17322. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17323. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17324. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17325. };
  17326. };
  17327. // startPath() endPath()?
  17328. THREE.Path.prototype.moveTo = function ( x, y ) {
  17329. var args = Array.prototype.slice.call( arguments );
  17330. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17331. };
  17332. THREE.Path.prototype.lineTo = function ( x, y ) {
  17333. var args = Array.prototype.slice.call( arguments );
  17334. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17335. var x0 = lastargs[ lastargs.length - 2 ];
  17336. var y0 = lastargs[ lastargs.length - 1 ];
  17337. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17338. this.curves.push( curve );
  17339. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17340. };
  17341. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17342. var args = Array.prototype.slice.call( arguments );
  17343. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17344. var x0 = lastargs[ lastargs.length - 2 ];
  17345. var y0 = lastargs[ lastargs.length - 1 ];
  17346. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17347. new THREE.Vector2( aCPx, aCPy ),
  17348. new THREE.Vector2( aX, aY ) );
  17349. this.curves.push( curve );
  17350. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17351. };
  17352. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17353. aCP2x, aCP2y,
  17354. aX, aY ) {
  17355. var args = Array.prototype.slice.call( arguments );
  17356. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17357. var x0 = lastargs[ lastargs.length - 2 ];
  17358. var y0 = lastargs[ lastargs.length - 1 ];
  17359. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17360. new THREE.Vector2( aCP1x, aCP1y ),
  17361. new THREE.Vector2( aCP2x, aCP2y ),
  17362. new THREE.Vector2( aX, aY ) );
  17363. this.curves.push( curve );
  17364. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17365. };
  17366. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17367. var args = Array.prototype.slice.call( arguments );
  17368. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17369. var x0 = lastargs[ lastargs.length - 2 ];
  17370. var y0 = lastargs[ lastargs.length - 1 ];
  17371. //---
  17372. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17373. Array.prototype.push.apply( npts, pts );
  17374. var curve = new THREE.SplineCurve( npts );
  17375. this.curves.push( curve );
  17376. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17377. };
  17378. // FUTURE: Change the API or follow canvas API?
  17379. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17380. aStartAngle, aEndAngle, aClockwise ) {
  17381. var lastargs = this.actions[ this.actions.length - 1].args;
  17382. var x0 = lastargs[ lastargs.length - 2 ];
  17383. var y0 = lastargs[ lastargs.length - 1 ];
  17384. this.absarc(aX + x0, aY + y0, aRadius,
  17385. aStartAngle, aEndAngle, aClockwise );
  17386. };
  17387. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17388. aStartAngle, aEndAngle, aClockwise ) {
  17389. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17390. };
  17391. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17392. aStartAngle, aEndAngle, aClockwise ) {
  17393. var lastargs = this.actions[ this.actions.length - 1].args;
  17394. var x0 = lastargs[ lastargs.length - 2 ];
  17395. var y0 = lastargs[ lastargs.length - 1 ];
  17396. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17397. aStartAngle, aEndAngle, aClockwise );
  17398. };
  17399. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17400. aStartAngle, aEndAngle, aClockwise ) {
  17401. var args = Array.prototype.slice.call( arguments );
  17402. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17403. aStartAngle, aEndAngle, aClockwise );
  17404. this.curves.push( curve );
  17405. var lastPoint = curve.getPoint(1);
  17406. args.push(lastPoint.x);
  17407. args.push(lastPoint.y);
  17408. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17409. };
  17410. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17411. if ( ! divisions ) divisions = 40;
  17412. var points = [];
  17413. for ( var i = 0; i < divisions; i ++ ) {
  17414. points.push( this.getPoint( i / divisions ) );
  17415. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17416. }
  17417. // if ( closedPath ) {
  17418. //
  17419. // points.push( points[ 0 ] );
  17420. //
  17421. // }
  17422. return points;
  17423. };
  17424. /* Return an array of vectors based on contour of the path */
  17425. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17426. if (this.useSpacedPoints) {
  17427. console.log('tata');
  17428. return this.getSpacedPoints( divisions, closedPath );
  17429. }
  17430. divisions = divisions || 12;
  17431. var points = [];
  17432. var i, il, item, action, args;
  17433. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17434. laste, j,
  17435. t, tx, ty;
  17436. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17437. item = this.actions[ i ];
  17438. action = item.action;
  17439. args = item.args;
  17440. switch( action ) {
  17441. case THREE.PathActions.MOVE_TO:
  17442. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17443. break;
  17444. case THREE.PathActions.LINE_TO:
  17445. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17446. break;
  17447. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17448. cpx = args[ 2 ];
  17449. cpy = args[ 3 ];
  17450. cpx1 = args[ 0 ];
  17451. cpy1 = args[ 1 ];
  17452. if ( points.length > 0 ) {
  17453. laste = points[ points.length - 1 ];
  17454. cpx0 = laste.x;
  17455. cpy0 = laste.y;
  17456. } else {
  17457. laste = this.actions[ i - 1 ].args;
  17458. cpx0 = laste[ laste.length - 2 ];
  17459. cpy0 = laste[ laste.length - 1 ];
  17460. }
  17461. for ( j = 1; j <= divisions; j ++ ) {
  17462. t = j / divisions;
  17463. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17464. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17465. points.push( new THREE.Vector2( tx, ty ) );
  17466. }
  17467. break;
  17468. case THREE.PathActions.BEZIER_CURVE_TO:
  17469. cpx = args[ 4 ];
  17470. cpy = args[ 5 ];
  17471. cpx1 = args[ 0 ];
  17472. cpy1 = args[ 1 ];
  17473. cpx2 = args[ 2 ];
  17474. cpy2 = args[ 3 ];
  17475. if ( points.length > 0 ) {
  17476. laste = points[ points.length - 1 ];
  17477. cpx0 = laste.x;
  17478. cpy0 = laste.y;
  17479. } else {
  17480. laste = this.actions[ i - 1 ].args;
  17481. cpx0 = laste[ laste.length - 2 ];
  17482. cpy0 = laste[ laste.length - 1 ];
  17483. }
  17484. for ( j = 1; j <= divisions; j ++ ) {
  17485. t = j / divisions;
  17486. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17487. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17488. points.push( new THREE.Vector2( tx, ty ) );
  17489. }
  17490. break;
  17491. case THREE.PathActions.CSPLINE_THRU:
  17492. laste = this.actions[ i - 1 ].args;
  17493. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17494. var spts = [ last ];
  17495. var n = divisions * args[ 0 ].length;
  17496. spts = spts.concat( args[ 0 ] );
  17497. var spline = new THREE.SplineCurve( spts );
  17498. for ( j = 1; j <= n; j ++ ) {
  17499. points.push( spline.getPointAt( j / n ) ) ;
  17500. }
  17501. break;
  17502. case THREE.PathActions.ARC:
  17503. var aX = args[ 0 ], aY = args[ 1 ],
  17504. aRadius = args[ 2 ],
  17505. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17506. aClockwise = !!args[ 5 ];
  17507. var deltaAngle = aEndAngle - aStartAngle;
  17508. var angle;
  17509. var tdivisions = divisions * 2;
  17510. for ( j = 1; j <= tdivisions; j ++ ) {
  17511. t = j / tdivisions;
  17512. if ( ! aClockwise ) {
  17513. t = 1 - t;
  17514. }
  17515. angle = aStartAngle + t * deltaAngle;
  17516. tx = aX + aRadius * Math.cos( angle );
  17517. ty = aY + aRadius * Math.sin( angle );
  17518. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17519. points.push( new THREE.Vector2( tx, ty ) );
  17520. }
  17521. //console.log(points);
  17522. break;
  17523. case THREE.PathActions.ELLIPSE:
  17524. var aX = args[ 0 ], aY = args[ 1 ],
  17525. xRadius = args[ 2 ],
  17526. yRadius = args[ 3 ],
  17527. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17528. aClockwise = !!args[ 6 ];
  17529. var deltaAngle = aEndAngle - aStartAngle;
  17530. var angle;
  17531. var tdivisions = divisions * 2;
  17532. for ( j = 1; j <= tdivisions; j ++ ) {
  17533. t = j / tdivisions;
  17534. if ( ! aClockwise ) {
  17535. t = 1 - t;
  17536. }
  17537. angle = aStartAngle + t * deltaAngle;
  17538. tx = aX + xRadius * Math.cos( angle );
  17539. ty = aY + yRadius * Math.sin( angle );
  17540. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17541. points.push( new THREE.Vector2( tx, ty ) );
  17542. }
  17543. //console.log(points);
  17544. break;
  17545. } // end switch
  17546. }
  17547. // Normalize to remove the closing point by default.
  17548. var lastPoint = points[ points.length - 1];
  17549. var EPSILON = 0.0000000001;
  17550. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17551. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17552. points.splice( points.length - 1, 1);
  17553. if ( closedPath ) {
  17554. points.push( points[ 0 ] );
  17555. }
  17556. return points;
  17557. };
  17558. // Breaks path into shapes
  17559. THREE.Path.prototype.toShapes = function( isCCW ) {
  17560. function isPointInsidePolygon( inPt, inPolygon ) {
  17561. var EPSILON = 0.0000000001;
  17562. var polyLen = inPolygon.length;
  17563. // inPt on polygon contour => immediate success or
  17564. // toggling of inside/outside at every single! intersection point of an edge
  17565. // with the horizontal line through inPt, left of inPt
  17566. // not counting lowerY endpoints of edges and whole edges on that line
  17567. var inside = false;
  17568. for( var p = polyLen - 1, q = 0; q < polyLen; p = q++ ) {
  17569. var edgeLowPt = inPolygon[ p ];
  17570. var edgeHighPt = inPolygon[ q ];
  17571. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  17572. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  17573. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  17574. if ( edgeDy < 0 ) {
  17575. edgeLowPt = inPolygon[ q ]; edgeDx = -edgeDx;
  17576. edgeHighPt = inPolygon[ p ]; edgeDy = -edgeDy;
  17577. }
  17578. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  17579. if ( inPt.y == edgeLowPt.y ) {
  17580. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  17581. // continue; // no intersection or edgeLowPt => doesn't count !!!
  17582. } else {
  17583. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  17584. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  17585. if ( perpEdge < 0 ) continue;
  17586. inside = !inside; // true intersection left of inPt
  17587. }
  17588. } else { // parallel or colinear
  17589. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  17590. // egde lies on the same horizontal line as inPt
  17591. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  17592. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  17593. // continue;
  17594. }
  17595. }
  17596. return inside;
  17597. }
  17598. var i, il, item, action, args;
  17599. var subPaths = [], lastPath = new THREE.Path();
  17600. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17601. item = this.actions[ i ];
  17602. args = item.args;
  17603. action = item.action;
  17604. if ( action == THREE.PathActions.MOVE_TO ) {
  17605. if ( lastPath.actions.length != 0 ) {
  17606. subPaths.push( lastPath );
  17607. lastPath = new THREE.Path();
  17608. }
  17609. }
  17610. lastPath[ action ].apply( lastPath, args );
  17611. }
  17612. if ( lastPath.actions.length != 0 ) {
  17613. subPaths.push( lastPath );
  17614. }
  17615. // console.log(subPaths);
  17616. if ( subPaths.length == 0 ) return [];
  17617. var solid, tmpPath, tmpShape, shapes = [];
  17618. if ( subPaths.length == 1) {
  17619. tmpPath = subPaths[0];
  17620. tmpShape = new THREE.Shape();
  17621. tmpShape.actions = tmpPath.actions;
  17622. tmpShape.curves = tmpPath.curves;
  17623. shapes.push( tmpShape );
  17624. return shapes;
  17625. }
  17626. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17627. holesFirst = isCCW ? !holesFirst : holesFirst;
  17628. // console.log("Holes first", holesFirst);
  17629. var betterShapeHoles = [];
  17630. var newShapes = [];
  17631. var newShapeHoles = [];
  17632. var mainIdx = 0;
  17633. var tmpPoints;
  17634. newShapes[mainIdx] = undefined;
  17635. newShapeHoles[mainIdx] = [];
  17636. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17637. tmpPath = subPaths[ i ];
  17638. tmpPoints = tmpPath.getPoints();
  17639. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  17640. solid = isCCW ? !solid : solid;
  17641. if ( solid ) {
  17642. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx++;
  17643. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  17644. newShapes[mainIdx].s.actions = tmpPath.actions;
  17645. newShapes[mainIdx].s.curves = tmpPath.curves;
  17646. if ( holesFirst ) mainIdx++;
  17647. newShapeHoles[mainIdx] = [];
  17648. //console.log('cw', i);
  17649. } else {
  17650. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  17651. //console.log('ccw', i);
  17652. }
  17653. }
  17654. if ( newShapes.length > 1 ) {
  17655. var ambigious = false;
  17656. var toChange = [];
  17657. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  17658. betterShapeHoles[sIdx] = [];
  17659. }
  17660. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  17661. var sh = newShapes[sIdx];
  17662. var sho = newShapeHoles[sIdx];
  17663. for (var hIdx = 0; hIdx < sho.length; hIdx++ ) {
  17664. var ho = sho[hIdx];
  17665. var hole_unassigned = true;
  17666. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++ ) {
  17667. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  17668. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  17669. if ( hole_unassigned ) {
  17670. hole_unassigned = false;
  17671. betterShapeHoles[s2Idx].push( ho );
  17672. } else {
  17673. ambigious = true;
  17674. }
  17675. }
  17676. }
  17677. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  17678. }
  17679. }
  17680. // console.log("ambigious: ", ambigious);
  17681. if ( toChange.length > 0 ) {
  17682. // console.log("to change: ", toChange);
  17683. if (! ambigious) newShapeHoles = betterShapeHoles;
  17684. }
  17685. }
  17686. var tmpHoles, j, jl;
  17687. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  17688. tmpShape = newShapes[i].s;
  17689. shapes.push( tmpShape );
  17690. tmpHoles = newShapeHoles[i];
  17691. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  17692. tmpShape.holes.push( tmpHoles[j].h );
  17693. }
  17694. }
  17695. //console.log("shape", shapes);
  17696. return shapes;
  17697. };
  17698. /**
  17699. * @author zz85 / http://www.lab4games.net/zz85/blog
  17700. * Defines a 2d shape plane using paths.
  17701. **/
  17702. // STEP 1 Create a path.
  17703. // STEP 2 Turn path into shape.
  17704. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17705. // STEP 3a - Extract points from each shape, turn to vertices
  17706. // STEP 3b - Triangulate each shape, add faces.
  17707. THREE.Shape = function () {
  17708. THREE.Path.apply( this, arguments );
  17709. this.holes = [];
  17710. };
  17711. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17712. // Convenience method to return ExtrudeGeometry
  17713. THREE.Shape.prototype.extrude = function ( options ) {
  17714. var extruded = new THREE.ExtrudeGeometry( this, options );
  17715. return extruded;
  17716. };
  17717. // Convenience method to return ShapeGeometry
  17718. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17719. var geometry = new THREE.ShapeGeometry( this, options );
  17720. return geometry;
  17721. };
  17722. // Get points of holes
  17723. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17724. var i, il = this.holes.length, holesPts = [];
  17725. for ( i = 0; i < il; i ++ ) {
  17726. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17727. }
  17728. return holesPts;
  17729. };
  17730. // Get points of holes (spaced by regular distance)
  17731. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17732. var i, il = this.holes.length, holesPts = [];
  17733. for ( i = 0; i < il; i ++ ) {
  17734. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17735. }
  17736. return holesPts;
  17737. };
  17738. // Get points of shape and holes (keypoints based on segments parameter)
  17739. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17740. return {
  17741. shape: this.getTransformedPoints( divisions ),
  17742. holes: this.getPointsHoles( divisions )
  17743. };
  17744. };
  17745. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17746. if (this.useSpacedPoints) {
  17747. return this.extractAllSpacedPoints(divisions);
  17748. }
  17749. return this.extractAllPoints(divisions);
  17750. };
  17751. //
  17752. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17753. //
  17754. // return {
  17755. //
  17756. // shape: this.transform( bend, divisions ),
  17757. // holes: this.getPointsHoles( divisions, bend )
  17758. //
  17759. // };
  17760. //
  17761. // };
  17762. // Get points of shape and holes (spaced by regular distance)
  17763. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17764. return {
  17765. shape: this.getTransformedSpacedPoints( divisions ),
  17766. holes: this.getSpacedPointsHoles( divisions )
  17767. };
  17768. };
  17769. /**************************************************************
  17770. * Utils
  17771. **************************************************************/
  17772. THREE.Shape.Utils = {
  17773. triangulateShape: function ( contour, holes ) {
  17774. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17775. // inOtherPt needs to be colinear to the inSegment
  17776. if ( inSegPt1.x != inSegPt2.x ) {
  17777. if ( inSegPt1.x < inSegPt2.x ) {
  17778. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17779. } else {
  17780. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17781. }
  17782. } else {
  17783. if ( inSegPt1.y < inSegPt2.y ) {
  17784. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17785. } else {
  17786. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17787. }
  17788. }
  17789. }
  17790. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17791. var EPSILON = 0.0000000001;
  17792. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17793. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17794. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17795. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17796. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17797. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17798. if ( Math.abs(limit) > EPSILON ) { // not parallel
  17799. var perpSeg2;
  17800. if ( limit > 0 ) {
  17801. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17802. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17803. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17804. } else {
  17805. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17806. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17807. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17808. }
  17809. // i.e. to reduce rounding errors
  17810. // intersection at endpoint of segment#1?
  17811. if ( perpSeg2 == 0 ) {
  17812. if ( ( inExcludeAdjacentSegs ) &&
  17813. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17814. return [ inSeg1Pt1 ];
  17815. }
  17816. if ( perpSeg2 == limit ) {
  17817. if ( ( inExcludeAdjacentSegs ) &&
  17818. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17819. return [ inSeg1Pt2 ];
  17820. }
  17821. // intersection at endpoint of segment#2?
  17822. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  17823. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  17824. // return real intersection point
  17825. var factorSeg1 = perpSeg2 / limit;
  17826. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17827. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17828. } else { // parallel or colinear
  17829. if ( ( perpSeg1 != 0 ) ||
  17830. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  17831. // they are collinear or degenerate
  17832. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  17833. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  17834. // both segments are points
  17835. if ( seg1Pt && seg2Pt ) {
  17836. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  17837. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  17838. return [ inSeg1Pt1 ]; // they are the same point
  17839. }
  17840. // segment#1 is a single point
  17841. if ( seg1Pt ) {
  17842. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17843. return [ inSeg1Pt1 ];
  17844. }
  17845. // segment#2 is a single point
  17846. if ( seg2Pt ) {
  17847. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17848. return [ inSeg2Pt1 ];
  17849. }
  17850. // they are collinear segments, which might overlap
  17851. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17852. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17853. if (seg1dx != 0) { // the segments are NOT on a vertical line
  17854. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17855. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17856. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17857. } else {
  17858. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17859. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17860. }
  17861. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17862. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17863. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17864. } else {
  17865. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17866. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17867. }
  17868. } else { // the segments are on a vertical line
  17869. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17870. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17871. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17872. } else {
  17873. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17874. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17875. }
  17876. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17877. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17878. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17879. } else {
  17880. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17881. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17882. }
  17883. }
  17884. if ( seg1minVal <= seg2minVal ) {
  17885. if ( seg1maxVal < seg2minVal ) return [];
  17886. if ( seg1maxVal == seg2minVal ) {
  17887. if ( inExcludeAdjacentSegs ) return [];
  17888. return [ seg2min ];
  17889. }
  17890. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17891. return [ seg2min, seg2max ];
  17892. } else {
  17893. if ( seg1minVal > seg2maxVal ) return [];
  17894. if ( seg1minVal == seg2maxVal ) {
  17895. if ( inExcludeAdjacentSegs ) return [];
  17896. return [ seg1min ];
  17897. }
  17898. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17899. return [ seg1min, seg2max ];
  17900. }
  17901. }
  17902. }
  17903. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17904. // The order of legs is important
  17905. var EPSILON = 0.0000000001;
  17906. // translation of all points, so that Vertex is at (0,0)
  17907. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17908. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17909. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17910. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17911. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17912. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17913. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  17914. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17915. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17916. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  17917. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17918. } else { // main angle > 180 deg.
  17919. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17920. }
  17921. } else { // angle == 180 deg.
  17922. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17923. return ( from2otherAngle > 0 );
  17924. }
  17925. }
  17926. function removeHoles( contour, holes ) {
  17927. var shape = contour.concat(); // work on this shape
  17928. var hole;
  17929. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17930. // Check if hole point lies within angle around shape point
  17931. var lastShapeIdx = shape.length - 1;
  17932. var prevShapeIdx = inShapeIdx - 1;
  17933. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17934. var nextShapeIdx = inShapeIdx + 1;
  17935. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17936. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  17937. if (! insideAngle ) {
  17938. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17939. return false;
  17940. }
  17941. // Check if shape point lies within angle around hole point
  17942. var lastHoleIdx = hole.length - 1;
  17943. var prevHoleIdx = inHoleIdx - 1;
  17944. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17945. var nextHoleIdx = inHoleIdx + 1;
  17946. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17947. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  17948. if (! insideAngle ) {
  17949. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17950. return false;
  17951. }
  17952. return true;
  17953. }
  17954. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17955. // checks for intersections with shape edges
  17956. var sIdx, nextIdx, intersection;
  17957. for ( sIdx = 0; sIdx < shape.length; sIdx++ ) {
  17958. nextIdx = sIdx+1; nextIdx %= shape.length;
  17959. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  17960. if ( intersection.length > 0 ) return true;
  17961. }
  17962. return false;
  17963. }
  17964. var indepHoles = [];
  17965. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17966. // checks for intersections with hole edges
  17967. var ihIdx, chkHole,
  17968. hIdx, nextIdx, intersection;
  17969. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx++ ) {
  17970. chkHole = holes[indepHoles[ihIdx]];
  17971. for ( hIdx = 0; hIdx < chkHole.length; hIdx++ ) {
  17972. nextIdx = hIdx+1; nextIdx %= chkHole.length;
  17973. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  17974. if ( intersection.length > 0 ) return true;
  17975. }
  17976. }
  17977. return false;
  17978. }
  17979. var holeIndex, shapeIndex,
  17980. shapePt, holePt,
  17981. holeIdx, cutKey, failedCuts = [],
  17982. tmpShape1, tmpShape2,
  17983. tmpHole1, tmpHole2;
  17984. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17985. indepHoles.push( h );
  17986. }
  17987. var counter = indepHoles.length * 2;
  17988. while ( indepHoles.length > 0 ) {
  17989. counter --;
  17990. if ( counter < 0 ) {
  17991. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17992. break;
  17993. }
  17994. // search for shape-vertex and hole-vertex,
  17995. // which can be connected without intersections
  17996. for ( shapeIndex = 0; shapeIndex < shape.length; shapeIndex++ ) {
  17997. shapePt = shape[ shapeIndex ];
  17998. holeIndex = -1;
  17999. // search for hole which can be reached without intersections
  18000. for ( var h = 0; h < indepHoles.length; h ++ ) {
  18001. holeIdx = indepHoles[h];
  18002. // prevent multiple checks
  18003. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  18004. if ( failedCuts[cutKey] !== undefined ) continue;
  18005. hole = holes[holeIdx];
  18006. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  18007. holePt = hole[ h2 ];
  18008. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  18009. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  18010. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  18011. holeIndex = h2;
  18012. indepHoles.splice(h,1);
  18013. tmpShape1 = shape.slice( 0, shapeIndex+1 );
  18014. tmpShape2 = shape.slice( shapeIndex );
  18015. tmpHole1 = hole.slice( holeIndex );
  18016. tmpHole2 = hole.slice( 0, holeIndex+1 );
  18017. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  18018. // Debug only, to show the selected cuts
  18019. // glob_CutLines.push( [ shapePt, holePt ] );
  18020. break;
  18021. }
  18022. if ( holeIndex >= 0 ) break; // hole-vertex found
  18023. failedCuts[cutKey] = true; // remember failure
  18024. }
  18025. if ( holeIndex >= 0 ) break; // hole-vertex found
  18026. }
  18027. }
  18028. return shape; /* shape with no holes */
  18029. }
  18030. var i, il, f, face,
  18031. key, index,
  18032. allPointsMap = {};
  18033. // 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.
  18034. var allpoints = contour.concat();
  18035. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  18036. Array.prototype.push.apply( allpoints, holes[h] );
  18037. }
  18038. //console.log( "allpoints",allpoints, allpoints.length );
  18039. // prepare all points map
  18040. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  18041. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  18042. if ( allPointsMap[ key ] !== undefined ) {
  18043. console.log( "Duplicate point", key );
  18044. }
  18045. allPointsMap[ key ] = i;
  18046. }
  18047. // remove holes by cutting paths to holes and adding them to the shape
  18048. var shapeWithoutHoles = removeHoles( contour, holes );
  18049. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  18050. //console.log( "triangles",triangles, triangles.length );
  18051. // check all face vertices against all points map
  18052. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  18053. face = triangles[ i ];
  18054. for ( f = 0; f < 3; f ++ ) {
  18055. key = face[ f ].x + ":" + face[ f ].y;
  18056. index = allPointsMap[ key ];
  18057. if ( index !== undefined ) {
  18058. face[ f ] = index;
  18059. }
  18060. }
  18061. }
  18062. return triangles.concat();
  18063. },
  18064. isClockWise: function ( pts ) {
  18065. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  18066. },
  18067. // Bezier Curves formulas obtained from
  18068. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18069. // Quad Bezier Functions
  18070. b2p0: function ( t, p ) {
  18071. var k = 1 - t;
  18072. return k * k * p;
  18073. },
  18074. b2p1: function ( t, p ) {
  18075. return 2 * ( 1 - t ) * t * p;
  18076. },
  18077. b2p2: function ( t, p ) {
  18078. return t * t * p;
  18079. },
  18080. b2: function ( t, p0, p1, p2 ) {
  18081. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  18082. },
  18083. // Cubic Bezier Functions
  18084. b3p0: function ( t, p ) {
  18085. var k = 1 - t;
  18086. return k * k * k * p;
  18087. },
  18088. b3p1: function ( t, p ) {
  18089. var k = 1 - t;
  18090. return 3 * k * k * t * p;
  18091. },
  18092. b3p2: function ( t, p ) {
  18093. var k = 1 - t;
  18094. return 3 * k * t * t * p;
  18095. },
  18096. b3p3: function ( t, p ) {
  18097. return t * t * t * p;
  18098. },
  18099. b3: function ( t, p0, p1, p2, p3 ) {
  18100. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  18101. }
  18102. };
  18103. /**************************************************************
  18104. * Line
  18105. **************************************************************/
  18106. THREE.LineCurve = function ( v1, v2 ) {
  18107. this.v1 = v1;
  18108. this.v2 = v2;
  18109. };
  18110. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  18111. THREE.LineCurve.prototype.getPoint = function ( t ) {
  18112. var point = this.v2.clone().sub(this.v1);
  18113. point.multiplyScalar( t ).add( this.v1 );
  18114. return point;
  18115. };
  18116. // Line curve is linear, so we can overwrite default getPointAt
  18117. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  18118. return this.getPoint( u );
  18119. };
  18120. THREE.LineCurve.prototype.getTangent = function( t ) {
  18121. var tangent = this.v2.clone().sub(this.v1);
  18122. return tangent.normalize();
  18123. };
  18124. /**************************************************************
  18125. * Quadratic Bezier curve
  18126. **************************************************************/
  18127. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  18128. this.v0 = v0;
  18129. this.v1 = v1;
  18130. this.v2 = v2;
  18131. };
  18132. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18133. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  18134. var tx, ty;
  18135. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18136. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18137. return new THREE.Vector2( tx, ty );
  18138. };
  18139. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  18140. var tx, ty;
  18141. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  18142. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  18143. // returns unit vector
  18144. var tangent = new THREE.Vector2( tx, ty );
  18145. tangent.normalize();
  18146. return tangent;
  18147. };
  18148. /**************************************************************
  18149. * Cubic Bezier curve
  18150. **************************************************************/
  18151. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  18152. this.v0 = v0;
  18153. this.v1 = v1;
  18154. this.v2 = v2;
  18155. this.v3 = v3;
  18156. };
  18157. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18158. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  18159. var tx, ty;
  18160. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18161. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18162. return new THREE.Vector2( tx, ty );
  18163. };
  18164. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  18165. var tx, ty;
  18166. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18167. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18168. var tangent = new THREE.Vector2( tx, ty );
  18169. tangent.normalize();
  18170. return tangent;
  18171. };
  18172. /**************************************************************
  18173. * Spline curve
  18174. **************************************************************/
  18175. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  18176. this.points = (points == undefined) ? [] : points;
  18177. };
  18178. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  18179. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  18180. var v = new THREE.Vector2();
  18181. var c = [];
  18182. var points = this.points, point, intPoint, weight;
  18183. point = ( points.length - 1 ) * t;
  18184. intPoint = Math.floor( point );
  18185. weight = point - intPoint;
  18186. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18187. c[ 1 ] = intPoint;
  18188. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  18189. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  18190. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18191. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18192. return v;
  18193. };
  18194. /**************************************************************
  18195. * Ellipse curve
  18196. **************************************************************/
  18197. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  18198. this.aX = aX;
  18199. this.aY = aY;
  18200. this.xRadius = xRadius;
  18201. this.yRadius = yRadius;
  18202. this.aStartAngle = aStartAngle;
  18203. this.aEndAngle = aEndAngle;
  18204. this.aClockwise = aClockwise;
  18205. };
  18206. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  18207. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  18208. var angle;
  18209. var deltaAngle = this.aEndAngle - this.aStartAngle;
  18210. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  18211. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  18212. if ( this.aClockwise === true ) {
  18213. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  18214. } else {
  18215. angle = this.aStartAngle + t * deltaAngle;
  18216. }
  18217. var tx = this.aX + this.xRadius * Math.cos( angle );
  18218. var ty = this.aY + this.yRadius * Math.sin( angle );
  18219. return new THREE.Vector2( tx, ty );
  18220. };
  18221. /**************************************************************
  18222. * Arc curve
  18223. **************************************************************/
  18224. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18225. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18226. };
  18227. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  18228. /**************************************************************
  18229. * Line3D
  18230. **************************************************************/
  18231. THREE.LineCurve3 = THREE.Curve.create(
  18232. function ( v1, v2 ) {
  18233. this.v1 = v1;
  18234. this.v2 = v2;
  18235. },
  18236. function ( t ) {
  18237. var r = new THREE.Vector3();
  18238. r.subVectors( this.v2, this.v1 ); // diff
  18239. r.multiplyScalar( t );
  18240. r.add( this.v1 );
  18241. return r;
  18242. }
  18243. );
  18244. /**************************************************************
  18245. * Quadratic Bezier 3D curve
  18246. **************************************************************/
  18247. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  18248. function ( v0, v1, v2 ) {
  18249. this.v0 = v0;
  18250. this.v1 = v1;
  18251. this.v2 = v2;
  18252. },
  18253. function ( t ) {
  18254. var tx, ty, tz;
  18255. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18256. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18257. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  18258. return new THREE.Vector3( tx, ty, tz );
  18259. }
  18260. );
  18261. /**************************************************************
  18262. * Cubic Bezier 3D curve
  18263. **************************************************************/
  18264. THREE.CubicBezierCurve3 = THREE.Curve.create(
  18265. function ( v0, v1, v2, v3 ) {
  18266. this.v0 = v0;
  18267. this.v1 = v1;
  18268. this.v2 = v2;
  18269. this.v3 = v3;
  18270. },
  18271. function ( t ) {
  18272. var tx, ty, tz;
  18273. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18274. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18275. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  18276. return new THREE.Vector3( tx, ty, tz );
  18277. }
  18278. );
  18279. /**************************************************************
  18280. * Spline 3D curve
  18281. **************************************************************/
  18282. THREE.SplineCurve3 = THREE.Curve.create(
  18283. function ( points /* array of Vector3 */) {
  18284. this.points = (points == undefined) ? [] : points;
  18285. },
  18286. function ( t ) {
  18287. var v = new THREE.Vector3();
  18288. var c = [];
  18289. var points = this.points, point, intPoint, weight;
  18290. point = ( points.length - 1 ) * t;
  18291. intPoint = Math.floor( point );
  18292. weight = point - intPoint;
  18293. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18294. c[ 1 ] = intPoint;
  18295. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18296. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18297. var pt0 = points[ c[0] ],
  18298. pt1 = points[ c[1] ],
  18299. pt2 = points[ c[2] ],
  18300. pt3 = points[ c[3] ];
  18301. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  18302. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  18303. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  18304. return v;
  18305. }
  18306. );
  18307. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  18308. // var v = new THREE.Vector3();
  18309. // var c = [];
  18310. // var points = this.points, point, intPoint, weight;
  18311. // point = ( points.length - 1 ) * t;
  18312. // intPoint = Math.floor( point );
  18313. // weight = point - intPoint;
  18314. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18315. // c[ 1 ] = intPoint;
  18316. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18317. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18318. // var pt0 = points[ c[0] ],
  18319. // pt1 = points[ c[1] ],
  18320. // pt2 = points[ c[2] ],
  18321. // pt3 = points[ c[3] ];
  18322. // // t = weight;
  18323. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  18324. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  18325. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  18326. // return v;
  18327. // }
  18328. /**************************************************************
  18329. * Closed Spline 3D curve
  18330. **************************************************************/
  18331. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  18332. function ( points /* array of Vector3 */) {
  18333. this.points = (points == undefined) ? [] : points;
  18334. },
  18335. function ( t ) {
  18336. var v = new THREE.Vector3();
  18337. var c = [];
  18338. var points = this.points, point, intPoint, weight;
  18339. point = ( points.length - 0 ) * t;
  18340. // This needs to be from 0-length +1
  18341. intPoint = Math.floor( point );
  18342. weight = point - intPoint;
  18343. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  18344. c[ 0 ] = ( intPoint - 1 ) % points.length;
  18345. c[ 1 ] = ( intPoint ) % points.length;
  18346. c[ 2 ] = ( intPoint + 1 ) % points.length;
  18347. c[ 3 ] = ( intPoint + 2 ) % points.length;
  18348. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18349. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18350. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  18351. return v;
  18352. }
  18353. );
  18354. /**
  18355. * @author mikael emtinger / http://gomo.se/
  18356. */
  18357. THREE.AnimationHandler = (function() {
  18358. var playing = [];
  18359. var library = {};
  18360. var that = {};
  18361. //--- update ---
  18362. that.update = function( deltaTimeMS ) {
  18363. for( var i = 0; i < playing.length; i ++ )
  18364. playing[ i ].update( deltaTimeMS );
  18365. };
  18366. //--- add ---
  18367. that.addToUpdate = function( animation ) {
  18368. if ( playing.indexOf( animation ) === -1 )
  18369. playing.push( animation );
  18370. };
  18371. //--- remove ---
  18372. that.removeFromUpdate = function( animation ) {
  18373. var index = playing.indexOf( animation );
  18374. if( index !== -1 )
  18375. playing.splice( index, 1 );
  18376. };
  18377. //--- add ---
  18378. that.add = function( data ) {
  18379. if ( library[ data.name ] !== undefined )
  18380. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18381. library[ data.name ] = data;
  18382. initData( data );
  18383. };
  18384. //--- get ---
  18385. that.get = function( name ) {
  18386. if ( typeof name === "string" ) {
  18387. if ( library[ name ] ) {
  18388. return library[ name ];
  18389. } else {
  18390. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  18391. return null;
  18392. }
  18393. } else {
  18394. // todo: add simple tween library
  18395. }
  18396. };
  18397. //--- parse ---
  18398. that.parse = function( root ) {
  18399. // setup hierarchy
  18400. var hierarchy = [];
  18401. if ( root instanceof THREE.SkinnedMesh ) {
  18402. for( var b = 0; b < root.bones.length; b++ ) {
  18403. hierarchy.push( root.bones[ b ] );
  18404. }
  18405. } else {
  18406. parseRecurseHierarchy( root, hierarchy );
  18407. }
  18408. return hierarchy;
  18409. };
  18410. var parseRecurseHierarchy = function( root, hierarchy ) {
  18411. hierarchy.push( root );
  18412. for( var c = 0; c < root.children.length; c++ )
  18413. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18414. }
  18415. //--- init data ---
  18416. var initData = function( data ) {
  18417. if( data.initialized === true )
  18418. return;
  18419. // loop through all keys
  18420. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  18421. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18422. // remove minus times
  18423. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  18424. data.hierarchy[ h ].keys[ k ].time = 0;
  18425. // create quaternions
  18426. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18427. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18428. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18429. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  18430. }
  18431. }
  18432. // prepare morph target keys
  18433. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18434. // get all used
  18435. var usedMorphTargets = {};
  18436. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18437. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18438. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18439. usedMorphTargets[ morphTargetName ] = -1;
  18440. }
  18441. }
  18442. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18443. // set all used on all frames
  18444. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18445. var influences = {};
  18446. for ( var morphTargetName in usedMorphTargets ) {
  18447. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18448. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18449. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18450. break;
  18451. }
  18452. }
  18453. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18454. influences[ morphTargetName ] = 0;
  18455. }
  18456. }
  18457. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18458. }
  18459. }
  18460. // remove all keys that are on the same time
  18461. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18462. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18463. data.hierarchy[ h ].keys.splice( k, 1 );
  18464. k --;
  18465. }
  18466. }
  18467. // set index
  18468. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18469. data.hierarchy[ h ].keys[ k ].index = k;
  18470. }
  18471. }
  18472. // done
  18473. data.initialized = true;
  18474. };
  18475. // interpolation types
  18476. that.LINEAR = 0;
  18477. that.CATMULLROM = 1;
  18478. that.CATMULLROM_FORWARD = 2;
  18479. return that;
  18480. }());
  18481. /**
  18482. * @author mikael emtinger / http://gomo.se/
  18483. * @author mrdoob / http://mrdoob.com/
  18484. * @author alteredq / http://alteredqualia.com/
  18485. */
  18486. THREE.Animation = function ( root, name ) {
  18487. this.root = root;
  18488. this.data = THREE.AnimationHandler.get( name );
  18489. this.hierarchy = THREE.AnimationHandler.parse( root );
  18490. this.currentTime = 0;
  18491. this.timeScale = 1;
  18492. this.isPlaying = false;
  18493. this.isPaused = true;
  18494. this.loop = true;
  18495. this.interpolationType = THREE.AnimationHandler.LINEAR;
  18496. };
  18497. THREE.Animation.prototype.play = function ( startTime ) {
  18498. this.currentTime = startTime !== undefined ? startTime : 0;
  18499. if ( this.isPlaying === false ) {
  18500. this.isPlaying = true;
  18501. this.reset();
  18502. this.update( 0 );
  18503. }
  18504. this.isPaused = false;
  18505. THREE.AnimationHandler.addToUpdate( this );
  18506. };
  18507. THREE.Animation.prototype.pause = function() {
  18508. if ( this.isPaused === true ) {
  18509. THREE.AnimationHandler.addToUpdate( this );
  18510. } else {
  18511. THREE.AnimationHandler.removeFromUpdate( this );
  18512. }
  18513. this.isPaused = !this.isPaused;
  18514. };
  18515. THREE.Animation.prototype.stop = function() {
  18516. this.isPlaying = false;
  18517. this.isPaused = false;
  18518. THREE.AnimationHandler.removeFromUpdate( this );
  18519. };
  18520. THREE.Animation.prototype.reset = function () {
  18521. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18522. var object = this.hierarchy[ h ];
  18523. object.matrixAutoUpdate = true;
  18524. if ( object.animationCache === undefined ) {
  18525. object.animationCache = {};
  18526. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  18527. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  18528. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18529. }
  18530. var prevKey = object.animationCache.prevKey;
  18531. var nextKey = object.animationCache.nextKey;
  18532. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  18533. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  18534. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  18535. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  18536. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  18537. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  18538. }
  18539. };
  18540. THREE.Animation.prototype.update = (function(){
  18541. var points = [];
  18542. var target = new THREE.Vector3();
  18543. // Catmull-Rom spline
  18544. var interpolateCatmullRom = function ( points, scale ) {
  18545. var c = [], v3 = [],
  18546. point, intPoint, weight, w2, w3,
  18547. pa, pb, pc, pd;
  18548. point = ( points.length - 1 ) * scale;
  18549. intPoint = Math.floor( point );
  18550. weight = point - intPoint;
  18551. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18552. c[ 1 ] = intPoint;
  18553. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18554. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18555. pa = points[ c[ 0 ] ];
  18556. pb = points[ c[ 1 ] ];
  18557. pc = points[ c[ 2 ] ];
  18558. pd = points[ c[ 3 ] ];
  18559. w2 = weight * weight;
  18560. w3 = weight * w2;
  18561. v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18562. v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18563. v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18564. return v3;
  18565. };
  18566. var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18567. var v0 = ( p2 - p0 ) * 0.5,
  18568. v1 = ( p3 - p1 ) * 0.5;
  18569. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18570. };
  18571. return function ( delta ) {
  18572. if ( this.isPlaying === false ) return;
  18573. this.currentTime += delta * this.timeScale;
  18574. //
  18575. var vector;
  18576. var types = [ "pos", "rot", "scl" ];
  18577. var duration = this.data.length;
  18578. if ( this.loop === true && this.currentTime > duration ) {
  18579. this.currentTime %= duration;
  18580. this.reset();
  18581. } else if ( this.loop === false && this.currentTime > duration ) {
  18582. this.stop();
  18583. return;
  18584. }
  18585. this.currentTime = Math.min( this.currentTime, duration );
  18586. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18587. var object = this.hierarchy[ h ];
  18588. var animationCache = object.animationCache;
  18589. // loop through pos/rot/scl
  18590. for ( var t = 0; t < 3; t ++ ) {
  18591. // get keys
  18592. var type = types[ t ];
  18593. var prevKey = animationCache.prevKey[ type ];
  18594. var nextKey = animationCache.nextKey[ type ];
  18595. if ( nextKey.time <= this.currentTime ) {
  18596. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18597. nextKey = this.getNextKeyWith( type, h, 1 );
  18598. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18599. prevKey = nextKey;
  18600. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18601. }
  18602. animationCache.prevKey[ type ] = prevKey;
  18603. animationCache.nextKey[ type ] = nextKey;
  18604. }
  18605. object.matrixAutoUpdate = true;
  18606. object.matrixWorldNeedsUpdate = true;
  18607. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18608. var prevXYZ = prevKey[ type ];
  18609. var nextXYZ = nextKey[ type ];
  18610. if ( scale < 0 ) scale = 0;
  18611. if ( scale > 1 ) scale = 1;
  18612. // interpolate
  18613. if ( type === "pos" ) {
  18614. vector = object.position;
  18615. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18616. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18617. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18618. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18619. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18620. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18621. points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18622. points[ 1 ] = prevXYZ;
  18623. points[ 2 ] = nextXYZ;
  18624. points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18625. scale = scale * 0.33 + 0.33;
  18626. var currentPoint = interpolateCatmullRom( points, scale );
  18627. vector.x = currentPoint[ 0 ];
  18628. vector.y = currentPoint[ 1 ];
  18629. vector.z = currentPoint[ 2 ];
  18630. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18631. var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
  18632. target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18633. target.sub( vector );
  18634. target.y = 0;
  18635. target.normalize();
  18636. var angle = Math.atan2( target.x, target.z );
  18637. object.rotation.set( 0, angle, 0 );
  18638. }
  18639. }
  18640. } else if ( type === "rot" ) {
  18641. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18642. } else if ( type === "scl" ) {
  18643. vector = object.scale;
  18644. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18645. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18646. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18647. }
  18648. }
  18649. }
  18650. };
  18651. })();
  18652. // Get next key with
  18653. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18654. var keys = this.data.hierarchy[ h ].keys;
  18655. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18656. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18657. key = key < keys.length - 1 ? key : keys.length - 1;
  18658. } else {
  18659. key = key % keys.length;
  18660. }
  18661. for ( ; key < keys.length; key++ ) {
  18662. if ( keys[ key ][ type ] !== undefined ) {
  18663. return keys[ key ];
  18664. }
  18665. }
  18666. return this.data.hierarchy[ h ].keys[ 0 ];
  18667. };
  18668. // Get previous key with
  18669. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18670. var keys = this.data.hierarchy[ h ].keys;
  18671. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18672. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18673. key = key > 0 ? key : 0;
  18674. } else {
  18675. key = key >= 0 ? key : key + keys.length;
  18676. }
  18677. for ( ; key >= 0; key -- ) {
  18678. if ( keys[ key ][ type ] !== undefined ) {
  18679. return keys[ key ];
  18680. }
  18681. }
  18682. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18683. };
  18684. /**
  18685. * @author mikael emtinger / http://gomo.se/
  18686. * @author mrdoob / http://mrdoob.com/
  18687. * @author alteredq / http://alteredqualia.com/
  18688. * @author khang duong
  18689. * @author erik kitson
  18690. */
  18691. THREE.KeyFrameAnimation = function ( root, data ) {
  18692. this.root = root;
  18693. this.data = THREE.AnimationHandler.get( data );
  18694. this.hierarchy = THREE.AnimationHandler.parse( root );
  18695. this.currentTime = 0;
  18696. this.timeScale = 0.001;
  18697. this.isPlaying = false;
  18698. this.isPaused = true;
  18699. this.loop = true;
  18700. // initialize to first keyframes
  18701. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18702. var keys = this.data.hierarchy[h].keys,
  18703. sids = this.data.hierarchy[h].sids,
  18704. obj = this.hierarchy[h];
  18705. if ( keys.length && sids ) {
  18706. for ( var s = 0; s < sids.length; s++ ) {
  18707. var sid = sids[ s ],
  18708. next = this.getNextKeyWith( sid, h, 0 );
  18709. if ( next ) {
  18710. next.apply( sid );
  18711. }
  18712. }
  18713. obj.matrixAutoUpdate = false;
  18714. this.data.hierarchy[h].node.updateMatrix();
  18715. obj.matrixWorldNeedsUpdate = true;
  18716. }
  18717. }
  18718. };
  18719. // Play
  18720. THREE.KeyFrameAnimation.prototype.play = function ( startTime ) {
  18721. this.currentTime = startTime !== undefined ? startTime : 0;
  18722. if ( this.isPlaying === false ) {
  18723. this.isPlaying = true;
  18724. // reset key cache
  18725. var h, hl = this.hierarchy.length,
  18726. object,
  18727. node;
  18728. for ( h = 0; h < hl; h++ ) {
  18729. object = this.hierarchy[ h ];
  18730. node = this.data.hierarchy[ h ];
  18731. if ( node.animationCache === undefined ) {
  18732. node.animationCache = {};
  18733. node.animationCache.prevKey = null;
  18734. node.animationCache.nextKey = null;
  18735. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18736. }
  18737. var keys = this.data.hierarchy[h].keys;
  18738. if (keys.length) {
  18739. node.animationCache.prevKey = keys[ 0 ];
  18740. node.animationCache.nextKey = keys[ 1 ];
  18741. this.startTime = Math.min( keys[0].time, this.startTime );
  18742. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18743. }
  18744. }
  18745. this.update( 0 );
  18746. }
  18747. this.isPaused = false;
  18748. THREE.AnimationHandler.addToUpdate( this );
  18749. };
  18750. // Pause
  18751. THREE.KeyFrameAnimation.prototype.pause = function() {
  18752. if( this.isPaused ) {
  18753. THREE.AnimationHandler.addToUpdate( this );
  18754. } else {
  18755. THREE.AnimationHandler.removeFromUpdate( this );
  18756. }
  18757. this.isPaused = !this.isPaused;
  18758. };
  18759. // Stop
  18760. THREE.KeyFrameAnimation.prototype.stop = function() {
  18761. this.isPlaying = false;
  18762. this.isPaused = false;
  18763. THREE.AnimationHandler.removeFromUpdate( this );
  18764. // reset JIT matrix and remove cache
  18765. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18766. var obj = this.hierarchy[ h ];
  18767. var node = this.data.hierarchy[ h ];
  18768. if ( node.animationCache !== undefined ) {
  18769. var original = node.animationCache.originalMatrix;
  18770. if( obj instanceof THREE.Bone ) {
  18771. original.copy( obj.skinMatrix );
  18772. obj.skinMatrix = original;
  18773. } else {
  18774. original.copy( obj.matrix );
  18775. obj.matrix = original;
  18776. }
  18777. delete node.animationCache;
  18778. }
  18779. }
  18780. };
  18781. // Update
  18782. THREE.KeyFrameAnimation.prototype.update = function ( delta ) {
  18783. if ( this.isPlaying === false ) return;
  18784. this.currentTime += delta * this.timeScale;
  18785. //
  18786. var duration = this.data.length;
  18787. if ( this.loop === true && this.currentTime > duration ) {
  18788. this.currentTime %= duration;
  18789. }
  18790. this.currentTime = Math.min( this.currentTime, duration );
  18791. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18792. var object = this.hierarchy[ h ];
  18793. var node = this.data.hierarchy[ h ];
  18794. var keys = node.keys,
  18795. animationCache = node.animationCache;
  18796. if ( keys.length ) {
  18797. var prevKey = animationCache.prevKey;
  18798. var nextKey = animationCache.nextKey;
  18799. if ( nextKey.time <= this.currentTime ) {
  18800. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18801. prevKey = nextKey;
  18802. nextKey = keys[ prevKey.index + 1 ];
  18803. }
  18804. animationCache.prevKey = prevKey;
  18805. animationCache.nextKey = nextKey;
  18806. }
  18807. if ( nextKey.time >= this.currentTime ) {
  18808. prevKey.interpolate( nextKey, this.currentTime );
  18809. } else {
  18810. prevKey.interpolate( nextKey, nextKey.time );
  18811. }
  18812. this.data.hierarchy[ h ].node.updateMatrix();
  18813. object.matrixWorldNeedsUpdate = true;
  18814. }
  18815. }
  18816. };
  18817. // Get next key with
  18818. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18819. var keys = this.data.hierarchy[ h ].keys;
  18820. key = key % keys.length;
  18821. for ( ; key < keys.length; key++ ) {
  18822. if ( keys[ key ].hasTarget( sid ) ) {
  18823. return keys[ key ];
  18824. }
  18825. }
  18826. return keys[ 0 ];
  18827. };
  18828. // Get previous key with
  18829. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18830. var keys = this.data.hierarchy[ h ].keys;
  18831. key = key >= 0 ? key : key + keys.length;
  18832. for ( ; key >= 0; key-- ) {
  18833. if ( keys[ key ].hasTarget( sid ) ) {
  18834. return keys[ key ];
  18835. }
  18836. }
  18837. return keys[ keys.length - 1 ];
  18838. };
  18839. /**
  18840. * @author mrdoob / http://mrdoob.com
  18841. */
  18842. THREE.MorphAnimation = function ( mesh ) {
  18843. this.mesh = mesh;
  18844. this.frames = mesh.morphTargetInfluences.length;
  18845. this.currentTime = 0;
  18846. this.duration = 1000;
  18847. this.loop = true;
  18848. this.isPlaying = false;
  18849. };
  18850. THREE.MorphAnimation.prototype = {
  18851. play: function () {
  18852. this.isPlaying = true;
  18853. },
  18854. pause: function () {
  18855. this.isPlaying = false;
  18856. },
  18857. update: ( function () {
  18858. var lastFrame = 0;
  18859. var currentFrame = 0;
  18860. return function ( delta ) {
  18861. if ( this.isPlaying === false ) return;
  18862. this.currentTime += delta;
  18863. if ( this.loop === true && this.currentTime > this.duration ) {
  18864. this.currentTime %= this.duration;
  18865. }
  18866. this.currentTime = Math.min( this.currentTime, this.duration );
  18867. var interpolation = this.duration / this.frames;
  18868. var frame = Math.floor( this.currentTime / interpolation );
  18869. if ( frame != currentFrame ) {
  18870. this.mesh.morphTargetInfluences[ lastFrame ] = 0;
  18871. this.mesh.morphTargetInfluences[ currentFrame ] = 1;
  18872. this.mesh.morphTargetInfluences[ frame ] = 0;
  18873. lastFrame = currentFrame;
  18874. currentFrame = frame;
  18875. }
  18876. this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  18877. this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ];
  18878. }
  18879. } )()
  18880. };
  18881. /**
  18882. * Camera for rendering cube maps
  18883. * - renders scene into axis-aligned cube
  18884. *
  18885. * @author alteredq / http://alteredqualia.com/
  18886. */
  18887. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18888. THREE.Object3D.call( this );
  18889. var fov = 90, aspect = 1;
  18890. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18891. cameraPX.up.set( 0, -1, 0 );
  18892. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18893. this.add( cameraPX );
  18894. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18895. cameraNX.up.set( 0, -1, 0 );
  18896. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18897. this.add( cameraNX );
  18898. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18899. cameraPY.up.set( 0, 0, 1 );
  18900. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18901. this.add( cameraPY );
  18902. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18903. cameraNY.up.set( 0, 0, -1 );
  18904. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18905. this.add( cameraNY );
  18906. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18907. cameraPZ.up.set( 0, -1, 0 );
  18908. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18909. this.add( cameraPZ );
  18910. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18911. cameraNZ.up.set( 0, -1, 0 );
  18912. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18913. this.add( cameraNZ );
  18914. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18915. this.updateCubeMap = function ( renderer, scene ) {
  18916. var renderTarget = this.renderTarget;
  18917. var generateMipmaps = renderTarget.generateMipmaps;
  18918. renderTarget.generateMipmaps = false;
  18919. renderTarget.activeCubeFace = 0;
  18920. renderer.render( scene, cameraPX, renderTarget );
  18921. renderTarget.activeCubeFace = 1;
  18922. renderer.render( scene, cameraNX, renderTarget );
  18923. renderTarget.activeCubeFace = 2;
  18924. renderer.render( scene, cameraPY, renderTarget );
  18925. renderTarget.activeCubeFace = 3;
  18926. renderer.render( scene, cameraNY, renderTarget );
  18927. renderTarget.activeCubeFace = 4;
  18928. renderer.render( scene, cameraPZ, renderTarget );
  18929. renderTarget.generateMipmaps = generateMipmaps;
  18930. renderTarget.activeCubeFace = 5;
  18931. renderer.render( scene, cameraNZ, renderTarget );
  18932. };
  18933. };
  18934. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18935. /**
  18936. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18937. *
  18938. * A general perpose camera, for setting FOV, Lens Focal Length,
  18939. * and switching between perspective and orthographic views easily.
  18940. * Use this only if you do not wish to manage
  18941. * both a Orthographic and Perspective Camera
  18942. *
  18943. */
  18944. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18945. THREE.Camera.call( this );
  18946. this.fov = fov;
  18947. this.left = -width / 2;
  18948. this.right = width / 2
  18949. this.top = height / 2;
  18950. this.bottom = -height / 2;
  18951. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18952. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18953. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18954. this.zoom = 1;
  18955. this.toPerspective();
  18956. var aspect = width/height;
  18957. };
  18958. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18959. THREE.CombinedCamera.prototype.toPerspective = function () {
  18960. // Switches to the Perspective Camera
  18961. this.near = this.cameraP.near;
  18962. this.far = this.cameraP.far;
  18963. this.cameraP.fov = this.fov / this.zoom ;
  18964. this.cameraP.updateProjectionMatrix();
  18965. this.projectionMatrix = this.cameraP.projectionMatrix;
  18966. this.inPerspectiveMode = true;
  18967. this.inOrthographicMode = false;
  18968. };
  18969. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18970. // Switches to the Orthographic camera estimating viewport from Perspective
  18971. var fov = this.fov;
  18972. var aspect = this.cameraP.aspect;
  18973. var near = this.cameraP.near;
  18974. var far = this.cameraP.far;
  18975. // The size that we set is the mid plane of the viewing frustum
  18976. var hyperfocus = ( near + far ) / 2;
  18977. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18978. var planeHeight = 2 * halfHeight;
  18979. var planeWidth = planeHeight * aspect;
  18980. var halfWidth = planeWidth / 2;
  18981. halfHeight /= this.zoom;
  18982. halfWidth /= this.zoom;
  18983. this.cameraO.left = -halfWidth;
  18984. this.cameraO.right = halfWidth;
  18985. this.cameraO.top = halfHeight;
  18986. this.cameraO.bottom = -halfHeight;
  18987. // this.cameraO.left = -farHalfWidth;
  18988. // this.cameraO.right = farHalfWidth;
  18989. // this.cameraO.top = farHalfHeight;
  18990. // this.cameraO.bottom = -farHalfHeight;
  18991. // this.cameraO.left = this.left / this.zoom;
  18992. // this.cameraO.right = this.right / this.zoom;
  18993. // this.cameraO.top = this.top / this.zoom;
  18994. // this.cameraO.bottom = this.bottom / this.zoom;
  18995. this.cameraO.updateProjectionMatrix();
  18996. this.near = this.cameraO.near;
  18997. this.far = this.cameraO.far;
  18998. this.projectionMatrix = this.cameraO.projectionMatrix;
  18999. this.inPerspectiveMode = false;
  19000. this.inOrthographicMode = true;
  19001. };
  19002. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  19003. this.cameraP.aspect = width / height;
  19004. this.left = -width / 2;
  19005. this.right = width / 2
  19006. this.top = height / 2;
  19007. this.bottom = -height / 2;
  19008. };
  19009. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  19010. this.fov = fov;
  19011. if ( this.inPerspectiveMode ) {
  19012. this.toPerspective();
  19013. } else {
  19014. this.toOrthographic();
  19015. }
  19016. };
  19017. // For mantaining similar API with PerspectiveCamera
  19018. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  19019. if ( this.inPerspectiveMode ) {
  19020. this.toPerspective();
  19021. } else {
  19022. this.toPerspective();
  19023. this.toOrthographic();
  19024. }
  19025. };
  19026. /*
  19027. * Uses Focal Length (in mm) to estimate and set FOV
  19028. * 35mm (fullframe) camera is used if frame size is not specified;
  19029. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  19030. */
  19031. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  19032. if ( frameHeight === undefined ) frameHeight = 24;
  19033. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  19034. this.setFov( fov );
  19035. return fov;
  19036. };
  19037. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  19038. this.zoom = zoom;
  19039. if ( this.inPerspectiveMode ) {
  19040. this.toPerspective();
  19041. } else {
  19042. this.toOrthographic();
  19043. }
  19044. };
  19045. THREE.CombinedCamera.prototype.toFrontView = function() {
  19046. this.rotation.x = 0;
  19047. this.rotation.y = 0;
  19048. this.rotation.z = 0;
  19049. // should we be modifing the matrix instead?
  19050. this.rotationAutoUpdate = false;
  19051. };
  19052. THREE.CombinedCamera.prototype.toBackView = function() {
  19053. this.rotation.x = 0;
  19054. this.rotation.y = Math.PI;
  19055. this.rotation.z = 0;
  19056. this.rotationAutoUpdate = false;
  19057. };
  19058. THREE.CombinedCamera.prototype.toLeftView = function() {
  19059. this.rotation.x = 0;
  19060. this.rotation.y = - Math.PI / 2;
  19061. this.rotation.z = 0;
  19062. this.rotationAutoUpdate = false;
  19063. };
  19064. THREE.CombinedCamera.prototype.toRightView = function() {
  19065. this.rotation.x = 0;
  19066. this.rotation.y = Math.PI / 2;
  19067. this.rotation.z = 0;
  19068. this.rotationAutoUpdate = false;
  19069. };
  19070. THREE.CombinedCamera.prototype.toTopView = function() {
  19071. this.rotation.x = - Math.PI / 2;
  19072. this.rotation.y = 0;
  19073. this.rotation.z = 0;
  19074. this.rotationAutoUpdate = false;
  19075. };
  19076. THREE.CombinedCamera.prototype.toBottomView = function() {
  19077. this.rotation.x = Math.PI / 2;
  19078. this.rotation.y = 0;
  19079. this.rotation.z = 0;
  19080. this.rotationAutoUpdate = false;
  19081. };
  19082. /**
  19083. * @author mrdoob / http://mrdoob.com/
  19084. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  19085. */
  19086. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19087. THREE.Geometry.call( this );
  19088. var scope = this;
  19089. this.width = width;
  19090. this.height = height;
  19091. this.depth = depth;
  19092. this.widthSegments = widthSegments || 1;
  19093. this.heightSegments = heightSegments || 1;
  19094. this.depthSegments = depthSegments || 1;
  19095. var width_half = this.width / 2;
  19096. var height_half = this.height / 2;
  19097. var depth_half = this.depth / 2;
  19098. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  19099. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  19100. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  19101. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  19102. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  19103. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  19104. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  19105. var w, ix, iy,
  19106. gridX = scope.widthSegments,
  19107. gridY = scope.heightSegments,
  19108. width_half = width / 2,
  19109. height_half = height / 2,
  19110. offset = scope.vertices.length;
  19111. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  19112. w = 'z';
  19113. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  19114. w = 'y';
  19115. gridY = scope.depthSegments;
  19116. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  19117. w = 'x';
  19118. gridX = scope.depthSegments;
  19119. }
  19120. var gridX1 = gridX + 1,
  19121. gridY1 = gridY + 1,
  19122. segment_width = width / gridX,
  19123. segment_height = height / gridY,
  19124. normal = new THREE.Vector3();
  19125. normal[ w ] = depth > 0 ? 1 : - 1;
  19126. for ( iy = 0; iy < gridY1; iy ++ ) {
  19127. for ( ix = 0; ix < gridX1; ix ++ ) {
  19128. var vector = new THREE.Vector3();
  19129. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  19130. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  19131. vector[ w ] = depth;
  19132. scope.vertices.push( vector );
  19133. }
  19134. }
  19135. for ( iy = 0; iy < gridY; iy++ ) {
  19136. for ( ix = 0; ix < gridX; ix++ ) {
  19137. var a = ix + gridX1 * iy;
  19138. var b = ix + gridX1 * ( iy + 1 );
  19139. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19140. var d = ( ix + 1 ) + gridX1 * iy;
  19141. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  19142. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  19143. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  19144. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  19145. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  19146. face.normal.copy( normal );
  19147. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19148. face.materialIndex = materialIndex;
  19149. scope.faces.push( face );
  19150. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19151. face = new THREE.Face3( b + offset, c + offset, d + offset );
  19152. face.normal.copy( normal );
  19153. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19154. face.materialIndex = materialIndex;
  19155. scope.faces.push( face );
  19156. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19157. }
  19158. }
  19159. }
  19160. this.computeCentroids();
  19161. this.mergeVertices();
  19162. };
  19163. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19164. /**
  19165. * @author hughes
  19166. */
  19167. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  19168. THREE.Geometry.call( this );
  19169. this.radius = radius = radius || 50;
  19170. this.segments = segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  19171. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19172. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19173. var i, uvs = [],
  19174. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  19175. this.vertices.push(center);
  19176. uvs.push( centerUV );
  19177. for ( i = 0; i <= segments; i ++ ) {
  19178. var vertex = new THREE.Vector3();
  19179. var segment = thetaStart + i / segments * thetaLength;
  19180. vertex.x = radius * Math.cos( segment );
  19181. vertex.y = radius * Math.sin( segment );
  19182. this.vertices.push( vertex );
  19183. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  19184. }
  19185. var n = new THREE.Vector3( 0, 0, 1 );
  19186. for ( i = 1; i <= segments; i ++ ) {
  19187. var v1 = i;
  19188. var v2 = i + 1 ;
  19189. var v3 = 0;
  19190. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19191. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  19192. }
  19193. this.computeCentroids();
  19194. this.computeFaceNormals();
  19195. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19196. };
  19197. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19198. // DEPRECATED
  19199. THREE.CubeGeometry = THREE.BoxGeometry;
  19200. /**
  19201. * @author mrdoob / http://mrdoob.com/
  19202. */
  19203. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  19204. THREE.Geometry.call( this );
  19205. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  19206. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  19207. this.height = height = height !== undefined ? height : 100;
  19208. this.radialSegments = radialSegments = radialSegments || 8;
  19209. this.heightSegments = heightSegments = heightSegments || 1;
  19210. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  19211. var heightHalf = height / 2;
  19212. var x, y, vertices = [], uvs = [];
  19213. for ( y = 0; y <= heightSegments; y ++ ) {
  19214. var verticesRow = [];
  19215. var uvsRow = [];
  19216. var v = y / heightSegments;
  19217. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19218. for ( x = 0; x <= radialSegments; x ++ ) {
  19219. var u = x / radialSegments;
  19220. var vertex = new THREE.Vector3();
  19221. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  19222. vertex.y = - v * height + heightHalf;
  19223. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  19224. this.vertices.push( vertex );
  19225. verticesRow.push( this.vertices.length - 1 );
  19226. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19227. }
  19228. vertices.push( verticesRow );
  19229. uvs.push( uvsRow );
  19230. }
  19231. var tanTheta = ( radiusBottom - radiusTop ) / height;
  19232. var na, nb;
  19233. for ( x = 0; x < radialSegments; x ++ ) {
  19234. if ( radiusTop !== 0 ) {
  19235. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  19236. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  19237. } else {
  19238. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  19239. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  19240. }
  19241. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19242. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19243. for ( y = 0; y < heightSegments; y ++ ) {
  19244. var v1 = vertices[ y ][ x ];
  19245. var v2 = vertices[ y + 1 ][ x ];
  19246. var v3 = vertices[ y + 1 ][ x + 1 ];
  19247. var v4 = vertices[ y ][ x + 1 ];
  19248. var n1 = na.clone();
  19249. var n2 = na.clone();
  19250. var n3 = nb.clone();
  19251. var n4 = nb.clone();
  19252. var uv1 = uvs[ y ][ x ].clone();
  19253. var uv2 = uvs[ y + 1 ][ x ].clone();
  19254. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19255. var uv4 = uvs[ y ][ x + 1 ].clone();
  19256. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19257. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19258. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19259. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19260. }
  19261. }
  19262. // top cap
  19263. if ( openEnded === false && radiusTop > 0 ) {
  19264. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19265. for ( x = 0; x < radialSegments; x ++ ) {
  19266. var v1 = vertices[ 0 ][ x ];
  19267. var v2 = vertices[ 0 ][ x + 1 ];
  19268. var v3 = this.vertices.length - 1;
  19269. var n1 = new THREE.Vector3( 0, 1, 0 );
  19270. var n2 = new THREE.Vector3( 0, 1, 0 );
  19271. var n3 = new THREE.Vector3( 0, 1, 0 );
  19272. var uv1 = uvs[ 0 ][ x ].clone();
  19273. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19274. var uv3 = new THREE.Vector2( uv2.x, 0 );
  19275. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19276. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19277. }
  19278. }
  19279. // bottom cap
  19280. if ( openEnded === false && radiusBottom > 0 ) {
  19281. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19282. for ( x = 0; x < radialSegments; x ++ ) {
  19283. var v1 = vertices[ y ][ x + 1 ];
  19284. var v2 = vertices[ y ][ x ];
  19285. var v3 = this.vertices.length - 1;
  19286. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19287. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19288. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19289. var uv1 = uvs[ y ][ x + 1 ].clone();
  19290. var uv2 = uvs[ y ][ x ].clone();
  19291. var uv3 = new THREE.Vector2( uv2.x, 1 );
  19292. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19293. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19294. }
  19295. }
  19296. this.computeCentroids();
  19297. this.computeFaceNormals();
  19298. }
  19299. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19300. /**
  19301. * @author zz85 / http://www.lab4games.net/zz85/blog
  19302. *
  19303. * Creates extruded geometry from a path shape.
  19304. *
  19305. * parameters = {
  19306. *
  19307. * curveSegments: <int>, // number of points on the curves
  19308. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19309. * amount: <int>, // Depth to extrude the shape
  19310. *
  19311. * bevelEnabled: <bool>, // turn on bevel
  19312. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19313. * bevelSize: <float>, // how far from shape outline is bevel
  19314. * bevelSegments: <int>, // number of bevel layers
  19315. *
  19316. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19317. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19318. *
  19319. * material: <int> // material index for front and back faces
  19320. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19321. * uvGenerator: <Object> // object that provides UV generator functions
  19322. *
  19323. * }
  19324. **/
  19325. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19326. if ( typeof( shapes ) === "undefined" ) {
  19327. shapes = [];
  19328. return;
  19329. }
  19330. THREE.Geometry.call( this );
  19331. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19332. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19333. this.addShapeList( shapes, options );
  19334. this.computeCentroids();
  19335. this.computeFaceNormals();
  19336. // can't really use automatic vertex normals
  19337. // as then front and back sides get smoothed too
  19338. // should do separate smoothing just for sides
  19339. //this.computeVertexNormals();
  19340. //console.log( "took", ( Date.now() - startTime ) );
  19341. };
  19342. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19343. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19344. var sl = shapes.length;
  19345. for ( var s = 0; s < sl; s ++ ) {
  19346. var shape = shapes[ s ];
  19347. this.addShape( shape, options );
  19348. }
  19349. };
  19350. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19351. var amount = options.amount !== undefined ? options.amount : 100;
  19352. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19353. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19354. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19355. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19356. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19357. var steps = options.steps !== undefined ? options.steps : 1;
  19358. var extrudePath = options.extrudePath;
  19359. var extrudePts, extrudeByPath = false;
  19360. var material = options.material;
  19361. var extrudeMaterial = options.extrudeMaterial;
  19362. // Use default WorldUVGenerator if no UV generators are specified.
  19363. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19364. var shapebb = this.shapebb;
  19365. //shapebb = shape.getBoundingBox();
  19366. var splineTube, binormal, normal, position2;
  19367. if ( extrudePath ) {
  19368. extrudePts = extrudePath.getSpacedPoints( steps );
  19369. extrudeByPath = true;
  19370. bevelEnabled = false; // bevels not supported for path extrusion
  19371. // SETUP TNB variables
  19372. // Reuse TNB from TubeGeomtry for now.
  19373. // TODO1 - have a .isClosed in spline?
  19374. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19375. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19376. binormal = new THREE.Vector3();
  19377. normal = new THREE.Vector3();
  19378. position2 = new THREE.Vector3();
  19379. }
  19380. // Safeguards if bevels are not enabled
  19381. if ( ! bevelEnabled ) {
  19382. bevelSegments = 0;
  19383. bevelThickness = 0;
  19384. bevelSize = 0;
  19385. }
  19386. // Variables initalization
  19387. var ahole, h, hl; // looping of holes
  19388. var scope = this;
  19389. var bevelPoints = [];
  19390. var shapesOffset = this.vertices.length;
  19391. var shapePoints = shape.extractPoints( curveSegments );
  19392. var vertices = shapePoints.shape;
  19393. var holes = shapePoints.holes;
  19394. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19395. if ( reverse ) {
  19396. vertices = vertices.reverse();
  19397. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19398. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19399. ahole = holes[ h ];
  19400. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19401. holes[ h ] = ahole.reverse();
  19402. }
  19403. }
  19404. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19405. }
  19406. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19407. /* Vertices */
  19408. var contour = vertices; // vertices has all points but contour has only points of circumference
  19409. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19410. ahole = holes[ h ];
  19411. vertices = vertices.concat( ahole );
  19412. }
  19413. function scalePt2 ( pt, vec, size ) {
  19414. if ( !vec ) console.log( "die" );
  19415. return vec.clone().multiplyScalar( size ).add( pt );
  19416. }
  19417. var b, bs, t, z,
  19418. vert, vlen = vertices.length,
  19419. face, flen = faces.length,
  19420. cont, clen = contour.length;
  19421. // Find directions for point movement
  19422. var RAD_TO_DEGREES = 180 / Math.PI;
  19423. function getBevelVec( inPt, inPrev, inNext ) {
  19424. var EPSILON = 0.0000000001;
  19425. var sign = THREE.Math.sign;
  19426. // computes for inPt the corresponding point inPt' on a new contour
  19427. // shiftet by 1 unit (length of normalized vector) to the left
  19428. // if we walk along contour clockwise, this new contour is outside the old one
  19429. //
  19430. // inPt' is the intersection of the two lines parallel to the two
  19431. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19432. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  19433. // good reading for geometry algorithms (here: line-line intersection)
  19434. // http://geomalgorithms.com/a05-_intersect-1.html
  19435. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  19436. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  19437. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19438. // check for colinear edges
  19439. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19440. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  19441. // length of vectors for normalizing
  19442. var v_prev_len = Math.sqrt( v_prev_lensq );
  19443. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19444. // shift adjacent points by unit vectors to the left
  19445. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19446. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19447. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19448. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19449. // scaling factor for v_prev to intersection point
  19450. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19451. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19452. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19453. // vector from inPt to intersection point
  19454. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19455. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19456. // Don't normalize!, otherwise sharp corners become ugly
  19457. // but prevent crazy spikes
  19458. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  19459. if ( v_trans_lensq <= 2 ) {
  19460. return new THREE.Vector2( v_trans_x, v_trans_y );
  19461. } else {
  19462. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19463. }
  19464. } else { // handle special case of colinear edges
  19465. var direction_eq = false; // assumes: opposite
  19466. if ( v_prev_x > EPSILON ) {
  19467. if ( v_next_x > EPSILON ) { direction_eq = true; }
  19468. } else {
  19469. if ( v_prev_x < -EPSILON ) {
  19470. if ( v_next_x < -EPSILON ) { direction_eq = true; }
  19471. } else {
  19472. if ( sign(v_prev_y) == sign(v_next_y) ) { direction_eq = true; }
  19473. }
  19474. }
  19475. if ( direction_eq ) {
  19476. // console.log("Warning: lines are a straight sequence");
  19477. v_trans_x = -v_prev_y;
  19478. v_trans_y = v_prev_x;
  19479. shrink_by = Math.sqrt( v_prev_lensq );
  19480. } else {
  19481. // console.log("Warning: lines are a straight spike");
  19482. v_trans_x = v_prev_x;
  19483. v_trans_y = v_prev_y;
  19484. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19485. }
  19486. }
  19487. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19488. }
  19489. var contourMovements = [];
  19490. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19491. if ( j === il ) j = 0;
  19492. if ( k === il ) k = 0;
  19493. // (j)---(i)---(k)
  19494. // console.log('i,j,k', i, j , k)
  19495. var pt_i = contour[ i ];
  19496. var pt_j = contour[ j ];
  19497. var pt_k = contour[ k ];
  19498. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19499. }
  19500. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19501. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19502. ahole = holes[ h ];
  19503. oneHoleMovements = [];
  19504. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19505. if ( j === il ) j = 0;
  19506. if ( k === il ) k = 0;
  19507. // (j)---(i)---(k)
  19508. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19509. }
  19510. holesMovements.push( oneHoleMovements );
  19511. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19512. }
  19513. // Loop bevelSegments, 1 for the front, 1 for the back
  19514. for ( b = 0; b < bevelSegments; b ++ ) {
  19515. //for ( b = bevelSegments; b > 0; b -- ) {
  19516. t = b / bevelSegments;
  19517. z = bevelThickness * ( 1 - t );
  19518. //z = bevelThickness * t;
  19519. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19520. //bs = bevelSize * t ; // linear
  19521. // contract shape
  19522. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19523. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19524. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19525. v( vert.x, vert.y, - z );
  19526. }
  19527. // expand holes
  19528. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19529. ahole = holes[ h ];
  19530. oneHoleMovements = holesMovements[ h ];
  19531. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19532. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19533. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19534. v( vert.x, vert.y, -z );
  19535. }
  19536. }
  19537. }
  19538. bs = bevelSize;
  19539. // Back facing vertices
  19540. for ( i = 0; i < vlen; i ++ ) {
  19541. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19542. if ( !extrudeByPath ) {
  19543. v( vert.x, vert.y, 0 );
  19544. } else {
  19545. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19546. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19547. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19548. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19549. v( position2.x, position2.y, position2.z );
  19550. }
  19551. }
  19552. // Add stepped vertices...
  19553. // Including front facing vertices
  19554. var s;
  19555. for ( s = 1; s <= steps; s ++ ) {
  19556. for ( i = 0; i < vlen; i ++ ) {
  19557. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19558. if ( !extrudeByPath ) {
  19559. v( vert.x, vert.y, amount / steps * s );
  19560. } else {
  19561. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19562. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19563. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19564. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19565. v( position2.x, position2.y, position2.z );
  19566. }
  19567. }
  19568. }
  19569. // Add bevel segments planes
  19570. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19571. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19572. t = b / bevelSegments;
  19573. z = bevelThickness * ( 1 - t );
  19574. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19575. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19576. // contract shape
  19577. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19578. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19579. v( vert.x, vert.y, amount + z );
  19580. }
  19581. // expand holes
  19582. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19583. ahole = holes[ h ];
  19584. oneHoleMovements = holesMovements[ h ];
  19585. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19586. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19587. if ( !extrudeByPath ) {
  19588. v( vert.x, vert.y, amount + z );
  19589. } else {
  19590. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19591. }
  19592. }
  19593. }
  19594. }
  19595. /* Faces */
  19596. // Top and bottom faces
  19597. buildLidFaces();
  19598. // Sides faces
  19599. buildSideFaces();
  19600. ///// Internal functions
  19601. function buildLidFaces() {
  19602. if ( bevelEnabled ) {
  19603. var layer = 0 ; // steps + 1
  19604. var offset = vlen * layer;
  19605. // Bottom faces
  19606. for ( i = 0; i < flen; i ++ ) {
  19607. face = faces[ i ];
  19608. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19609. }
  19610. layer = steps + bevelSegments * 2;
  19611. offset = vlen * layer;
  19612. // Top faces
  19613. for ( i = 0; i < flen; i ++ ) {
  19614. face = faces[ i ];
  19615. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19616. }
  19617. } else {
  19618. // Bottom faces
  19619. for ( i = 0; i < flen; i++ ) {
  19620. face = faces[ i ];
  19621. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19622. }
  19623. // Top faces
  19624. for ( i = 0; i < flen; i ++ ) {
  19625. face = faces[ i ];
  19626. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19627. }
  19628. }
  19629. }
  19630. // Create faces for the z-sides of the shape
  19631. function buildSideFaces() {
  19632. var layeroffset = 0;
  19633. sidewalls( contour, layeroffset );
  19634. layeroffset += contour.length;
  19635. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19636. ahole = holes[ h ];
  19637. sidewalls( ahole, layeroffset );
  19638. //, true
  19639. layeroffset += ahole.length;
  19640. }
  19641. }
  19642. function sidewalls( contour, layeroffset ) {
  19643. var j, k;
  19644. i = contour.length;
  19645. while ( --i >= 0 ) {
  19646. j = i;
  19647. k = i - 1;
  19648. if ( k < 0 ) k = contour.length - 1;
  19649. //console.log('b', i,j, i-1, k,vertices.length);
  19650. var s = 0, sl = steps + bevelSegments * 2;
  19651. for ( s = 0; s < sl; s ++ ) {
  19652. var slen1 = vlen * s;
  19653. var slen2 = vlen * ( s + 1 );
  19654. var a = layeroffset + j + slen1,
  19655. b = layeroffset + k + slen1,
  19656. c = layeroffset + k + slen2,
  19657. d = layeroffset + j + slen2;
  19658. f4( a, b, c, d, contour, s, sl, j, k );
  19659. }
  19660. }
  19661. }
  19662. function v( x, y, z ) {
  19663. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19664. }
  19665. function f3( a, b, c, isBottom ) {
  19666. a += shapesOffset;
  19667. b += shapesOffset;
  19668. c += shapesOffset;
  19669. // normal, color, material
  19670. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19671. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19672. scope.faceVertexUvs[ 0 ].push( uvs );
  19673. }
  19674. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19675. a += shapesOffset;
  19676. b += shapesOffset;
  19677. c += shapesOffset;
  19678. d += shapesOffset;
  19679. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19680. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19681. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19682. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19683. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19684. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19685. }
  19686. };
  19687. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19688. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19689. var ax = geometry.vertices[ indexA ].x,
  19690. ay = geometry.vertices[ indexA ].y,
  19691. bx = geometry.vertices[ indexB ].x,
  19692. by = geometry.vertices[ indexB ].y,
  19693. cx = geometry.vertices[ indexC ].x,
  19694. cy = geometry.vertices[ indexC ].y;
  19695. return [
  19696. new THREE.Vector2( ax, ay ),
  19697. new THREE.Vector2( bx, by ),
  19698. new THREE.Vector2( cx, cy )
  19699. ];
  19700. },
  19701. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19702. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19703. },
  19704. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19705. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19706. contourIndex1, contourIndex2 ) {
  19707. var ax = geometry.vertices[ indexA ].x,
  19708. ay = geometry.vertices[ indexA ].y,
  19709. az = geometry.vertices[ indexA ].z,
  19710. bx = geometry.vertices[ indexB ].x,
  19711. by = geometry.vertices[ indexB ].y,
  19712. bz = geometry.vertices[ indexB ].z,
  19713. cx = geometry.vertices[ indexC ].x,
  19714. cy = geometry.vertices[ indexC ].y,
  19715. cz = geometry.vertices[ indexC ].z,
  19716. dx = geometry.vertices[ indexD ].x,
  19717. dy = geometry.vertices[ indexD ].y,
  19718. dz = geometry.vertices[ indexD ].z;
  19719. if ( Math.abs( ay - by ) < 0.01 ) {
  19720. return [
  19721. new THREE.Vector2( ax, 1 - az ),
  19722. new THREE.Vector2( bx, 1 - bz ),
  19723. new THREE.Vector2( cx, 1 - cz ),
  19724. new THREE.Vector2( dx, 1 - dz )
  19725. ];
  19726. } else {
  19727. return [
  19728. new THREE.Vector2( ay, 1 - az ),
  19729. new THREE.Vector2( by, 1 - bz ),
  19730. new THREE.Vector2( cy, 1 - cz ),
  19731. new THREE.Vector2( dy, 1 - dz )
  19732. ];
  19733. }
  19734. }
  19735. };
  19736. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19737. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19738. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19739. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19740. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19741. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19742. /**
  19743. * @author jonobr1 / http://jonobr1.com
  19744. *
  19745. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19746. * ExtrudeGeometry.
  19747. *
  19748. * parameters = {
  19749. *
  19750. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19751. *
  19752. * material: <int> // material index for front and back faces
  19753. * uvGenerator: <Object> // object that provides UV generator functions
  19754. *
  19755. * }
  19756. **/
  19757. THREE.ShapeGeometry = function ( shapes, options ) {
  19758. THREE.Geometry.call( this );
  19759. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19760. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19761. this.addShapeList( shapes, options );
  19762. this.computeCentroids();
  19763. this.computeFaceNormals();
  19764. };
  19765. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19766. /**
  19767. * Add an array of shapes to THREE.ShapeGeometry.
  19768. */
  19769. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19770. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19771. this.addShape( shapes[ i ], options );
  19772. }
  19773. return this;
  19774. };
  19775. /**
  19776. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19777. */
  19778. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19779. if ( options === undefined ) options = {};
  19780. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19781. var material = options.material;
  19782. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19783. var shapebb = this.shapebb;
  19784. //
  19785. var i, l, hole, s;
  19786. var shapesOffset = this.vertices.length;
  19787. var shapePoints = shape.extractPoints( curveSegments );
  19788. var vertices = shapePoints.shape;
  19789. var holes = shapePoints.holes;
  19790. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19791. if ( reverse ) {
  19792. vertices = vertices.reverse();
  19793. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19794. for ( i = 0, l = holes.length; i < l; i++ ) {
  19795. hole = holes[ i ];
  19796. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19797. holes[ i ] = hole.reverse();
  19798. }
  19799. }
  19800. reverse = false;
  19801. }
  19802. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19803. // Vertices
  19804. var contour = vertices;
  19805. for ( i = 0, l = holes.length; i < l; i++ ) {
  19806. hole = holes[ i ];
  19807. vertices = vertices.concat( hole );
  19808. }
  19809. //
  19810. var vert, vlen = vertices.length;
  19811. var face, flen = faces.length;
  19812. var cont, clen = contour.length;
  19813. for ( i = 0; i < vlen; i++ ) {
  19814. vert = vertices[ i ];
  19815. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19816. }
  19817. for ( i = 0; i < flen; i++ ) {
  19818. face = faces[ i ];
  19819. var a = face[ 0 ] + shapesOffset;
  19820. var b = face[ 1 ] + shapesOffset;
  19821. var c = face[ 2 ] + shapesOffset;
  19822. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19823. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19824. }
  19825. };
  19826. /**
  19827. * @author astrodud / http://astrodud.isgreat.org/
  19828. * @author zz85 / https://github.com/zz85
  19829. * @author bhouston / http://exocortex.com
  19830. */
  19831. // points - to create a closed torus, one must use a set of points
  19832. // like so: [ a, b, c, d, a ], see first is the same as last.
  19833. // segments - the number of circumference segments to create
  19834. // phiStart - the starting radian
  19835. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19836. // 2*pi is a closed lathe, less than 2PI is a portion.
  19837. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19838. THREE.Geometry.call( this );
  19839. segments = segments || 12;
  19840. phiStart = phiStart || 0;
  19841. phiLength = phiLength || 2 * Math.PI;
  19842. var inversePointLength = 1.0 / ( points.length - 1 );
  19843. var inverseSegments = 1.0 / segments;
  19844. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19845. var phi = phiStart + i * inverseSegments * phiLength;
  19846. var c = Math.cos( phi ),
  19847. s = Math.sin( phi );
  19848. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19849. var pt = points[ j ];
  19850. var vertex = new THREE.Vector3();
  19851. vertex.x = c * pt.x - s * pt.y;
  19852. vertex.y = s * pt.x + c * pt.y;
  19853. vertex.z = pt.z;
  19854. this.vertices.push( vertex );
  19855. }
  19856. }
  19857. var np = points.length;
  19858. for ( var i = 0, il = segments; i < il; i ++ ) {
  19859. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19860. var base = j + np * i;
  19861. var a = base;
  19862. var b = base + np;
  19863. var c = base + 1 + np;
  19864. var d = base + 1;
  19865. var u0 = i * inverseSegments;
  19866. var v0 = j * inversePointLength;
  19867. var u1 = u0 + inverseSegments;
  19868. var v1 = v0 + inversePointLength;
  19869. this.faces.push( new THREE.Face3( a, b, d ) );
  19870. this.faceVertexUvs[ 0 ].push( [
  19871. new THREE.Vector2( u0, v0 ),
  19872. new THREE.Vector2( u1, v0 ),
  19873. new THREE.Vector2( u0, v1 )
  19874. ] );
  19875. this.faces.push( new THREE.Face3( b, c, d ) );
  19876. this.faceVertexUvs[ 0 ].push( [
  19877. new THREE.Vector2( u1, v0 ),
  19878. new THREE.Vector2( u1, v1 ),
  19879. new THREE.Vector2( u0, v1 )
  19880. ] );
  19881. }
  19882. }
  19883. this.mergeVertices();
  19884. this.computeCentroids();
  19885. this.computeFaceNormals();
  19886. this.computeVertexNormals();
  19887. };
  19888. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19889. /**
  19890. * @author mrdoob / http://mrdoob.com/
  19891. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19892. */
  19893. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19894. THREE.Geometry.call( this );
  19895. this.width = width;
  19896. this.height = height;
  19897. this.widthSegments = widthSegments || 1;
  19898. this.heightSegments = heightSegments || 1;
  19899. var ix, iz;
  19900. var width_half = width / 2;
  19901. var height_half = height / 2;
  19902. var gridX = this.widthSegments;
  19903. var gridZ = this.heightSegments;
  19904. var gridX1 = gridX + 1;
  19905. var gridZ1 = gridZ + 1;
  19906. var segment_width = this.width / gridX;
  19907. var segment_height = this.height / gridZ;
  19908. var normal = new THREE.Vector3( 0, 0, 1 );
  19909. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19910. for ( ix = 0; ix < gridX1; ix ++ ) {
  19911. var x = ix * segment_width - width_half;
  19912. var y = iz * segment_height - height_half;
  19913. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19914. }
  19915. }
  19916. for ( iz = 0; iz < gridZ; iz ++ ) {
  19917. for ( ix = 0; ix < gridX; ix ++ ) {
  19918. var a = ix + gridX1 * iz;
  19919. var b = ix + gridX1 * ( iz + 1 );
  19920. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19921. var d = ( ix + 1 ) + gridX1 * iz;
  19922. var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
  19923. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
  19924. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
  19925. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
  19926. var face = new THREE.Face3( a, b, d );
  19927. face.normal.copy( normal );
  19928. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19929. this.faces.push( face );
  19930. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19931. face = new THREE.Face3( b, c, d );
  19932. face.normal.copy( normal );
  19933. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19934. this.faces.push( face );
  19935. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19936. }
  19937. }
  19938. this.computeCentroids();
  19939. };
  19940. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19941. /**
  19942. * @author Kaleb Murphy
  19943. */
  19944. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19945. THREE.Geometry.call( this );
  19946. innerRadius = innerRadius || 0;
  19947. outerRadius = outerRadius || 50;
  19948. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19949. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19950. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19951. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19952. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19953. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19954. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19955. var vertex = new THREE.Vector3();
  19956. var segment = thetaStart + o / thetaSegments * thetaLength;
  19957. vertex.x = radius * Math.cos( segment );
  19958. vertex.y = radius * Math.sin( segment );
  19959. this.vertices.push( vertex );
  19960. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19961. }
  19962. radius += radiusStep;
  19963. }
  19964. var n = new THREE.Vector3( 0, 0, 1 );
  19965. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19966. var thetaSegment = i * thetaSegments;
  19967. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19968. var segment = o + thetaSegment;
  19969. var v1 = segment + i;
  19970. var v2 = segment + thetaSegments + i;
  19971. var v3 = segment + thetaSegments + 1 + i;
  19972. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19973. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19974. v1 = segment + i;
  19975. v2 = segment + thetaSegments + 1 + i;
  19976. v3 = segment + 1 + i;
  19977. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19978. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19979. }
  19980. }
  19981. this.computeCentroids();
  19982. this.computeFaceNormals();
  19983. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19984. };
  19985. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19986. /**
  19987. * @author mrdoob / http://mrdoob.com/
  19988. */
  19989. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19990. THREE.Geometry.call( this );
  19991. this.radius = radius = radius || 50;
  19992. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19993. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19994. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19995. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19996. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19997. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19998. var x, y, vertices = [], uvs = [];
  19999. for ( y = 0; y <= heightSegments; y ++ ) {
  20000. var verticesRow = [];
  20001. var uvsRow = [];
  20002. for ( x = 0; x <= widthSegments; x ++ ) {
  20003. var u = x / widthSegments;
  20004. var v = y / heightSegments;
  20005. var vertex = new THREE.Vector3();
  20006. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20007. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  20008. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20009. this.vertices.push( vertex );
  20010. verticesRow.push( this.vertices.length - 1 );
  20011. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  20012. }
  20013. vertices.push( verticesRow );
  20014. uvs.push( uvsRow );
  20015. }
  20016. for ( y = 0; y < this.heightSegments; y ++ ) {
  20017. for ( x = 0; x < this.widthSegments; x ++ ) {
  20018. var v1 = vertices[ y ][ x + 1 ];
  20019. var v2 = vertices[ y ][ x ];
  20020. var v3 = vertices[ y + 1 ][ x ];
  20021. var v4 = vertices[ y + 1 ][ x + 1 ];
  20022. var n1 = this.vertices[ v1 ].clone().normalize();
  20023. var n2 = this.vertices[ v2 ].clone().normalize();
  20024. var n3 = this.vertices[ v3 ].clone().normalize();
  20025. var n4 = this.vertices[ v4 ].clone().normalize();
  20026. var uv1 = uvs[ y ][ x + 1 ].clone();
  20027. var uv2 = uvs[ y ][ x ].clone();
  20028. var uv3 = uvs[ y + 1 ][ x ].clone();
  20029. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  20030. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  20031. uv1.x = ( uv1.x + uv2.x ) / 2;
  20032. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  20033. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  20034. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  20035. uv3.x = ( uv3.x + uv4.x ) / 2;
  20036. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  20037. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  20038. } else {
  20039. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  20040. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  20041. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  20042. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  20043. }
  20044. }
  20045. }
  20046. this.computeCentroids();
  20047. this.computeFaceNormals();
  20048. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20049. };
  20050. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20051. /**
  20052. * @author zz85 / http://www.lab4games.net/zz85/blog
  20053. * @author alteredq / http://alteredqualia.com/
  20054. *
  20055. * For creating 3D text geometry in three.js
  20056. *
  20057. * Text = 3D Text
  20058. *
  20059. * parameters = {
  20060. * size: <float>, // size of the text
  20061. * height: <float>, // thickness to extrude text
  20062. * curveSegments: <int>, // number of points on the curves
  20063. *
  20064. * font: <string>, // font name
  20065. * weight: <string>, // font weight (normal, bold)
  20066. * style: <string>, // font style (normal, italics)
  20067. *
  20068. * bevelEnabled: <bool>, // turn on bevel
  20069. * bevelThickness: <float>, // how deep into text bevel goes
  20070. * bevelSize: <float>, // how far from text outline is bevel
  20071. * }
  20072. *
  20073. */
  20074. /* Usage Examples
  20075. // TextGeometry wrapper
  20076. var text3d = new TextGeometry( text, options );
  20077. // Complete manner
  20078. var textShapes = THREE.FontUtils.generateShapes( text, options );
  20079. var text3d = new ExtrudeGeometry( textShapes, options );
  20080. */
  20081. THREE.TextGeometry = function ( text, parameters ) {
  20082. parameters = parameters || {};
  20083. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  20084. // translate parameters to ExtrudeGeometry API
  20085. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  20086. // defaults
  20087. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  20088. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  20089. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  20090. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  20091. };
  20092. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  20093. /**
  20094. * @author oosmoxiecode
  20095. * @author mrdoob / http://mrdoob.com/
  20096. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  20097. */
  20098. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  20099. THREE.Geometry.call( this );
  20100. var scope = this;
  20101. this.radius = radius || 100;
  20102. this.tube = tube || 40;
  20103. this.radialSegments = radialSegments || 8;
  20104. this.tubularSegments = tubularSegments || 6;
  20105. this.arc = arc || Math.PI * 2;
  20106. var center = new THREE.Vector3(), uvs = [], normals = [];
  20107. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  20108. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  20109. var u = i / this.tubularSegments * this.arc;
  20110. var v = j / this.radialSegments * Math.PI * 2;
  20111. center.x = this.radius * Math.cos( u );
  20112. center.y = this.radius * Math.sin( u );
  20113. var vertex = new THREE.Vector3();
  20114. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  20115. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  20116. vertex.z = this.tube * Math.sin( v );
  20117. this.vertices.push( vertex );
  20118. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  20119. normals.push( vertex.clone().sub( center ).normalize() );
  20120. }
  20121. }
  20122. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  20123. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  20124. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  20125. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20126. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  20127. var d = ( this.tubularSegments + 1 ) * j + i;
  20128. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  20129. this.faces.push( face );
  20130. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  20131. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  20132. this.faces.push( face );
  20133. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  20134. }
  20135. }
  20136. this.computeCentroids();
  20137. this.computeFaceNormals();
  20138. };
  20139. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20140. /**
  20141. * @author oosmoxiecode
  20142. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20143. */
  20144. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  20145. THREE.Geometry.call( this );
  20146. var scope = this;
  20147. this.radius = radius || 100;
  20148. this.tube = tube || 40;
  20149. this.radialSegments = radialSegments || 64;
  20150. this.tubularSegments = tubularSegments || 8;
  20151. this.p = p || 2;
  20152. this.q = q || 3;
  20153. this.heightScale = heightScale || 1;
  20154. this.grid = new Array( this.radialSegments );
  20155. var tang = new THREE.Vector3();
  20156. var n = new THREE.Vector3();
  20157. var bitan = new THREE.Vector3();
  20158. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20159. this.grid[ i ] = new Array( this.tubularSegments );
  20160. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  20161. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  20162. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  20163. tang.subVectors( p2, p1 );
  20164. n.addVectors( p2, p1 );
  20165. bitan.crossVectors( tang, n );
  20166. n.crossVectors( bitan, tang );
  20167. bitan.normalize();
  20168. n.normalize();
  20169. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20170. var v = j / this.tubularSegments * 2 * Math.PI;
  20171. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20172. var cy = this.tube * Math.sin( v );
  20173. var pos = new THREE.Vector3();
  20174. pos.x = p1.x + cx * n.x + cy * bitan.x;
  20175. pos.y = p1.y + cx * n.y + cy * bitan.y;
  20176. pos.z = p1.z + cx * n.z + cy * bitan.z;
  20177. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  20178. }
  20179. }
  20180. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20181. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20182. var ip = ( i + 1 ) % this.radialSegments;
  20183. var jp = ( j + 1 ) % this.tubularSegments;
  20184. var a = this.grid[ i ][ j ];
  20185. var b = this.grid[ ip ][ j ];
  20186. var c = this.grid[ ip ][ jp ];
  20187. var d = this.grid[ i ][ jp ];
  20188. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  20189. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  20190. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20191. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20192. this.faces.push( new THREE.Face3( a, b, d ) );
  20193. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20194. this.faces.push( new THREE.Face3( b, c, d ) );
  20195. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20196. }
  20197. }
  20198. this.computeCentroids();
  20199. this.computeFaceNormals();
  20200. this.computeVertexNormals();
  20201. function getPos( u, in_q, in_p, radius, heightScale ) {
  20202. var cu = Math.cos( u );
  20203. var su = Math.sin( u );
  20204. var quOverP = in_q / in_p * u;
  20205. var cs = Math.cos( quOverP );
  20206. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  20207. var ty = radius * ( 2 + cs ) * su * 0.5;
  20208. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  20209. return new THREE.Vector3( tx, ty, tz );
  20210. }
  20211. };
  20212. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20213. /**
  20214. * @author WestLangley / https://github.com/WestLangley
  20215. * @author zz85 / https://github.com/zz85
  20216. * @author miningold / https://github.com/miningold
  20217. *
  20218. * Modified from the TorusKnotGeometry by @oosmoxiecode
  20219. *
  20220. * Creates a tube which extrudes along a 3d spline
  20221. *
  20222. * Uses parallel transport frames as described in
  20223. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20224. */
  20225. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  20226. THREE.Geometry.call( this );
  20227. this.path = path;
  20228. this.segments = segments || 64;
  20229. this.radius = radius || 1;
  20230. this.radialSegments = radialSegments || 8;
  20231. this.closed = closed || false;
  20232. this.grid = [];
  20233. var scope = this,
  20234. tangent,
  20235. normal,
  20236. binormal,
  20237. numpoints = this.segments + 1,
  20238. x, y, z,
  20239. tx, ty, tz,
  20240. u, v,
  20241. cx, cy,
  20242. pos, pos2 = new THREE.Vector3(),
  20243. i, j,
  20244. ip, jp,
  20245. a, b, c, d,
  20246. uva, uvb, uvc, uvd;
  20247. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  20248. tangents = frames.tangents,
  20249. normals = frames.normals,
  20250. binormals = frames.binormals;
  20251. // proxy internals
  20252. this.tangents = tangents;
  20253. this.normals = normals;
  20254. this.binormals = binormals;
  20255. function vert( x, y, z ) {
  20256. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20257. }
  20258. // consruct the grid
  20259. for ( i = 0; i < numpoints; i++ ) {
  20260. this.grid[ i ] = [];
  20261. u = i / ( numpoints - 1 );
  20262. pos = path.getPointAt( u );
  20263. tangent = tangents[ i ];
  20264. normal = normals[ i ];
  20265. binormal = binormals[ i ];
  20266. for ( j = 0; j < this.radialSegments; j++ ) {
  20267. v = j / this.radialSegments * 2 * Math.PI;
  20268. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20269. cy = this.radius * Math.sin( v );
  20270. pos2.copy( pos );
  20271. pos2.x += cx * normal.x + cy * binormal.x;
  20272. pos2.y += cx * normal.y + cy * binormal.y;
  20273. pos2.z += cx * normal.z + cy * binormal.z;
  20274. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20275. }
  20276. }
  20277. // construct the mesh
  20278. for ( i = 0; i < this.segments; i++ ) {
  20279. for ( j = 0; j < this.radialSegments; j++ ) {
  20280. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  20281. jp = (j + 1) % this.radialSegments;
  20282. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20283. b = this.grid[ ip ][ j ];
  20284. c = this.grid[ ip ][ jp ];
  20285. d = this.grid[ i ][ jp ];
  20286. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  20287. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  20288. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  20289. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  20290. this.faces.push( new THREE.Face3( a, b, d ) );
  20291. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20292. this.faces.push( new THREE.Face3( b, c, d ) );
  20293. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20294. }
  20295. }
  20296. this.computeCentroids();
  20297. this.computeFaceNormals();
  20298. this.computeVertexNormals();
  20299. };
  20300. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20301. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20302. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  20303. var tangent = new THREE.Vector3(),
  20304. normal = new THREE.Vector3(),
  20305. binormal = new THREE.Vector3(),
  20306. tangents = [],
  20307. normals = [],
  20308. binormals = [],
  20309. vec = new THREE.Vector3(),
  20310. mat = new THREE.Matrix4(),
  20311. numpoints = segments + 1,
  20312. theta,
  20313. epsilon = 0.0001,
  20314. smallest,
  20315. tx, ty, tz,
  20316. i, u, v;
  20317. // expose internals
  20318. this.tangents = tangents;
  20319. this.normals = normals;
  20320. this.binormals = binormals;
  20321. // compute the tangent vectors for each segment on the path
  20322. for ( i = 0; i < numpoints; i++ ) {
  20323. u = i / ( numpoints - 1 );
  20324. tangents[ i ] = path.getTangentAt( u );
  20325. tangents[ i ].normalize();
  20326. }
  20327. initialNormal3();
  20328. function initialNormal1(lastBinormal) {
  20329. // fixed start binormal. Has dangers of 0 vectors
  20330. normals[ 0 ] = new THREE.Vector3();
  20331. binormals[ 0 ] = new THREE.Vector3();
  20332. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20333. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20334. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20335. }
  20336. function initialNormal2() {
  20337. // This uses the Frenet-Serret formula for deriving binormal
  20338. var t2 = path.getTangentAt( epsilon );
  20339. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20340. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20341. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20342. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20343. }
  20344. function initialNormal3() {
  20345. // select an initial normal vector perpenicular to the first tangent vector,
  20346. // and in the direction of the smallest tangent xyz component
  20347. normals[ 0 ] = new THREE.Vector3();
  20348. binormals[ 0 ] = new THREE.Vector3();
  20349. smallest = Number.MAX_VALUE;
  20350. tx = Math.abs( tangents[ 0 ].x );
  20351. ty = Math.abs( tangents[ 0 ].y );
  20352. tz = Math.abs( tangents[ 0 ].z );
  20353. if ( tx <= smallest ) {
  20354. smallest = tx;
  20355. normal.set( 1, 0, 0 );
  20356. }
  20357. if ( ty <= smallest ) {
  20358. smallest = ty;
  20359. normal.set( 0, 1, 0 );
  20360. }
  20361. if ( tz <= smallest ) {
  20362. normal.set( 0, 0, 1 );
  20363. }
  20364. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20365. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20366. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20367. }
  20368. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20369. for ( i = 1; i < numpoints; i++ ) {
  20370. normals[ i ] = normals[ i-1 ].clone();
  20371. binormals[ i ] = binormals[ i-1 ].clone();
  20372. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20373. if ( vec.length() > epsilon ) {
  20374. vec.normalize();
  20375. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  20376. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20377. }
  20378. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20379. }
  20380. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20381. if ( closed ) {
  20382. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  20383. theta /= ( numpoints - 1 );
  20384. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20385. theta = -theta;
  20386. }
  20387. for ( i = 1; i < numpoints; i++ ) {
  20388. // twist a little...
  20389. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20390. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20391. }
  20392. }
  20393. };
  20394. /**
  20395. * @author clockworkgeek / https://github.com/clockworkgeek
  20396. * @author timothypratley / https://github.com/timothypratley
  20397. * @author WestLangley / http://github.com/WestLangley
  20398. */
  20399. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  20400. THREE.Geometry.call( this );
  20401. radius = radius || 1;
  20402. detail = detail || 0;
  20403. var that = this;
  20404. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20405. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  20406. }
  20407. var midpoints = [], p = this.vertices;
  20408. var f = [];
  20409. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20410. var v1 = p[ faces[ i ][ 0 ] ];
  20411. var v2 = p[ faces[ i ][ 1 ] ];
  20412. var v3 = p[ faces[ i ][ 2 ] ];
  20413. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20414. }
  20415. for ( var i = 0, l = f.length; i < l; i ++ ) {
  20416. subdivide(f[ i ], detail);
  20417. }
  20418. // Handle case when face straddles the seam
  20419. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20420. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20421. var x0 = uvs[ 0 ].x;
  20422. var x1 = uvs[ 1 ].x;
  20423. var x2 = uvs[ 2 ].x;
  20424. var max = Math.max( x0, Math.max( x1, x2 ) );
  20425. var min = Math.min( x0, Math.min( x1, x2 ) );
  20426. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  20427. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20428. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20429. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20430. }
  20431. }
  20432. // Apply radius
  20433. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20434. this.vertices[ i ].multiplyScalar( radius );
  20435. }
  20436. // Merge vertices
  20437. this.mergeVertices();
  20438. this.computeCentroids();
  20439. this.computeFaceNormals();
  20440. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20441. // Project vector onto sphere's surface
  20442. function prepare( vector ) {
  20443. var vertex = vector.normalize().clone();
  20444. vertex.index = that.vertices.push( vertex ) - 1;
  20445. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20446. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20447. var v = inclination( vector ) / Math.PI + 0.5;
  20448. vertex.uv = new THREE.Vector2( u, 1 - v );
  20449. return vertex;
  20450. }
  20451. // Approximate a curved face with recursively sub-divided triangles.
  20452. function make( v1, v2, v3 ) {
  20453. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20454. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20455. that.faces.push( face );
  20456. var azi = azimuth( face.centroid );
  20457. that.faceVertexUvs[ 0 ].push( [
  20458. correctUV( v1.uv, v1, azi ),
  20459. correctUV( v2.uv, v2, azi ),
  20460. correctUV( v3.uv, v3, azi )
  20461. ] );
  20462. }
  20463. // Analytically subdivide a face to the required detail level.
  20464. function subdivide(face, detail ) {
  20465. var cols = Math.pow(2, detail);
  20466. var cells = Math.pow(4, detail);
  20467. var a = prepare( that.vertices[ face.a ] );
  20468. var b = prepare( that.vertices[ face.b ] );
  20469. var c = prepare( that.vertices[ face.c ] );
  20470. var v = [];
  20471. // Construct all of the vertices for this subdivision.
  20472. for ( var i = 0 ; i <= cols; i ++ ) {
  20473. v[ i ] = [];
  20474. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20475. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20476. var rows = cols - i;
  20477. for ( var j = 0; j <= rows; j ++) {
  20478. if ( j == 0 && i == cols ) {
  20479. v[ i ][ j ] = aj;
  20480. } else {
  20481. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20482. }
  20483. }
  20484. }
  20485. // Construct all of the faces.
  20486. for ( var i = 0; i < cols ; i ++ ) {
  20487. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20488. var k = Math.floor( j / 2 );
  20489. if ( j % 2 == 0 ) {
  20490. make(
  20491. v[ i ][ k + 1],
  20492. v[ i + 1 ][ k ],
  20493. v[ i ][ k ]
  20494. );
  20495. } else {
  20496. make(
  20497. v[ i ][ k + 1 ],
  20498. v[ i + 1][ k + 1],
  20499. v[ i + 1 ][ k ]
  20500. );
  20501. }
  20502. }
  20503. }
  20504. }
  20505. // Angle around the Y axis, counter-clockwise when looking from above.
  20506. function azimuth( vector ) {
  20507. return Math.atan2( vector.z, -vector.x );
  20508. }
  20509. // Angle above the XZ plane.
  20510. function inclination( vector ) {
  20511. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20512. }
  20513. // Texture fixing helper. Spheres have some odd behaviours.
  20514. function correctUV( uv, vector, azimuth ) {
  20515. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20516. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20517. return uv.clone();
  20518. }
  20519. };
  20520. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20521. /**
  20522. * @author timothypratley / https://github.com/timothypratley
  20523. */
  20524. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20525. this.radius = radius;
  20526. this.detail = detail;
  20527. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20528. var vertices = [
  20529. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20530. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20531. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20532. ];
  20533. var faces = [
  20534. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20535. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20536. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20537. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20538. ];
  20539. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20540. };
  20541. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20542. /**
  20543. * @author timothypratley / https://github.com/timothypratley
  20544. */
  20545. THREE.OctahedronGeometry = function ( radius, detail ) {
  20546. var vertices = [
  20547. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20548. ];
  20549. var faces = [
  20550. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20551. ];
  20552. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20553. };
  20554. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20555. /**
  20556. * @author timothypratley / https://github.com/timothypratley
  20557. */
  20558. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20559. var vertices = [
  20560. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20561. ];
  20562. var faces = [
  20563. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20564. ];
  20565. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20566. };
  20567. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20568. /**
  20569. * @author zz85 / https://github.com/zz85
  20570. * Parametric Surfaces Geometry
  20571. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20572. *
  20573. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20574. *
  20575. */
  20576. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20577. THREE.Geometry.call( this );
  20578. var verts = this.vertices;
  20579. var faces = this.faces;
  20580. var uvs = this.faceVertexUvs[ 0 ];
  20581. var i, il, j, p;
  20582. var u, v;
  20583. var stackCount = stacks + 1;
  20584. var sliceCount = slices + 1;
  20585. for ( i = 0; i <= stacks; i ++ ) {
  20586. v = i / stacks;
  20587. for ( j = 0; j <= slices; j ++ ) {
  20588. u = j / slices;
  20589. p = func( u, v );
  20590. verts.push( p );
  20591. }
  20592. }
  20593. var a, b, c, d;
  20594. var uva, uvb, uvc, uvd;
  20595. for ( i = 0; i < stacks; i ++ ) {
  20596. for ( j = 0; j < slices; j ++ ) {
  20597. a = i * sliceCount + j;
  20598. b = i * sliceCount + j + 1;
  20599. c = (i + 1) * sliceCount + j + 1;
  20600. d = (i + 1) * sliceCount + j;
  20601. uva = new THREE.Vector2( j / slices, i / stacks );
  20602. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20603. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20604. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20605. faces.push( new THREE.Face3( a, b, d ) );
  20606. uvs.push( [ uva, uvb, uvd ] );
  20607. faces.push( new THREE.Face3( b, c, d ) );
  20608. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20609. }
  20610. }
  20611. // console.log(this);
  20612. // magic bullet
  20613. // var diff = this.mergeVertices();
  20614. // console.log('removed ', diff, ' vertices by merging');
  20615. this.computeCentroids();
  20616. this.computeFaceNormals();
  20617. this.computeVertexNormals();
  20618. };
  20619. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20620. /**
  20621. * @author sroucheray / http://sroucheray.org/
  20622. * @author mrdoob / http://mrdoob.com/
  20623. */
  20624. THREE.AxisHelper = function ( size ) {
  20625. size = size || 1;
  20626. var geometry = new THREE.Geometry();
  20627. geometry.vertices.push(
  20628. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20629. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20630. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20631. );
  20632. geometry.colors.push(
  20633. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20634. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20635. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20636. );
  20637. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20638. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20639. };
  20640. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20641. /**
  20642. * @author WestLangley / http://github.com/WestLangley
  20643. * @author zz85 / http://github.com/zz85
  20644. * @author bhouston / http://exocortex.com
  20645. *
  20646. * Creates an arrow for visualizing directions
  20647. *
  20648. * Parameters:
  20649. * dir - Vector3
  20650. * origin - Vector3
  20651. * length - Number
  20652. * hex - color in hex value
  20653. * headLength - Number
  20654. * headWidth - Number
  20655. */
  20656. THREE.ArrowHelper = function ( dir, origin, length, hex, headLength, headWidth ) {
  20657. // dir is assumed to be normalized
  20658. THREE.Object3D.call( this );
  20659. if ( hex === undefined ) hex = 0xffff00;
  20660. if ( length === undefined ) length = 1;
  20661. if ( headLength === undefined ) headLength = 0.2 * length;
  20662. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20663. this.position = origin;
  20664. var lineGeometry = new THREE.Geometry();
  20665. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20666. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20667. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20668. this.line.matrixAutoUpdate = false;
  20669. this.add( this.line );
  20670. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  20671. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20672. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20673. this.cone.matrixAutoUpdate = false;
  20674. this.add( this.cone );
  20675. this.setDirection( dir );
  20676. this.setLength( length, headLength, headWidth );
  20677. };
  20678. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20679. THREE.ArrowHelper.prototype.setDirection = function () {
  20680. var axis = new THREE.Vector3();
  20681. var radians;
  20682. return function ( dir ) {
  20683. // dir is assumed to be normalized
  20684. if ( dir.y > 0.99999 ) {
  20685. this.quaternion.set( 0, 0, 0, 1 );
  20686. } else if ( dir.y < - 0.99999 ) {
  20687. this.quaternion.set( 1, 0, 0, 0 );
  20688. } else {
  20689. axis.set( dir.z, 0, - dir.x ).normalize();
  20690. radians = Math.acos( dir.y );
  20691. this.quaternion.setFromAxisAngle( axis, radians );
  20692. }
  20693. };
  20694. }();
  20695. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20696. if ( headLength === undefined ) headLength = 0.2 * length;
  20697. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20698. this.line.scale.set( 1, length, 1 );
  20699. this.line.updateMatrix();
  20700. this.cone.scale.set( headWidth, headLength, headWidth );
  20701. this.cone.position.y = length;
  20702. this.cone.updateMatrix();
  20703. };
  20704. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20705. this.line.material.color.setHex( hex );
  20706. this.cone.material.color.setHex( hex );
  20707. };
  20708. /**
  20709. * @author mrdoob / http://mrdoob.com/
  20710. */
  20711. THREE.BoxHelper = function ( object ) {
  20712. // 5____4
  20713. // 1/___0/|
  20714. // | 6__|_7
  20715. // 2/___3/
  20716. var vertices = [
  20717. new THREE.Vector3( 1, 1, 1 ),
  20718. new THREE.Vector3( - 1, 1, 1 ),
  20719. new THREE.Vector3( - 1, - 1, 1 ),
  20720. new THREE.Vector3( 1, - 1, 1 ),
  20721. new THREE.Vector3( 1, 1, - 1 ),
  20722. new THREE.Vector3( - 1, 1, - 1 ),
  20723. new THREE.Vector3( - 1, - 1, - 1 ),
  20724. new THREE.Vector3( 1, - 1, - 1 )
  20725. ];
  20726. this.vertices = vertices;
  20727. // TODO: Wouldn't be nice if Line had .segments?
  20728. var geometry = new THREE.Geometry();
  20729. geometry.vertices.push(
  20730. vertices[ 0 ], vertices[ 1 ],
  20731. vertices[ 1 ], vertices[ 2 ],
  20732. vertices[ 2 ], vertices[ 3 ],
  20733. vertices[ 3 ], vertices[ 0 ],
  20734. vertices[ 4 ], vertices[ 5 ],
  20735. vertices[ 5 ], vertices[ 6 ],
  20736. vertices[ 6 ], vertices[ 7 ],
  20737. vertices[ 7 ], vertices[ 4 ],
  20738. vertices[ 0 ], vertices[ 4 ],
  20739. vertices[ 1 ], vertices[ 5 ],
  20740. vertices[ 2 ], vertices[ 6 ],
  20741. vertices[ 3 ], vertices[ 7 ]
  20742. );
  20743. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20744. if ( object !== undefined ) {
  20745. this.update( object );
  20746. }
  20747. };
  20748. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20749. THREE.BoxHelper.prototype.update = function ( object ) {
  20750. var geometry = object.geometry;
  20751. if ( geometry.boundingBox === null ) {
  20752. geometry.computeBoundingBox();
  20753. }
  20754. var min = geometry.boundingBox.min;
  20755. var max = geometry.boundingBox.max;
  20756. var vertices = this.vertices;
  20757. vertices[ 0 ].set( max.x, max.y, max.z );
  20758. vertices[ 1 ].set( min.x, max.y, max.z );
  20759. vertices[ 2 ].set( min.x, min.y, max.z );
  20760. vertices[ 3 ].set( max.x, min.y, max.z );
  20761. vertices[ 4 ].set( max.x, max.y, min.z );
  20762. vertices[ 5 ].set( min.x, max.y, min.z );
  20763. vertices[ 6 ].set( min.x, min.y, min.z );
  20764. vertices[ 7 ].set( max.x, min.y, min.z );
  20765. this.geometry.computeBoundingSphere();
  20766. this.geometry.verticesNeedUpdate = true;
  20767. this.matrixAutoUpdate = false;
  20768. this.matrixWorld = object.matrixWorld;
  20769. };
  20770. /**
  20771. * @author WestLangley / http://github.com/WestLangley
  20772. */
  20773. // a helper to show the world-axis-aligned bounding box for an object
  20774. THREE.BoundingBoxHelper = function ( object, hex ) {
  20775. var color = ( hex !== undefined ) ? hex : 0x888888;
  20776. this.object = object;
  20777. this.box = new THREE.Box3();
  20778. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20779. };
  20780. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20781. THREE.BoundingBoxHelper.prototype.update = function () {
  20782. this.box.setFromObject( this.object );
  20783. this.box.size( this.scale );
  20784. this.box.center( this.position );
  20785. };
  20786. /**
  20787. * @author alteredq / http://alteredqualia.com/
  20788. *
  20789. * - shows frustum, line of sight and up of the camera
  20790. * - suitable for fast updates
  20791. * - based on frustum visualization in lightgl.js shadowmap example
  20792. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20793. */
  20794. THREE.CameraHelper = function ( camera ) {
  20795. var geometry = new THREE.Geometry();
  20796. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20797. var pointMap = {};
  20798. // colors
  20799. var hexFrustum = 0xffaa00;
  20800. var hexCone = 0xff0000;
  20801. var hexUp = 0x00aaff;
  20802. var hexTarget = 0xffffff;
  20803. var hexCross = 0x333333;
  20804. // near
  20805. addLine( "n1", "n2", hexFrustum );
  20806. addLine( "n2", "n4", hexFrustum );
  20807. addLine( "n4", "n3", hexFrustum );
  20808. addLine( "n3", "n1", hexFrustum );
  20809. // far
  20810. addLine( "f1", "f2", hexFrustum );
  20811. addLine( "f2", "f4", hexFrustum );
  20812. addLine( "f4", "f3", hexFrustum );
  20813. addLine( "f3", "f1", hexFrustum );
  20814. // sides
  20815. addLine( "n1", "f1", hexFrustum );
  20816. addLine( "n2", "f2", hexFrustum );
  20817. addLine( "n3", "f3", hexFrustum );
  20818. addLine( "n4", "f4", hexFrustum );
  20819. // cone
  20820. addLine( "p", "n1", hexCone );
  20821. addLine( "p", "n2", hexCone );
  20822. addLine( "p", "n3", hexCone );
  20823. addLine( "p", "n4", hexCone );
  20824. // up
  20825. addLine( "u1", "u2", hexUp );
  20826. addLine( "u2", "u3", hexUp );
  20827. addLine( "u3", "u1", hexUp );
  20828. // target
  20829. addLine( "c", "t", hexTarget );
  20830. addLine( "p", "c", hexCross );
  20831. // cross
  20832. addLine( "cn1", "cn2", hexCross );
  20833. addLine( "cn3", "cn4", hexCross );
  20834. addLine( "cf1", "cf2", hexCross );
  20835. addLine( "cf3", "cf4", hexCross );
  20836. function addLine( a, b, hex ) {
  20837. addPoint( a, hex );
  20838. addPoint( b, hex );
  20839. }
  20840. function addPoint( id, hex ) {
  20841. geometry.vertices.push( new THREE.Vector3() );
  20842. geometry.colors.push( new THREE.Color( hex ) );
  20843. if ( pointMap[ id ] === undefined ) {
  20844. pointMap[ id ] = [];
  20845. }
  20846. pointMap[ id ].push( geometry.vertices.length - 1 );
  20847. }
  20848. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20849. this.camera = camera;
  20850. this.matrixWorld = camera.matrixWorld;
  20851. this.matrixAutoUpdate = false;
  20852. this.pointMap = pointMap;
  20853. this.update();
  20854. };
  20855. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20856. THREE.CameraHelper.prototype.update = function () {
  20857. var vector = new THREE.Vector3();
  20858. var camera = new THREE.Camera();
  20859. var projector = new THREE.Projector();
  20860. return function () {
  20861. var scope = this;
  20862. var w = 1, h = 1;
  20863. // we need just camera projection matrix
  20864. // world matrix must be identity
  20865. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20866. // center / target
  20867. setPoint( "c", 0, 0, -1 );
  20868. setPoint( "t", 0, 0, 1 );
  20869. // near
  20870. setPoint( "n1", -w, -h, -1 );
  20871. setPoint( "n2", w, -h, -1 );
  20872. setPoint( "n3", -w, h, -1 );
  20873. setPoint( "n4", w, h, -1 );
  20874. // far
  20875. setPoint( "f1", -w, -h, 1 );
  20876. setPoint( "f2", w, -h, 1 );
  20877. setPoint( "f3", -w, h, 1 );
  20878. setPoint( "f4", w, h, 1 );
  20879. // up
  20880. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20881. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20882. setPoint( "u3", 0, h * 2, -1 );
  20883. // cross
  20884. setPoint( "cf1", -w, 0, 1 );
  20885. setPoint( "cf2", w, 0, 1 );
  20886. setPoint( "cf3", 0, -h, 1 );
  20887. setPoint( "cf4", 0, h, 1 );
  20888. setPoint( "cn1", -w, 0, -1 );
  20889. setPoint( "cn2", w, 0, -1 );
  20890. setPoint( "cn3", 0, -h, -1 );
  20891. setPoint( "cn4", 0, h, -1 );
  20892. function setPoint( point, x, y, z ) {
  20893. vector.set( x, y, z );
  20894. projector.unprojectVector( vector, camera );
  20895. var points = scope.pointMap[ point ];
  20896. if ( points !== undefined ) {
  20897. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20898. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20899. }
  20900. }
  20901. }
  20902. this.geometry.verticesNeedUpdate = true;
  20903. };
  20904. }();
  20905. /**
  20906. * @author alteredq / http://alteredqualia.com/
  20907. * @author mrdoob / http://mrdoob.com/
  20908. * @author WestLangley / http://github.com/WestLangley
  20909. */
  20910. THREE.DirectionalLightHelper = function ( light, size ) {
  20911. THREE.Object3D.call( this );
  20912. this.light = light;
  20913. this.light.updateMatrixWorld();
  20914. this.matrixWorld = light.matrixWorld;
  20915. this.matrixAutoUpdate = false;
  20916. size = size || 1;
  20917. var geometry = new THREE.PlaneGeometry( size, size );
  20918. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20919. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20920. this.lightPlane = new THREE.Mesh( geometry, material );
  20921. this.add( this.lightPlane );
  20922. geometry = new THREE.Geometry();
  20923. geometry.vertices.push( new THREE.Vector3() );
  20924. geometry.vertices.push( new THREE.Vector3() );
  20925. material = new THREE.LineBasicMaterial( { fog: false } );
  20926. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20927. this.targetLine = new THREE.Line( geometry, material );
  20928. this.add( this.targetLine );
  20929. this.update();
  20930. };
  20931. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20932. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20933. this.lightPlane.geometry.dispose();
  20934. this.lightPlane.material.dispose();
  20935. this.targetLine.geometry.dispose();
  20936. this.targetLine.material.dispose();
  20937. };
  20938. THREE.DirectionalLightHelper.prototype.update = function () {
  20939. var v1 = new THREE.Vector3();
  20940. var v2 = new THREE.Vector3();
  20941. var v3 = new THREE.Vector3();
  20942. return function () {
  20943. v1.setFromMatrixPosition( this.light.matrixWorld );
  20944. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20945. v3.subVectors( v2, v1 );
  20946. this.lightPlane.lookAt( v3 );
  20947. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20948. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20949. this.targetLine.geometry.verticesNeedUpdate = true;
  20950. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20951. }
  20952. }();
  20953. /**
  20954. * @author WestLangley / http://github.com/WestLangley
  20955. */
  20956. THREE.EdgesHelper = function ( object, hex ) {
  20957. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20958. var edge = [ 0, 0 ], hash = {};
  20959. var sortFunction = function ( a, b ) { return a - b };
  20960. var keys = [ 'a', 'b', 'c' ];
  20961. var geometry = new THREE.BufferGeometry();
  20962. var geometry2 = object.geometry.clone();
  20963. geometry2.mergeVertices();
  20964. geometry2.computeFaceNormals();
  20965. var vertices = geometry2.vertices;
  20966. var faces = geometry2.faces;
  20967. var numEdges = 0;
  20968. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20969. var face = faces[ i ];
  20970. for ( var j = 0; j < 3; j ++ ) {
  20971. edge[ 0 ] = face[ keys[ j ] ];
  20972. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20973. edge.sort( sortFunction );
  20974. var key = edge.toString();
  20975. if ( hash[ key ] === undefined ) {
  20976. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  20977. numEdges ++;
  20978. } else {
  20979. hash[ key ].face2 = i;
  20980. }
  20981. }
  20982. }
  20983. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  20984. var coords = geometry.attributes.position.array;
  20985. var index = 0;
  20986. for ( var key in hash ) {
  20987. var h = hash[ key ];
  20988. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK
  20989. var vertex = vertices[ h.vert1 ];
  20990. coords[ index ++ ] = vertex.x;
  20991. coords[ index ++ ] = vertex.y;
  20992. coords[ index ++ ] = vertex.z;
  20993. vertex = vertices[ h.vert2 ];
  20994. coords[ index ++ ] = vertex.x;
  20995. coords[ index ++ ] = vertex.y;
  20996. coords[ index ++ ] = vertex.z;
  20997. }
  20998. }
  20999. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21000. this.matrixAutoUpdate = false;
  21001. this.matrixWorld = object.matrixWorld;
  21002. };
  21003. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  21004. /**
  21005. * @author mrdoob / http://mrdoob.com/
  21006. * @author WestLangley / http://github.com/WestLangley
  21007. */
  21008. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  21009. this.object = object;
  21010. this.size = ( size !== undefined ) ? size : 1;
  21011. var color = ( hex !== undefined ) ? hex : 0xffff00;
  21012. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21013. var geometry = new THREE.Geometry();
  21014. var faces = this.object.geometry.faces;
  21015. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21016. geometry.vertices.push( new THREE.Vector3() );
  21017. geometry.vertices.push( new THREE.Vector3() );
  21018. }
  21019. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21020. this.matrixAutoUpdate = false;
  21021. this.normalMatrix = new THREE.Matrix3();
  21022. this.update();
  21023. };
  21024. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21025. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  21026. var v1 = new THREE.Vector3();
  21027. return function ( object ) {
  21028. this.object.updateMatrixWorld( true );
  21029. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21030. var vertices = this.geometry.vertices;
  21031. var faces = this.object.geometry.faces;
  21032. var worldMatrix = this.object.matrixWorld;
  21033. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21034. var face = faces[ i ];
  21035. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21036. var idx = 2 * i;
  21037. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  21038. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  21039. }
  21040. this.geometry.verticesNeedUpdate = true;
  21041. return this;
  21042. }
  21043. }());
  21044. /**
  21045. * @author mrdoob / http://mrdoob.com/
  21046. */
  21047. THREE.GridHelper = function ( size, step ) {
  21048. var geometry = new THREE.Geometry();
  21049. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  21050. this.color1 = new THREE.Color( 0x444444 );
  21051. this.color2 = new THREE.Color( 0x888888 );
  21052. for ( var i = - size; i <= size; i += step ) {
  21053. geometry.vertices.push(
  21054. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  21055. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  21056. );
  21057. var color = i === 0 ? this.color1 : this.color2;
  21058. geometry.colors.push( color, color, color, color );
  21059. }
  21060. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21061. };
  21062. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  21063. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  21064. this.color1.set( colorCenterLine );
  21065. this.color2.set( colorGrid );
  21066. this.geometry.colorsNeedUpdate = true;
  21067. }
  21068. /**
  21069. * @author alteredq / http://alteredqualia.com/
  21070. * @author mrdoob / http://mrdoob.com/
  21071. */
  21072. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  21073. THREE.Object3D.call( this );
  21074. this.light = light;
  21075. this.light.updateMatrixWorld();
  21076. this.matrixWorld = light.matrixWorld;
  21077. this.matrixAutoUpdate = false;
  21078. this.colors = [ new THREE.Color(), new THREE.Color() ];
  21079. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21080. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21081. for ( var i = 0, il = 8; i < il; i ++ ) {
  21082. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  21083. }
  21084. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  21085. this.lightSphere = new THREE.Mesh( geometry, material );
  21086. this.add( this.lightSphere );
  21087. this.update();
  21088. };
  21089. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21090. THREE.HemisphereLightHelper.prototype.dispose = function () {
  21091. this.lightSphere.geometry.dispose();
  21092. this.lightSphere.material.dispose();
  21093. };
  21094. THREE.HemisphereLightHelper.prototype.update = function () {
  21095. var vector = new THREE.Vector3();
  21096. return function () {
  21097. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  21098. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  21099. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  21100. this.lightSphere.geometry.colorsNeedUpdate = true;
  21101. }
  21102. }();
  21103. /**
  21104. * @author alteredq / http://alteredqualia.com/
  21105. * @author mrdoob / http://mrdoob.com/
  21106. */
  21107. THREE.PointLightHelper = function ( light, sphereSize ) {
  21108. this.light = light;
  21109. this.light.updateMatrixWorld();
  21110. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21111. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21112. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21113. THREE.Mesh.call( this, geometry, material );
  21114. this.matrixWorld = this.light.matrixWorld;
  21115. this.matrixAutoUpdate = false;
  21116. /*
  21117. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  21118. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  21119. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  21120. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  21121. var d = light.distance;
  21122. if ( d === 0.0 ) {
  21123. this.lightDistance.visible = false;
  21124. } else {
  21125. this.lightDistance.scale.set( d, d, d );
  21126. }
  21127. this.add( this.lightDistance );
  21128. */
  21129. };
  21130. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  21131. THREE.PointLightHelper.prototype.dispose = function () {
  21132. this.geometry.dispose();
  21133. this.material.dispose();
  21134. };
  21135. THREE.PointLightHelper.prototype.update = function () {
  21136. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21137. /*
  21138. var d = this.light.distance;
  21139. if ( d === 0.0 ) {
  21140. this.lightDistance.visible = false;
  21141. } else {
  21142. this.lightDistance.visible = true;
  21143. this.lightDistance.scale.set( d, d, d );
  21144. }
  21145. */
  21146. };
  21147. /**
  21148. * @author alteredq / http://alteredqualia.com/
  21149. * @author mrdoob / http://mrdoob.com/
  21150. * @author WestLangley / http://github.com/WestLangley
  21151. */
  21152. THREE.SpotLightHelper = function ( light ) {
  21153. THREE.Object3D.call( this );
  21154. this.light = light;
  21155. this.light.updateMatrixWorld();
  21156. this.matrixWorld = light.matrixWorld;
  21157. this.matrixAutoUpdate = false;
  21158. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  21159. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  21160. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21161. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21162. this.cone = new THREE.Mesh( geometry, material );
  21163. this.add( this.cone );
  21164. this.update();
  21165. };
  21166. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21167. THREE.SpotLightHelper.prototype.dispose = function () {
  21168. this.cone.geometry.dispose();
  21169. this.cone.material.dispose();
  21170. };
  21171. THREE.SpotLightHelper.prototype.update = function () {
  21172. var vector = new THREE.Vector3();
  21173. var vector2 = new THREE.Vector3();
  21174. return function () {
  21175. var coneLength = this.light.distance ? this.light.distance : 10000;
  21176. var coneWidth = coneLength * Math.tan( this.light.angle );
  21177. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  21178. vector.setFromMatrixPosition( this.light.matrixWorld );
  21179. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  21180. this.cone.lookAt( vector2.sub( vector ) );
  21181. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21182. };
  21183. }();
  21184. /**
  21185. * @author mrdoob / http://mrdoob.com/
  21186. * @author WestLangley / http://github.com/WestLangley
  21187. */
  21188. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  21189. this.object = object;
  21190. this.size = ( size !== undefined ) ? size : 1;
  21191. var color = ( hex !== undefined ) ? hex : 0xff0000;
  21192. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21193. var geometry = new THREE.Geometry();
  21194. var vertices = object.geometry.vertices;
  21195. var faces = object.geometry.faces;
  21196. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21197. var face = faces[ i ];
  21198. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21199. geometry.vertices.push( new THREE.Vector3() );
  21200. geometry.vertices.push( new THREE.Vector3() );
  21201. }
  21202. }
  21203. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21204. this.matrixAutoUpdate = false;
  21205. this.normalMatrix = new THREE.Matrix3();
  21206. this.update();
  21207. };
  21208. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21209. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  21210. var v1 = new THREE.Vector3();
  21211. return function( object ) {
  21212. var keys = [ 'a', 'b', 'c', 'd' ];
  21213. this.object.updateMatrixWorld( true );
  21214. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21215. var vertices = this.geometry.vertices;
  21216. var verts = this.object.geometry.vertices;
  21217. var faces = this.object.geometry.faces;
  21218. var worldMatrix = this.object.matrixWorld;
  21219. var idx = 0;
  21220. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21221. var face = faces[ i ];
  21222. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21223. var vertexId = face[ keys[ j ] ];
  21224. var vertex = verts[ vertexId ];
  21225. var normal = face.vertexNormals[ j ];
  21226. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21227. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21228. v1.add( vertices[ idx ] );
  21229. idx = idx + 1;
  21230. vertices[ idx ].copy( v1 );
  21231. idx = idx + 1;
  21232. }
  21233. }
  21234. this.geometry.verticesNeedUpdate = true;
  21235. return this;
  21236. }
  21237. }());
  21238. /**
  21239. * @author mrdoob / http://mrdoob.com/
  21240. * @author WestLangley / http://github.com/WestLangley
  21241. */
  21242. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  21243. this.object = object;
  21244. this.size = ( size !== undefined ) ? size : 1;
  21245. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  21246. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21247. var geometry = new THREE.Geometry();
  21248. var vertices = object.geometry.vertices;
  21249. var faces = object.geometry.faces;
  21250. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21251. var face = faces[ i ];
  21252. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21253. geometry.vertices.push( new THREE.Vector3() );
  21254. geometry.vertices.push( new THREE.Vector3() );
  21255. }
  21256. }
  21257. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21258. this.matrixAutoUpdate = false;
  21259. this.update();
  21260. };
  21261. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  21262. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  21263. var v1 = new THREE.Vector3();
  21264. return function( object ) {
  21265. var keys = [ 'a', 'b', 'c', 'd' ];
  21266. this.object.updateMatrixWorld( true );
  21267. var vertices = this.geometry.vertices;
  21268. var verts = this.object.geometry.vertices;
  21269. var faces = this.object.geometry.faces;
  21270. var worldMatrix = this.object.matrixWorld;
  21271. var idx = 0;
  21272. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21273. var face = faces[ i ];
  21274. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21275. var vertexId = face[ keys[ j ] ];
  21276. var vertex = verts[ vertexId ];
  21277. var tangent = face.vertexTangents[ j ];
  21278. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21279. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21280. v1.add( vertices[ idx ] );
  21281. idx = idx + 1;
  21282. vertices[ idx ].copy( v1 );
  21283. idx = idx + 1;
  21284. }
  21285. }
  21286. this.geometry.verticesNeedUpdate = true;
  21287. return this;
  21288. }
  21289. }());
  21290. /**
  21291. * @author mrdoob / http://mrdoob.com/
  21292. */
  21293. THREE.WireframeHelper = function ( object, hex ) {
  21294. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21295. var edge = [ 0, 0 ], hash = {};
  21296. var sortFunction = function ( a, b ) { return a - b };
  21297. var keys = [ 'a', 'b', 'c' ];
  21298. var geometry = new THREE.BufferGeometry();
  21299. if ( object.geometry instanceof THREE.Geometry ) {
  21300. var vertices = object.geometry.vertices;
  21301. var faces = object.geometry.faces;
  21302. var numEdges = 0;
  21303. // allocate maximal size
  21304. var edges = new Uint32Array( 6 * faces.length );
  21305. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21306. var face = faces[ i ];
  21307. for ( var j = 0; j < 3; j ++ ) {
  21308. edge[ 0 ] = face[ keys[ j ] ];
  21309. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21310. edge.sort( sortFunction );
  21311. var key = edge.toString();
  21312. if ( hash[ key ] === undefined ) {
  21313. edges[ 2 * numEdges ] = edge[ 0 ];
  21314. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21315. hash[ key ] = true;
  21316. numEdges ++;
  21317. }
  21318. }
  21319. }
  21320. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21321. var coords = geometry.attributes.position.array;
  21322. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21323. for ( var j = 0; j < 2; j ++ ) {
  21324. var vertex = vertices[ edges [ 2 * i + j] ];
  21325. var index = 6 * i + 3 * j;
  21326. coords[ index + 0 ] = vertex.x;
  21327. coords[ index + 1 ] = vertex.y;
  21328. coords[ index + 2 ] = vertex.z;
  21329. }
  21330. }
  21331. } else if ( object.geometry instanceof THREE.BufferGeometry && object.geometry.attributes.index !== undefined ) { // indexed BufferGeometry
  21332. var vertices = object.geometry.attributes.position.array;
  21333. var indices = object.geometry.attributes.index.array;
  21334. var offsets = object.geometry.offsets;
  21335. var numEdges = 0;
  21336. // allocate maximal size
  21337. var edges = new Uint32Array( 2 * indices.length );
  21338. for ( var o = 0, ol = offsets.length; o < ol; ++ o ) {
  21339. var start = offsets[ o ].start;
  21340. var count = offsets[ o ].count;
  21341. var index = offsets[ o ].index;
  21342. for ( var i = start, il = start + count; i < il; i += 3 ) {
  21343. for ( var j = 0; j < 3; j ++ ) {
  21344. edge[ 0 ] = index + indices[ i + j ];
  21345. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  21346. edge.sort( sortFunction );
  21347. var key = edge.toString();
  21348. if ( hash[ key ] === undefined ) {
  21349. edges[ 2 * numEdges ] = edge[ 0 ];
  21350. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21351. hash[ key ] = true;
  21352. numEdges ++;
  21353. }
  21354. }
  21355. }
  21356. }
  21357. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21358. var coords = geometry.attributes.position.array;
  21359. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21360. for ( var j = 0; j < 2; j ++ ) {
  21361. var index = 6 * i + 3 * j;
  21362. var index2 = 3 * edges[ 2 * i + j];
  21363. coords[ index + 0 ] = vertices[ index2 ];
  21364. coords[ index + 1 ] = vertices[ index2 + 1 ];
  21365. coords[ index + 2 ] = vertices[ index2 + 2 ];
  21366. }
  21367. }
  21368. } else if ( object.geometry instanceof THREE.BufferGeometry ) { // non-indexed BufferGeometry
  21369. var vertices = object.geometry.attributes.position.array;
  21370. var numEdges = vertices.length / 3;
  21371. var numTris = numEdges / 3;
  21372. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21373. var coords = geometry.attributes.position.array;
  21374. for ( var i = 0, l = numTris; i < l; i ++ ) {
  21375. for ( var j = 0; j < 3; j ++ ) {
  21376. var index = 18 * i + 6 * j;
  21377. var index1 = 9 * i + 3 * j;
  21378. coords[ index + 0 ] = vertices[ index1 ];
  21379. coords[ index + 1 ] = vertices[ index1 + 1 ];
  21380. coords[ index + 2 ] = vertices[ index1 + 2 ];
  21381. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  21382. coords[ index + 3 ] = vertices[ index2 ];
  21383. coords[ index + 4 ] = vertices[ index2 + 1 ];
  21384. coords[ index + 5 ] = vertices[ index2 + 2 ];
  21385. }
  21386. }
  21387. }
  21388. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21389. this.matrixAutoUpdate = false;
  21390. this.matrixWorld = object.matrixWorld;
  21391. };
  21392. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21393. /**
  21394. * @author alteredq / http://alteredqualia.com/
  21395. */
  21396. THREE.ImmediateRenderObject = function () {
  21397. THREE.Object3D.call( this );
  21398. this.render = function ( renderCallback ) { };
  21399. };
  21400. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21401. /**
  21402. * @author mikael emtinger / http://gomo.se/
  21403. * @author alteredq / http://alteredqualia.com/
  21404. */
  21405. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21406. THREE.Object3D.call( this );
  21407. this.lensFlares = [];
  21408. this.positionScreen = new THREE.Vector3();
  21409. this.customUpdateCallback = undefined;
  21410. if( texture !== undefined ) {
  21411. this.add( texture, size, distance, blending, color );
  21412. }
  21413. };
  21414. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21415. /*
  21416. * Add: adds another flare
  21417. */
  21418. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21419. if( size === undefined ) size = -1;
  21420. if( distance === undefined ) distance = 0;
  21421. if( opacity === undefined ) opacity = 1;
  21422. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21423. if( blending === undefined ) blending = THREE.NormalBlending;
  21424. distance = Math.min( distance, Math.max( 0, distance ) );
  21425. this.lensFlares.push( { texture: texture, // THREE.Texture
  21426. size: size, // size in pixels (-1 = use texture.width)
  21427. distance: distance, // distance (0-1) from light source (0=at light source)
  21428. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  21429. scale: 1, // scale
  21430. rotation: 1, // rotation
  21431. opacity: opacity, // opacity
  21432. color: color, // color
  21433. blending: blending } ); // blending
  21434. };
  21435. /*
  21436. * Update lens flares update positions on all flares based on the screen position
  21437. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21438. */
  21439. THREE.LensFlare.prototype.updateLensFlares = function () {
  21440. var f, fl = this.lensFlares.length;
  21441. var flare;
  21442. var vecX = -this.positionScreen.x * 2;
  21443. var vecY = -this.positionScreen.y * 2;
  21444. for( f = 0; f < fl; f ++ ) {
  21445. flare = this.lensFlares[ f ];
  21446. flare.x = this.positionScreen.x + vecX * flare.distance;
  21447. flare.y = this.positionScreen.y + vecY * flare.distance;
  21448. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21449. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21450. }
  21451. };
  21452. /**
  21453. * @author alteredq / http://alteredqualia.com/
  21454. */
  21455. THREE.MorphBlendMesh = function( geometry, material ) {
  21456. THREE.Mesh.call( this, geometry, material );
  21457. this.animationsMap = {};
  21458. this.animationsList = [];
  21459. // prepare default animation
  21460. // (all frames played together in 1 second)
  21461. var numFrames = this.geometry.morphTargets.length;
  21462. var name = "__default";
  21463. var startFrame = 0;
  21464. var endFrame = numFrames - 1;
  21465. var fps = numFrames / 1;
  21466. this.createAnimation( name, startFrame, endFrame, fps );
  21467. this.setAnimationWeight( name, 1 );
  21468. };
  21469. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21470. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21471. var animation = {
  21472. startFrame: start,
  21473. endFrame: end,
  21474. length: end - start + 1,
  21475. fps: fps,
  21476. duration: ( end - start ) / fps,
  21477. lastFrame: 0,
  21478. currentFrame: 0,
  21479. active: false,
  21480. time: 0,
  21481. direction: 1,
  21482. weight: 1,
  21483. directionBackwards: false,
  21484. mirroredLoop: false
  21485. };
  21486. this.animationsMap[ name ] = animation;
  21487. this.animationsList.push( animation );
  21488. };
  21489. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21490. var pattern = /([a-z]+)(\d+)/;
  21491. var firstAnimation, frameRanges = {};
  21492. var geometry = this.geometry;
  21493. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21494. var morph = geometry.morphTargets[ i ];
  21495. var chunks = morph.name.match( pattern );
  21496. if ( chunks && chunks.length > 1 ) {
  21497. var name = chunks[ 1 ];
  21498. var num = chunks[ 2 ];
  21499. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21500. var range = frameRanges[ name ];
  21501. if ( i < range.start ) range.start = i;
  21502. if ( i > range.end ) range.end = i;
  21503. if ( ! firstAnimation ) firstAnimation = name;
  21504. }
  21505. }
  21506. for ( var name in frameRanges ) {
  21507. var range = frameRanges[ name ];
  21508. this.createAnimation( name, range.start, range.end, fps );
  21509. }
  21510. this.firstAnimation = firstAnimation;
  21511. };
  21512. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21513. var animation = this.animationsMap[ name ];
  21514. if ( animation ) {
  21515. animation.direction = 1;
  21516. animation.directionBackwards = false;
  21517. }
  21518. };
  21519. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21520. var animation = this.animationsMap[ name ];
  21521. if ( animation ) {
  21522. animation.direction = -1;
  21523. animation.directionBackwards = true;
  21524. }
  21525. };
  21526. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21527. var animation = this.animationsMap[ name ];
  21528. if ( animation ) {
  21529. animation.fps = fps;
  21530. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21531. }
  21532. };
  21533. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21534. var animation = this.animationsMap[ name ];
  21535. if ( animation ) {
  21536. animation.duration = duration;
  21537. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21538. }
  21539. };
  21540. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21541. var animation = this.animationsMap[ name ];
  21542. if ( animation ) {
  21543. animation.weight = weight;
  21544. }
  21545. };
  21546. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21547. var animation = this.animationsMap[ name ];
  21548. if ( animation ) {
  21549. animation.time = time;
  21550. }
  21551. };
  21552. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21553. var time = 0;
  21554. var animation = this.animationsMap[ name ];
  21555. if ( animation ) {
  21556. time = animation.time;
  21557. }
  21558. return time;
  21559. };
  21560. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21561. var duration = -1;
  21562. var animation = this.animationsMap[ name ];
  21563. if ( animation ) {
  21564. duration = animation.duration;
  21565. }
  21566. return duration;
  21567. };
  21568. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21569. var animation = this.animationsMap[ name ];
  21570. if ( animation ) {
  21571. animation.time = 0;
  21572. animation.active = true;
  21573. } else {
  21574. console.warn( "animation[" + name + "] undefined" );
  21575. }
  21576. };
  21577. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21578. var animation = this.animationsMap[ name ];
  21579. if ( animation ) {
  21580. animation.active = false;
  21581. }
  21582. };
  21583. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21584. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21585. var animation = this.animationsList[ i ];
  21586. if ( ! animation.active ) continue;
  21587. var frameTime = animation.duration / animation.length;
  21588. animation.time += animation.direction * delta;
  21589. if ( animation.mirroredLoop ) {
  21590. if ( animation.time > animation.duration || animation.time < 0 ) {
  21591. animation.direction *= -1;
  21592. if ( animation.time > animation.duration ) {
  21593. animation.time = animation.duration;
  21594. animation.directionBackwards = true;
  21595. }
  21596. if ( animation.time < 0 ) {
  21597. animation.time = 0;
  21598. animation.directionBackwards = false;
  21599. }
  21600. }
  21601. } else {
  21602. animation.time = animation.time % animation.duration;
  21603. if ( animation.time < 0 ) animation.time += animation.duration;
  21604. }
  21605. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21606. var weight = animation.weight;
  21607. if ( keyframe !== animation.currentFrame ) {
  21608. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21609. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21610. this.morphTargetInfluences[ keyframe ] = 0;
  21611. animation.lastFrame = animation.currentFrame;
  21612. animation.currentFrame = keyframe;
  21613. }
  21614. var mix = ( animation.time % frameTime ) / frameTime;
  21615. if ( animation.directionBackwards ) mix = 1 - mix;
  21616. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21617. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21618. }
  21619. };
  21620. /**
  21621. * @author mikael emtinger / http://gomo.se/
  21622. * @author alteredq / http://alteredqualia.com/
  21623. */
  21624. THREE.LensFlarePlugin = function () {
  21625. var _gl, _renderer, _precision, _lensFlare = {};
  21626. this.init = function ( renderer ) {
  21627. _gl = renderer.context;
  21628. _renderer = renderer;
  21629. _precision = renderer.getPrecision();
  21630. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21631. _lensFlare.faces = new Uint16Array( 6 );
  21632. var i = 0;
  21633. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21634. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21635. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21636. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21637. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21638. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21639. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21640. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21641. i = 0;
  21642. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21643. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21644. // buffers
  21645. _lensFlare.vertexBuffer = _gl.createBuffer();
  21646. _lensFlare.elementBuffer = _gl.createBuffer();
  21647. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21648. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21649. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21650. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21651. // textures
  21652. _lensFlare.tempTexture = _gl.createTexture();
  21653. _lensFlare.occlusionTexture = _gl.createTexture();
  21654. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21655. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21656. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21657. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21658. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21659. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21660. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21661. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21662. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21663. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21664. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21665. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21666. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21667. _lensFlare.hasVertexTexture = false;
  21668. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21669. } else {
  21670. _lensFlare.hasVertexTexture = true;
  21671. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21672. }
  21673. _lensFlare.attributes = {};
  21674. _lensFlare.uniforms = {};
  21675. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21676. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21677. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21678. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21679. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21680. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21681. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21682. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21683. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21684. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21685. };
  21686. /*
  21687. * Render lens flares
  21688. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21689. * reads these back and calculates occlusion.
  21690. * Then _lensFlare.update_lensFlares() is called to re-position and
  21691. * update transparency of flares. Then they are rendered.
  21692. *
  21693. */
  21694. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21695. var flares = scene.__webglFlares,
  21696. nFlares = flares.length;
  21697. if ( ! nFlares ) return;
  21698. var tempPosition = new THREE.Vector3();
  21699. var invAspect = viewportHeight / viewportWidth,
  21700. halfViewportWidth = viewportWidth * 0.5,
  21701. halfViewportHeight = viewportHeight * 0.5;
  21702. var size = 16 / viewportHeight,
  21703. scale = new THREE.Vector2( size * invAspect, size );
  21704. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21705. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21706. var uniforms = _lensFlare.uniforms,
  21707. attributes = _lensFlare.attributes;
  21708. // set _lensFlare program and reset blending
  21709. _gl.useProgram( _lensFlare.program );
  21710. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21711. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21712. // loop through all lens flares to update their occlusion and positions
  21713. // setup gl and common used attribs/unforms
  21714. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21715. _gl.uniform1i( uniforms.map, 1 );
  21716. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21717. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21718. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21719. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21720. _gl.disable( _gl.CULL_FACE );
  21721. _gl.depthMask( false );
  21722. var i, j, jl, flare, sprite;
  21723. for ( i = 0; i < nFlares; i ++ ) {
  21724. size = 16 / viewportHeight;
  21725. scale.set( size * invAspect, size );
  21726. // calc object screen position
  21727. flare = flares[ i ];
  21728. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21729. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21730. tempPosition.applyProjection( camera.projectionMatrix );
  21731. // setup arrays for gl programs
  21732. screenPosition.copy( tempPosition )
  21733. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21734. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21735. // screen cull
  21736. if ( _lensFlare.hasVertexTexture || (
  21737. screenPositionPixels.x > 0 &&
  21738. screenPositionPixels.x < viewportWidth &&
  21739. screenPositionPixels.y > 0 &&
  21740. screenPositionPixels.y < viewportHeight ) ) {
  21741. // save current RGB to temp texture
  21742. _gl.activeTexture( _gl.TEXTURE1 );
  21743. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21744. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21745. // render pink quad
  21746. _gl.uniform1i( uniforms.renderType, 0 );
  21747. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21748. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21749. _gl.disable( _gl.BLEND );
  21750. _gl.enable( _gl.DEPTH_TEST );
  21751. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21752. // copy result to occlusionMap
  21753. _gl.activeTexture( _gl.TEXTURE0 );
  21754. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21755. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21756. // restore graphics
  21757. _gl.uniform1i( uniforms.renderType, 1 );
  21758. _gl.disable( _gl.DEPTH_TEST );
  21759. _gl.activeTexture( _gl.TEXTURE1 );
  21760. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21761. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21762. // update object positions
  21763. flare.positionScreen.copy( screenPosition )
  21764. if ( flare.customUpdateCallback ) {
  21765. flare.customUpdateCallback( flare );
  21766. } else {
  21767. flare.updateLensFlares();
  21768. }
  21769. // render flares
  21770. _gl.uniform1i( uniforms.renderType, 2 );
  21771. _gl.enable( _gl.BLEND );
  21772. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21773. sprite = flare.lensFlares[ j ];
  21774. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21775. screenPosition.x = sprite.x;
  21776. screenPosition.y = sprite.y;
  21777. screenPosition.z = sprite.z;
  21778. size = sprite.size * sprite.scale / viewportHeight;
  21779. scale.x = size * invAspect;
  21780. scale.y = size;
  21781. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21782. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21783. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21784. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21785. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21786. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21787. _renderer.setTexture( sprite.texture, 1 );
  21788. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21789. }
  21790. }
  21791. }
  21792. }
  21793. // restore gl
  21794. _gl.enable( _gl.CULL_FACE );
  21795. _gl.enable( _gl.DEPTH_TEST );
  21796. _gl.depthMask( true );
  21797. };
  21798. function createProgram ( shader, precision ) {
  21799. var program = _gl.createProgram();
  21800. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21801. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21802. var prefix = "precision " + precision + " float;\n";
  21803. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21804. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21805. _gl.compileShader( fragmentShader );
  21806. _gl.compileShader( vertexShader );
  21807. _gl.attachShader( program, fragmentShader );
  21808. _gl.attachShader( program, vertexShader );
  21809. _gl.linkProgram( program );
  21810. return program;
  21811. };
  21812. };
  21813. /**
  21814. * @author alteredq / http://alteredqualia.com/
  21815. */
  21816. THREE.ShadowMapPlugin = function () {
  21817. var _gl,
  21818. _renderer,
  21819. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21820. _frustum = new THREE.Frustum(),
  21821. _projScreenMatrix = new THREE.Matrix4(),
  21822. _min = new THREE.Vector3(),
  21823. _max = new THREE.Vector3(),
  21824. _matrixPosition = new THREE.Vector3();
  21825. this.init = function ( renderer ) {
  21826. _gl = renderer.context;
  21827. _renderer = renderer;
  21828. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21829. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21830. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21831. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21832. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21833. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21834. _depthMaterial._shadowPass = true;
  21835. _depthMaterialMorph._shadowPass = true;
  21836. _depthMaterialSkin._shadowPass = true;
  21837. _depthMaterialMorphSkin._shadowPass = true;
  21838. };
  21839. this.render = function ( scene, camera ) {
  21840. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21841. this.update( scene, camera );
  21842. };
  21843. this.update = function ( scene, camera ) {
  21844. var i, il, j, jl, n,
  21845. shadowMap, shadowMatrix, shadowCamera,
  21846. program, buffer, material,
  21847. webglObject, object, light,
  21848. renderList,
  21849. lights = [],
  21850. k = 0,
  21851. fog = null;
  21852. // set GL state for depth map
  21853. _gl.clearColor( 1, 1, 1, 1 );
  21854. _gl.disable( _gl.BLEND );
  21855. _gl.enable( _gl.CULL_FACE );
  21856. _gl.frontFace( _gl.CCW );
  21857. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21858. _gl.cullFace( _gl.FRONT );
  21859. } else {
  21860. _gl.cullFace( _gl.BACK );
  21861. }
  21862. _renderer.setDepthTest( true );
  21863. // preprocess lights
  21864. // - skip lights that are not casting shadows
  21865. // - create virtual lights for cascaded shadow maps
  21866. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21867. light = scene.__lights[ i ];
  21868. if ( ! light.castShadow ) continue;
  21869. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21870. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21871. var virtualLight;
  21872. if ( ! light.shadowCascadeArray[ n ] ) {
  21873. virtualLight = createVirtualLight( light, n );
  21874. virtualLight.originalCamera = camera;
  21875. var gyro = new THREE.Gyroscope();
  21876. gyro.position = light.shadowCascadeOffset;
  21877. gyro.add( virtualLight );
  21878. gyro.add( virtualLight.target );
  21879. camera.add( gyro );
  21880. light.shadowCascadeArray[ n ] = virtualLight;
  21881. console.log( "Created virtualLight", virtualLight );
  21882. } else {
  21883. virtualLight = light.shadowCascadeArray[ n ];
  21884. }
  21885. updateVirtualLight( light, n );
  21886. lights[ k ] = virtualLight;
  21887. k ++;
  21888. }
  21889. } else {
  21890. lights[ k ] = light;
  21891. k ++;
  21892. }
  21893. }
  21894. // render depth map
  21895. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21896. light = lights[ i ];
  21897. if ( ! light.shadowMap ) {
  21898. var shadowFilter = THREE.LinearFilter;
  21899. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21900. shadowFilter = THREE.NearestFilter;
  21901. }
  21902. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21903. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21904. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21905. light.shadowMatrix = new THREE.Matrix4();
  21906. }
  21907. if ( ! light.shadowCamera ) {
  21908. if ( light instanceof THREE.SpotLight ) {
  21909. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21910. } else if ( light instanceof THREE.DirectionalLight ) {
  21911. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21912. } else {
  21913. console.error( "Unsupported light type for shadow" );
  21914. continue;
  21915. }
  21916. scene.add( light.shadowCamera );
  21917. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21918. }
  21919. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21920. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21921. light.shadowCamera.add( light.cameraHelper );
  21922. }
  21923. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21924. updateShadowCamera( camera, light );
  21925. }
  21926. shadowMap = light.shadowMap;
  21927. shadowMatrix = light.shadowMatrix;
  21928. shadowCamera = light.shadowCamera;
  21929. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  21930. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  21931. shadowCamera.lookAt( _matrixPosition );
  21932. shadowCamera.updateMatrixWorld();
  21933. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21934. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21935. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21936. // compute shadow matrix
  21937. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21938. 0.0, 0.5, 0.0, 0.5,
  21939. 0.0, 0.0, 0.5, 0.5,
  21940. 0.0, 0.0, 0.0, 1.0 );
  21941. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21942. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21943. // update camera matrices and frustum
  21944. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21945. _frustum.setFromMatrix( _projScreenMatrix );
  21946. // render shadow map
  21947. _renderer.setRenderTarget( shadowMap );
  21948. _renderer.clear();
  21949. // set object matrices & frustum culling
  21950. renderList = scene.__webglObjects;
  21951. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21952. webglObject = renderList[ j ];
  21953. object = webglObject.object;
  21954. webglObject.render = false;
  21955. if ( object.visible && object.castShadow ) {
  21956. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21957. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21958. webglObject.render = true;
  21959. }
  21960. }
  21961. }
  21962. // render regular objects
  21963. var objectMaterial, useMorphing, useSkinning;
  21964. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21965. webglObject = renderList[ j ];
  21966. if ( webglObject.render ) {
  21967. object = webglObject.object;
  21968. buffer = webglObject.buffer;
  21969. // culling is overriden globally for all objects
  21970. // while rendering depth map
  21971. // need to deal with MeshFaceMaterial somehow
  21972. // in that case just use the first of material.materials for now
  21973. // (proper solution would require to break objects by materials
  21974. // similarly to regular rendering and then set corresponding
  21975. // depth materials per each chunk instead of just once per object)
  21976. objectMaterial = getObjectMaterial( object );
  21977. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21978. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21979. if ( object.customDepthMaterial ) {
  21980. material = object.customDepthMaterial;
  21981. } else if ( useSkinning ) {
  21982. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21983. } else if ( useMorphing ) {
  21984. material = _depthMaterialMorph;
  21985. } else {
  21986. material = _depthMaterial;
  21987. }
  21988. if ( buffer instanceof THREE.BufferGeometry ) {
  21989. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21990. } else {
  21991. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21992. }
  21993. }
  21994. }
  21995. // set matrices and render immediate objects
  21996. renderList = scene.__webglObjectsImmediate;
  21997. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21998. webglObject = renderList[ j ];
  21999. object = webglObject.object;
  22000. if ( object.visible && object.castShadow ) {
  22001. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  22002. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  22003. }
  22004. }
  22005. }
  22006. // restore GL state
  22007. var clearColor = _renderer.getClearColor(),
  22008. clearAlpha = _renderer.getClearAlpha();
  22009. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22010. _gl.enable( _gl.BLEND );
  22011. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  22012. _gl.cullFace( _gl.BACK );
  22013. }
  22014. };
  22015. function createVirtualLight( light, cascade ) {
  22016. var virtualLight = new THREE.DirectionalLight();
  22017. virtualLight.isVirtual = true;
  22018. virtualLight.onlyShadow = true;
  22019. virtualLight.castShadow = true;
  22020. virtualLight.shadowCameraNear = light.shadowCameraNear;
  22021. virtualLight.shadowCameraFar = light.shadowCameraFar;
  22022. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  22023. virtualLight.shadowCameraRight = light.shadowCameraRight;
  22024. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  22025. virtualLight.shadowCameraTop = light.shadowCameraTop;
  22026. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  22027. virtualLight.shadowDarkness = light.shadowDarkness;
  22028. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  22029. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  22030. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  22031. virtualLight.pointsWorld = [];
  22032. virtualLight.pointsFrustum = [];
  22033. var pointsWorld = virtualLight.pointsWorld,
  22034. pointsFrustum = virtualLight.pointsFrustum;
  22035. for ( var i = 0; i < 8; i ++ ) {
  22036. pointsWorld[ i ] = new THREE.Vector3();
  22037. pointsFrustum[ i ] = new THREE.Vector3();
  22038. }
  22039. var nearZ = light.shadowCascadeNearZ[ cascade ];
  22040. var farZ = light.shadowCascadeFarZ[ cascade ];
  22041. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  22042. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  22043. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  22044. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  22045. pointsFrustum[ 4 ].set( -1, -1, farZ );
  22046. pointsFrustum[ 5 ].set( 1, -1, farZ );
  22047. pointsFrustum[ 6 ].set( -1, 1, farZ );
  22048. pointsFrustum[ 7 ].set( 1, 1, farZ );
  22049. return virtualLight;
  22050. }
  22051. // Synchronize virtual light with the original light
  22052. function updateVirtualLight( light, cascade ) {
  22053. var virtualLight = light.shadowCascadeArray[ cascade ];
  22054. virtualLight.position.copy( light.position );
  22055. virtualLight.target.position.copy( light.target.position );
  22056. virtualLight.lookAt( virtualLight.target );
  22057. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  22058. virtualLight.shadowDarkness = light.shadowDarkness;
  22059. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  22060. var nearZ = light.shadowCascadeNearZ[ cascade ];
  22061. var farZ = light.shadowCascadeFarZ[ cascade ];
  22062. var pointsFrustum = virtualLight.pointsFrustum;
  22063. pointsFrustum[ 0 ].z = nearZ;
  22064. pointsFrustum[ 1 ].z = nearZ;
  22065. pointsFrustum[ 2 ].z = nearZ;
  22066. pointsFrustum[ 3 ].z = nearZ;
  22067. pointsFrustum[ 4 ].z = farZ;
  22068. pointsFrustum[ 5 ].z = farZ;
  22069. pointsFrustum[ 6 ].z = farZ;
  22070. pointsFrustum[ 7 ].z = farZ;
  22071. }
  22072. // Fit shadow camera's ortho frustum to camera frustum
  22073. function updateShadowCamera( camera, light ) {
  22074. var shadowCamera = light.shadowCamera,
  22075. pointsFrustum = light.pointsFrustum,
  22076. pointsWorld = light.pointsWorld;
  22077. _min.set( Infinity, Infinity, Infinity );
  22078. _max.set( -Infinity, -Infinity, -Infinity );
  22079. for ( var i = 0; i < 8; i ++ ) {
  22080. var p = pointsWorld[ i ];
  22081. p.copy( pointsFrustum[ i ] );
  22082. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  22083. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  22084. if ( p.x < _min.x ) _min.x = p.x;
  22085. if ( p.x > _max.x ) _max.x = p.x;
  22086. if ( p.y < _min.y ) _min.y = p.y;
  22087. if ( p.y > _max.y ) _max.y = p.y;
  22088. if ( p.z < _min.z ) _min.z = p.z;
  22089. if ( p.z > _max.z ) _max.z = p.z;
  22090. }
  22091. shadowCamera.left = _min.x;
  22092. shadowCamera.right = _max.x;
  22093. shadowCamera.top = _max.y;
  22094. shadowCamera.bottom = _min.y;
  22095. // can't really fit near/far
  22096. //shadowCamera.near = _min.z;
  22097. //shadowCamera.far = _max.z;
  22098. shadowCamera.updateProjectionMatrix();
  22099. }
  22100. // For the moment just ignore objects that have multiple materials with different animation methods
  22101. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  22102. function getObjectMaterial( object ) {
  22103. return object.material instanceof THREE.MeshFaceMaterial
  22104. ? object.material.materials[ 0 ]
  22105. : object.material;
  22106. };
  22107. };
  22108. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  22109. /**
  22110. * @author mikael emtinger / http://gomo.se/
  22111. * @author alteredq / http://alteredqualia.com/
  22112. */
  22113. THREE.SpritePlugin = function () {
  22114. var _gl, _renderer, _texture;
  22115. var vertices, faces, vertexBuffer, elementBuffer;
  22116. var program, attributes, uniforms;
  22117. this.init = function ( renderer ) {
  22118. _gl = renderer.context;
  22119. _renderer = renderer;
  22120. vertices = new Float32Array( [
  22121. - 0.5, - 0.5, 0, 0,
  22122. 0.5, - 0.5, 1, 0,
  22123. 0.5, 0.5, 1, 1,
  22124. - 0.5, 0.5, 0, 1
  22125. ] );
  22126. faces = new Uint16Array( [
  22127. 0, 1, 2,
  22128. 0, 2, 3
  22129. ] );
  22130. vertexBuffer = _gl.createBuffer();
  22131. elementBuffer = _gl.createBuffer();
  22132. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  22133. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  22134. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  22135. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  22136. program = createProgram();
  22137. attributes = {
  22138. position: _gl.getAttribLocation ( program, 'position' ),
  22139. uv: _gl.getAttribLocation ( program, 'uv' )
  22140. };
  22141. uniforms = {
  22142. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  22143. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  22144. rotation: _gl.getUniformLocation( program, 'rotation' ),
  22145. scale: _gl.getUniformLocation( program, 'scale' ),
  22146. color: _gl.getUniformLocation( program, 'color' ),
  22147. map: _gl.getUniformLocation( program, 'map' ),
  22148. opacity: _gl.getUniformLocation( program, 'opacity' ),
  22149. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  22150. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  22151. fogType: _gl.getUniformLocation( program, 'fogType' ),
  22152. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  22153. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  22154. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  22155. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  22156. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  22157. };
  22158. var canvas = document.createElement( 'canvas' );
  22159. canvas.width = 8;
  22160. canvas.height = 8;
  22161. var context = canvas.getContext( '2d' );
  22162. context.fillStyle = '#ffffff';
  22163. context.fillRect( 0, 0, canvas.width, canvas.height );
  22164. _texture = new THREE.Texture( canvas );
  22165. _texture.needsUpdate = true;
  22166. };
  22167. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  22168. var sprites = scene.__webglSprites,
  22169. nSprites = sprites.length;
  22170. if ( ! nSprites ) return;
  22171. // setup gl
  22172. _gl.useProgram( program );
  22173. _gl.enableVertexAttribArray( attributes.position );
  22174. _gl.enableVertexAttribArray( attributes.uv );
  22175. _gl.disable( _gl.CULL_FACE );
  22176. _gl.enable( _gl.BLEND );
  22177. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  22178. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  22179. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  22180. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  22181. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  22182. _gl.activeTexture( _gl.TEXTURE0 );
  22183. _gl.uniform1i( uniforms.map, 0 );
  22184. var oldFogType = 0;
  22185. var sceneFogType = 0;
  22186. var fog = scene.fog;
  22187. if ( fog ) {
  22188. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  22189. if ( fog instanceof THREE.Fog ) {
  22190. _gl.uniform1f( uniforms.fogNear, fog.near );
  22191. _gl.uniform1f( uniforms.fogFar, fog.far );
  22192. _gl.uniform1i( uniforms.fogType, 1 );
  22193. oldFogType = 1;
  22194. sceneFogType = 1;
  22195. } else if ( fog instanceof THREE.FogExp2 ) {
  22196. _gl.uniform1f( uniforms.fogDensity, fog.density );
  22197. _gl.uniform1i( uniforms.fogType, 2 );
  22198. oldFogType = 2;
  22199. sceneFogType = 2;
  22200. }
  22201. } else {
  22202. _gl.uniform1i( uniforms.fogType, 0 );
  22203. oldFogType = 0;
  22204. sceneFogType = 0;
  22205. }
  22206. // update positions and sort
  22207. var i, sprite, material, fogType, scale = [];
  22208. for( i = 0; i < nSprites; i ++ ) {
  22209. sprite = sprites[ i ];
  22210. material = sprite.material;
  22211. if ( sprite.visible === false ) continue;
  22212. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  22213. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  22214. }
  22215. sprites.sort( painterSortStable );
  22216. // render all sprites
  22217. for( i = 0; i < nSprites; i ++ ) {
  22218. sprite = sprites[ i ];
  22219. if ( sprite.visible === false ) continue;
  22220. material = sprite.material;
  22221. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  22222. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  22223. scale[ 0 ] = sprite.scale.x;
  22224. scale[ 1 ] = sprite.scale.y;
  22225. if ( scene.fog && material.fog ) {
  22226. fogType = sceneFogType;
  22227. } else {
  22228. fogType = 0;
  22229. }
  22230. if ( oldFogType !== fogType ) {
  22231. _gl.uniform1i( uniforms.fogType, fogType );
  22232. oldFogType = fogType;
  22233. }
  22234. if ( material.map !== null ) {
  22235. _gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  22236. _gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  22237. } else {
  22238. _gl.uniform2f( uniforms.uvOffset, 0, 0 );
  22239. _gl.uniform2f( uniforms.uvScale, 1, 1 );
  22240. }
  22241. _gl.uniform1f( uniforms.opacity, material.opacity );
  22242. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  22243. _gl.uniform1f( uniforms.rotation, material.rotation );
  22244. _gl.uniform2fv( uniforms.scale, scale );
  22245. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  22246. _renderer.setDepthTest( material.depthTest );
  22247. _renderer.setDepthWrite( material.depthWrite );
  22248. if ( material.map && material.map.image && material.map.image.width ) {
  22249. _renderer.setTexture( material.map, 0 );
  22250. } else {
  22251. _renderer.setTexture( _texture, 0 );
  22252. }
  22253. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22254. }
  22255. // restore gl
  22256. _gl.enable( _gl.CULL_FACE );
  22257. };
  22258. function createProgram () {
  22259. var program = _gl.createProgram();
  22260. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22261. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22262. _gl.shaderSource( vertexShader, [
  22263. 'precision ' + _renderer.getPrecision() + ' float;',
  22264. 'uniform mat4 modelViewMatrix;',
  22265. 'uniform mat4 projectionMatrix;',
  22266. 'uniform float rotation;',
  22267. 'uniform vec2 scale;',
  22268. 'uniform vec2 uvOffset;',
  22269. 'uniform vec2 uvScale;',
  22270. 'attribute vec2 position;',
  22271. 'attribute vec2 uv;',
  22272. 'varying vec2 vUV;',
  22273. 'void main() {',
  22274. 'vUV = uvOffset + uv * uvScale;',
  22275. 'vec2 alignedPosition = position * scale;',
  22276. 'vec2 rotatedPosition;',
  22277. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  22278. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  22279. 'vec4 finalPosition;',
  22280. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  22281. 'finalPosition.xy += rotatedPosition;',
  22282. 'finalPosition = projectionMatrix * finalPosition;',
  22283. 'gl_Position = finalPosition;',
  22284. '}'
  22285. ].join( '\n' ) );
  22286. _gl.shaderSource( fragmentShader, [
  22287. 'precision ' + _renderer.getPrecision() + ' float;',
  22288. 'uniform vec3 color;',
  22289. 'uniform sampler2D map;',
  22290. 'uniform float opacity;',
  22291. 'uniform int fogType;',
  22292. 'uniform vec3 fogColor;',
  22293. 'uniform float fogDensity;',
  22294. 'uniform float fogNear;',
  22295. 'uniform float fogFar;',
  22296. 'uniform float alphaTest;',
  22297. 'varying vec2 vUV;',
  22298. 'void main() {',
  22299. 'vec4 texture = texture2D( map, vUV );',
  22300. 'if ( texture.a < alphaTest ) discard;',
  22301. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  22302. 'if ( fogType > 0 ) {',
  22303. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  22304. 'float fogFactor = 0.0;',
  22305. 'if ( fogType == 1 ) {',
  22306. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  22307. '} else {',
  22308. 'const float LOG2 = 1.442695;',
  22309. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  22310. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  22311. '}',
  22312. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  22313. '}',
  22314. '}'
  22315. ].join( '\n' ) );
  22316. _gl.compileShader( vertexShader );
  22317. _gl.compileShader( fragmentShader );
  22318. _gl.attachShader( program, vertexShader );
  22319. _gl.attachShader( program, fragmentShader );
  22320. _gl.linkProgram( program );
  22321. return program;
  22322. };
  22323. function painterSortStable ( a, b ) {
  22324. if ( a.z !== b.z ) {
  22325. return b.z - a.z;
  22326. } else {
  22327. return b.id - a.id;
  22328. }
  22329. };
  22330. };
  22331. /**
  22332. * @author alteredq / http://alteredqualia.com/
  22333. */
  22334. THREE.DepthPassPlugin = function () {
  22335. this.enabled = false;
  22336. this.renderTarget = null;
  22337. var _gl,
  22338. _renderer,
  22339. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22340. _frustum = new THREE.Frustum(),
  22341. _projScreenMatrix = new THREE.Matrix4();
  22342. this.init = function ( renderer ) {
  22343. _gl = renderer.context;
  22344. _renderer = renderer;
  22345. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22346. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22347. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22348. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22349. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22350. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22351. _depthMaterial._shadowPass = true;
  22352. _depthMaterialMorph._shadowPass = true;
  22353. _depthMaterialSkin._shadowPass = true;
  22354. _depthMaterialMorphSkin._shadowPass = true;
  22355. };
  22356. this.render = function ( scene, camera ) {
  22357. if ( ! this.enabled ) return;
  22358. this.update( scene, camera );
  22359. };
  22360. this.update = function ( scene, camera ) {
  22361. var i, il, j, jl, n,
  22362. program, buffer, material,
  22363. webglObject, object, light,
  22364. renderList,
  22365. fog = null;
  22366. // set GL state for depth map
  22367. _gl.clearColor( 1, 1, 1, 1 );
  22368. _gl.disable( _gl.BLEND );
  22369. _renderer.setDepthTest( true );
  22370. // update scene
  22371. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22372. // update camera matrices and frustum
  22373. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  22374. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22375. _frustum.setFromMatrix( _projScreenMatrix );
  22376. // render depth map
  22377. _renderer.setRenderTarget( this.renderTarget );
  22378. _renderer.clear();
  22379. // set object matrices & frustum culling
  22380. renderList = scene.__webglObjects;
  22381. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22382. webglObject = renderList[ j ];
  22383. object = webglObject.object;
  22384. webglObject.render = false;
  22385. if ( object.visible ) {
  22386. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22387. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22388. webglObject.render = true;
  22389. }
  22390. }
  22391. }
  22392. // render regular objects
  22393. var objectMaterial, useMorphing, useSkinning;
  22394. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22395. webglObject = renderList[ j ];
  22396. if ( webglObject.render ) {
  22397. object = webglObject.object;
  22398. buffer = webglObject.buffer;
  22399. // todo: create proper depth material for particles
  22400. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  22401. objectMaterial = getObjectMaterial( object );
  22402. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  22403. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22404. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22405. if ( object.customDepthMaterial ) {
  22406. material = object.customDepthMaterial;
  22407. } else if ( useSkinning ) {
  22408. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22409. } else if ( useMorphing ) {
  22410. material = _depthMaterialMorph;
  22411. } else {
  22412. material = _depthMaterial;
  22413. }
  22414. if ( buffer instanceof THREE.BufferGeometry ) {
  22415. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22416. } else {
  22417. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22418. }
  22419. }
  22420. }
  22421. // set matrices and render immediate objects
  22422. renderList = scene.__webglObjectsImmediate;
  22423. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22424. webglObject = renderList[ j ];
  22425. object = webglObject.object;
  22426. if ( object.visible ) {
  22427. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22428. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22429. }
  22430. }
  22431. // restore GL state
  22432. var clearColor = _renderer.getClearColor(),
  22433. clearAlpha = _renderer.getClearAlpha();
  22434. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22435. _gl.enable( _gl.BLEND );
  22436. };
  22437. // For the moment just ignore objects that have multiple materials with different animation methods
  22438. // Only the first material will be taken into account for deciding which depth material to use
  22439. function getObjectMaterial( object ) {
  22440. return object.material instanceof THREE.MeshFaceMaterial
  22441. ? object.material.materials[ 0 ]
  22442. : object.material;
  22443. };
  22444. };
  22445. /**
  22446. * @author mikael emtinger / http://gomo.se/
  22447. */
  22448. THREE.ShaderFlares = {
  22449. 'lensFlareVertexTexture': {
  22450. vertexShader: [
  22451. "uniform lowp int renderType;",
  22452. "uniform vec3 screenPosition;",
  22453. "uniform vec2 scale;",
  22454. "uniform float rotation;",
  22455. "uniform sampler2D occlusionMap;",
  22456. "attribute vec2 position;",
  22457. "attribute vec2 uv;",
  22458. "varying vec2 vUV;",
  22459. "varying float vVisibility;",
  22460. "void main() {",
  22461. "vUV = uv;",
  22462. "vec2 pos = position;",
  22463. "if( renderType == 2 ) {",
  22464. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  22465. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  22466. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  22467. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  22468. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  22469. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  22470. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  22471. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  22472. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22473. "vVisibility = visibility.r / 9.0;",
  22474. "vVisibility *= 1.0 - visibility.g / 9.0;",
  22475. "vVisibility *= visibility.b / 9.0;",
  22476. "vVisibility *= 1.0 - visibility.a / 9.0;",
  22477. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22478. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22479. "}",
  22480. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22481. "}"
  22482. ].join( "\n" ),
  22483. fragmentShader: [
  22484. "uniform lowp int renderType;",
  22485. "uniform sampler2D map;",
  22486. "uniform float opacity;",
  22487. "uniform vec3 color;",
  22488. "varying vec2 vUV;",
  22489. "varying float vVisibility;",
  22490. "void main() {",
  22491. // pink square
  22492. "if( renderType == 0 ) {",
  22493. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22494. // restore
  22495. "} else if( renderType == 1 ) {",
  22496. "gl_FragColor = texture2D( map, vUV );",
  22497. // flare
  22498. "} else {",
  22499. "vec4 texture = texture2D( map, vUV );",
  22500. "texture.a *= opacity * vVisibility;",
  22501. "gl_FragColor = texture;",
  22502. "gl_FragColor.rgb *= color;",
  22503. "}",
  22504. "}"
  22505. ].join( "\n" )
  22506. },
  22507. 'lensFlare': {
  22508. vertexShader: [
  22509. "uniform lowp int renderType;",
  22510. "uniform vec3 screenPosition;",
  22511. "uniform vec2 scale;",
  22512. "uniform float rotation;",
  22513. "attribute vec2 position;",
  22514. "attribute vec2 uv;",
  22515. "varying vec2 vUV;",
  22516. "void main() {",
  22517. "vUV = uv;",
  22518. "vec2 pos = position;",
  22519. "if( renderType == 2 ) {",
  22520. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22521. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22522. "}",
  22523. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22524. "}"
  22525. ].join( "\n" ),
  22526. fragmentShader: [
  22527. "precision mediump float;",
  22528. "uniform lowp int renderType;",
  22529. "uniform sampler2D map;",
  22530. "uniform sampler2D occlusionMap;",
  22531. "uniform float opacity;",
  22532. "uniform vec3 color;",
  22533. "varying vec2 vUV;",
  22534. "void main() {",
  22535. // pink square
  22536. "if( renderType == 0 ) {",
  22537. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22538. // restore
  22539. "} else if( renderType == 1 ) {",
  22540. "gl_FragColor = texture2D( map, vUV );",
  22541. // flare
  22542. "} else {",
  22543. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  22544. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  22545. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  22546. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22547. "visibility = ( 1.0 - visibility / 4.0 );",
  22548. "vec4 texture = texture2D( map, vUV );",
  22549. "texture.a *= opacity * visibility;",
  22550. "gl_FragColor = texture;",
  22551. "gl_FragColor.rgb *= color;",
  22552. "}",
  22553. "}"
  22554. ].join( "\n" )
  22555. }
  22556. };